问:
passing list of strings in efficient way
```<code>#include <iostream>
#include <vector>
#include <string>

void function1(const char** keywords) {  // C like
    for (const char** keyword = keywords; *keyword; ++keyword) {
        std::cout << *keyword << std::endl;
    }
}

void function2(const std::vector<std::string>& keywords) {  // C++11 like
    for(const std::string& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}

int main() {
    static const char* keywords[] = { "hello", "world", "!", 0 };
    function1(keywords);
    function2({ "hello", "world", "!" });
    return 0;
}
</code>```

Both functions do the same result. I like the new c++11 format of initialization where values are inline and I can skip empty value (zero). The issue is a performance. I expect that function2 will dynamically alocate memory on each invoke. I suppose it wan't be efficient. Is there a better way to implement such function with c++ manner keeping old C efficency?

Update:

There is a little misunderstanding. My concern is usage of std::vector which provokes dynamic memory allocation. In fact I would use std::string in the body of function1 so std::string allocation is not a case. The same std::cout was added by me as an example of usage (not a real case). std::array cannot be used here becouse length of list is not fixed.

I extend my question:
Goal is use only one argument with default empty value to pass list of strings. How to achieve this in most effient and pretty-look way?

So above functions' declarations may look as follows:

```<code>void function1(const char** keywords = nullptr)

void function2(const std::vector<std::string>& keywords = {})
</code>```

Here I see the next problem. Invoking function1 without parameter cost nothing but I expect empty vector initialization in function2. Am I right?

答:
There is 2 difficulties:
const char* versus std::string (or even std::string_view in C++17)

and the collection of the above type.

as Container<const char*>, Container<std::string> and Container<std::string_view> are different types which will require conversion to pass from one to another.

To avoid those difficulties, you might use template:

```<code>template <typename StringContainer>
void function3(const StringContainer& keywords) {
    for(const auto& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}
</code>```

but you cannot then use

```<code>function3({ "hello", "world", "!" });
</code>```

as {/*..*/} has no type. It can though match C-array or initializer_list template.

So, you might add extra overload to handle that case:

```<code>template <typename String>
void function3(std::initializer_list<String> keywords) {
    return function3<std::initializer_list<String>>(keywords);
}
</code>```

and to handle empty initializer_list, or default argument, you might do:

```<code>template <typename String = std::string>
void function3(std::initializer_list<String> keywords = {}) {
    return function3<std::initializer_list<String>>(keywords);
}
</code>```

Demo

Body:
#include <iostream>
#include <vector>
#include <string>

void function1(const char** keywords) {  // C like
    for (const char** keyword = keywords; *keyword; ++keyword) {
        std::cout << *keyword << std::endl;
    }
}

void function2(const std::vector<std::string>& keywords) {  // C++11 like
    for(const std::string& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}

int main() {
    static const char* keywords[] = { "hello", "world", "!", 0 };
    function1(keywords);
    function2({ "hello", "world", "!" });
    return 0;
}

Both functions do the same result. I like the new c++11 format of initialization where values are inline and I can skip empty value (zero). The issue is a performance. I expect that function2 will dynamically alocate memory on each invoke. I suppose it wan't be efficient. Is there a better way to implement such function with c++ manner keeping old C efficency?

Update:

There is a little misunderstanding. My concern is usage of std::vector which provokes dynamic memory allocation. In fact I would use std::string in the body of function1 so std::string allocation is not a case. The same std::cout was added by me as an example of usage (not a real case). std::array cannot be used here becouse length of list is not fixed.

I extend my question:
Goal is use only one argument with default empty value to pass list of strings. How to achieve this in most effient and pretty-look way?

So above functions' declarations may look as follows:

void function1(const char** keywords = nullptr)

void function2(const std::vector<std::string>& keywords = {})

Here I see the next problem. Invoking function1 without parameter cost nothing but I expect empty vector initialization in function2. Am I right?

Body:
There is 2 difficulties:
const char* versus std::string (or even std::string_view in C++17)

and the collection of the above type.

as Container<const char*>, Container<std::string> and Container<std::string_view> are different types which will require conversion to pass from one to another.

To avoid those difficulties, you might use template:

template <typename StringContainer>
void function3(const StringContainer& keywords) {
    for(const auto& keyword : keywords) {
        std::cout << keyword << std::endl;
    }
}

but you cannot then use

function3({ "hello", "world", "!" });

as {/*..*/} has no type. It can though match C-array or initializer_list template.

So, you might add extra overload to handle that case:

template <typename String>
void function3(std::initializer_list<String> keywords) {
    return function3<std::initializer_list<String>>(keywords);
}

and to handle empty initializer_list, or default argument, you might do:

template <typename String = std::string>
void function3(std::initializer_list<String> keywords = {}) {
    return function3<std::initializer_list<String>>(keywords);
}

Demo


来源: stackexchange

问:
After Transaction is finished, we are returning object as null
I am working on the code which is calling, transaction after transaction.

```<code>@Asynchronous
@TransactionTimeout(value = 12, unit = TimeUnit.HOURS)
public void runExport(Long id) {
    /*
    *   some stuff that takes time
    */

    em.persist(objectTest);
    manager.runAnotherTransaction(id);
}

@Asynchronous
@TransactionTimeout(value = 1, unit = TimeUnit.HOURS)
public void runCopy(Long id) {
    if(manager.isPreviousValueCommited(id)){
        //do some stuff
    }
    /*
    *   some stuff that takes time
    */

}

//other class
public void runAnotherTransaction(long id){
    //...
    superBean.runCopy(id);
}

public void isPreviousValueCommited(long id){
    //Thread.sleep(1000) if we sleep here, object wont be null
    SomeObject obj = em.find(SomeObject.class, id); //is null,
}
</code>```

As you can see in code, first transaction method is persisting object, and after that we are calling other method via some kind of manager, and second transaction want to check some stuff on the previously commited object. But as you probably suspect it cant, because object does not exist in database (first transaction was not able to save it before we ask db). When I give some sleep before finding this object everything is ok.

This sample code is pretty simple, and it is probably make sense to not pass id, but object itself(true?) to avoid this problem, but I have question. But I would like to listen another ideas or pros/cons(possibly there is much more cons) of this approach of connecting Transaction as I have in example.

答:
Using em.persist() you definitly do not commit any data. And most of the times you do even not write any data to database.

Your data is committed automatically by the container after the call of an EJB-Method. So after runExport the data will commit. Before that the container will also flush the data to database.

You can do that programmatically as well using em.flush(). But again, this will not commit your data, just write it.

If your really want to control the transaction by yourself, you have to use @TransactionManagement(TransactionManagementType.BEAN). The Interface javax.transaction.UserTransaction defines the methods you need.

ContentLicense: CC BY-SA 4.0

Body:
I am working on the code which is calling, transaction after transaction.

@Asynchronous
@TransactionTimeout(value = 12, unit = TimeUnit.HOURS)
public void runExport(Long id) {
    /*
    *   some stuff that takes time
    */

    em.persist(objectTest);
    manager.runAnotherTransaction(id);
}

@Asynchronous
@TransactionTimeout(value = 1, unit = TimeUnit.HOURS)
public void runCopy(Long id) {
    if(manager.isPreviousValueCommited(id)){
        //do some stuff
    }
    /*
    *   some stuff that takes time
    */

}

//other class
public void runAnotherTransaction(long id){
    //...
    superBean.runCopy(id);
}

public void isPreviousValueCommited(long id){
    //Thread.sleep(1000) if we sleep here, object wont be null
    SomeObject obj = em.find(SomeObject.class, id); //is null,
}

As you can see in code, first transaction method is persisting object, and after that we are calling other method via some kind of manager, and second transaction want to check some stuff on the previously commited object. But as you probably suspect it cant, because object does not exist in database (first transaction was not able to save it before we ask db). When I give some sleep before finding this object everything is ok.

This sample code is pretty simple, and it is probably make sense to not pass id, but object itself(true?) to avoid this problem, but I have question. But I would like to listen another ideas or pros/cons(possibly there is much more cons) of this approach of connecting Transaction as I have in example.


问:
Translate a MySql query in a Laravel query builder
```<code>SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC
</code>```

how can I Translate this  MySql query in a Laravel query builder ?

答:
Check Laravel docs on query builder and see the examples, you can easily convert your SQL to query builder:

use Illuminate\Support\Facades\DB;

DB::table('views')
    ->selectRaw("apartment_id, COUNT(created_at) AS n_view, DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
    ->where('apartment_id', '=', 36)
    ->groupBy('day_view')
    ->orderByRaw('COUNT(created_at) DESC')
    ->get();
```

Body:
SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC

how can I Translate this  MySql query in a Laravel query builder ?


问:
convert text to decimal(16,2) in postgres
I have bytea datatype for file data in my table, I can get file size in MB by using below query in postgres.

```<code>select concat(length('0x546573742044617461') / 1048576.0)
</code>```

Output of above query is 0.000019073486328125000000 but i want to display 0.00 not whole string, now i want to convert into decimal(16,2)

Now I want to display only 2 decimals values.

Example:
if file size is 1.446119073486328125000000 then output will be 1.45

if file size is 1.12379073486300 then output will be 1.12

Equivalent MS-Sql server query is:

```<code>select CAST(CAST(CONVERT(NVARCHAR(50),DATALENGTH(0x546573742044617461)/ 1048576.0 ) as decimal(16,2)) as NVARCHAR(50))
</code>```

Could you please help me on this.

Thanks,

答:
If you want the number, then concat() makes no sense. Use round() to round the result of the division.

```<code>select round(length('0x546573742044617461') / 1048576.0, 2)
</code>```

Body:
I have bytea datatype for file data in my table, I can get file size in MB by using below query in postgres.

select concat(length('0x546573742044617461') / 1048576.0)

Output of above query is 0.000019073486328125000000 but i want to display 0.00 not whole string, now i want to convert into decimal(16,2)

Now I want to display only 2 decimals values.

Example:
if file size is 1.446119073486328125000000 then output will be 1.45

if file size is 1.12379073486300 then output will be 1.12

Equivalent MS-Sql server query is:

select CAST(CAST(CONVERT(NVARCHAR(50),DATALENGTH(0x546573742044617461)/ 1048576.0 ) as decimal(16,2)) as NVARCHAR(50))

Could you please help me on this.

Thanks,

Body:
If you want the number, then concat() makes no sense. Use round() to round the result of the division.

select round(length('0x546573742044617461') / 1048576.0, 2)


问:
I am using flutter bottomNavigatonBar widget, Is there anything which it can be raised?
This is what I want !

```<code>        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.add),
        ),
        bottomNavigationBar: BottomAppBar(
          shape: CircularNotchedRectangle(),
          notchMargin: 4.0,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.home),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.search),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.notifications),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.perm_identity),
                onPressed: () {},
              ),
            ],
          ),
        ),
</code>```

I want the Nav bar to be slightly raised from the bottom and have rounded border. Currently it's sitting in the bottom of the screen.

答:
Here is what you want. However, I suggest you not to use IconButton but FlatButton instead as they're much simpler to work with and IconButton's width and height cannot be overridden as far as I know so when you press on your IconButton with the container wrapped by it, it will look very off.

But for your solution, wrap your IconButton with a container and use the decoration property to add a shadow and give a raised effect.

```<code>
    Container(
      width: 100,
      decoration : BoxDecoration(
        borderRadius: BorderRadius.circular(30),
        color: Colors.red,
        boxShadow: [
          BoxShadow(color: Colors.black, blurRadius: 2, offset: Offset(5,5))

        ]

      ),
      child: IconButton(
        color: Colors.green,
        icon : Icon(Icons.access_alarm),
        onPressed : (){
          //
        }
      ),
    )
</code>```

This is the output:

You can change the offset property to adjust the direction of the shadow.

Body:
This is what I want !

        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.add),
        ),
        bottomNavigationBar: BottomAppBar(
          shape: CircularNotchedRectangle(),
          notchMargin: 4.0,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.home),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.search),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.notifications),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.perm_identity),
                onPressed: () {},
              ),
            ],
          ),
        ),

I want the Nav bar to be slightly raised from the bottom and have rounded border. Currently it's sitting in the bottom of the screen.

Body:
Here is what you want. However, I suggest you not to use IconButton but FlatButton instead as they're much simpler to work with and IconButton's width and height cannot be overridden as far as I know so when you press on your IconButton with the container wrapped by it, it will look very off.

But for your solution, wrap your IconButton with a container and use the decoration property to add a shadow and give a raised effect.

    Container(
      width: 100,
      decoration : BoxDecoration(
        borderRadius: BorderRadius.circular(30),
        color: Colors.red,
        boxShadow: [
          BoxShadow(color: Colors.black, blurRadius: 2, offset: Offset(5,5))

        ]

      ),
      child: IconButton(
        color: Colors.green,
        icon : Icon(Icons.access_alarm),
        onPressed : (){
          //
        }
      ),
    )

This is the output:

You can change the offset property to adjust the direction of the shadow.


问:
Merge multiple SQL Server tables into one
I have many SQL Server tables in a database that have information about the same domain (same columns) and their names are the same plus a date suffix (yyyyMMdd):

TABLE_ABOUT_THIS_THING_20200131

TABLE_ABOUT_THIS_THING_20191231

TABLE_ABOUT_THIS_THING_20191130

TABLE_ABOUT_THIS_THING_20191031

TABLE_ABOUT_THIS_THING_20190930

TABLE_ABOUT_THIS_THING_20190831

...

This seems like it would make more sense if it was all in the same table. Is there a way, using a query/SSIS or something similar, to merge this tables into one (TABLE_ABOUT_THIS_THING) with a new column (extraction_date) made out of the current table suffix?

答:
You can use UNION ALL:

```<code>create view v_about_this_thing as
    select convert(date, '20200131') as extraction_date t.*
    from TABLE_ABOUT_THIS_THING_20200131
    union all
    select convert(date, '20201912') as extraction_date t.*
    from TABLE_ABOUT_THIS_THING_20191231
    union all
    . . .
</code>```

This happens to be a partitioned view, which has some other benefits.

The challenge is how to keep this up-to-date.  My recommendation is to fix your data processing so all the data goes into a single table.  You can also set up a job that runs once a month and inserts the most recent values into an existing table.

An alternative is to reconstruct the view every month or periodically.  You can do this using a DDL trigger that recreates the view when the new table appears.

Another alternative is to create a year's worth of tables all at once -- but empty -- and to create the view manually once a year.  But a note on your calendar to remind you!

Body:
You can use UNION ALL:

create view v_about_this_thing as
    select convert(date, '20200131') as extraction_date t.*
    from TABLE_ABOUT_THIS_THING_20200131
    union all
    select convert(date, '20201912') as extraction_date t.*
    from TABLE_ABOUT_THIS_THING_20191231
    union all
    . . .

This happens to be a partitioned view, which has some other benefits.

The challenge is how to keep this up-to-date.  My recommendation is to fix your data processing so all the data goes into a single table.  You can also set up a job that runs once a month and inserts the most recent values into an existing table.

An alternative is to reconstruct the view every month or periodically.  You can do this using a DDL trigger that recreates the view when the new table appears.

Another alternative is to create a year's worth of tables all at once -- but empty -- and to create the view manually once a year.  But a note on your calendar to remind you!


问:
How to create/update a LastModified field in EF Code First
I want to add a column that stores the current DateTime when a record is saved to disk. What would be the best way to accomplish this?

I know it's not a very complex problem, but I wondered if there is any best practice or any feature of EF that would simplify the task.
For example:

Is there any way to include the logic for this field inside the table Class, so that it's automatically updated whenever it's saved to disk?

Is there any event to capture when an object is modified or saved?

答:
Unfortunatly there are no events which you can subscribe to. My recommendation is to override the SaveChanges method in your context and do your custom logic there (if  you want to keep it clean, you can expose your own events)

EDIT

One solution i picked for this was to let all my entities inherit from a common base class (e.g. EntityBase) which exposes the methods BeforeSave() and AfterSave() which you can call in your custom DbContext when overriding the SaveChanges method ( look at the ChangeTracker for all modified entries )

ContentLicense: CC BY-SA 3.0


问:
Using facet_grid to plot multiple spatial polygons with common polygon as overlay
I want to plot spatial data from a SpatialPolygonDataframe. More specifically I want to plot single spatial features in single subplots using facet_grid() of ggplot2. In addition I'd like to plot a common spatial polygon as overlay in each of the facets.

Here an example using a spatial dataset of the USA and its single states. Each state (of the subset) should be displayed in a single facet) while the outline of the USA (provided in another spatial dataset) should be plotted as overlay in each facet. With my current attempt, also the USA outline is split (based on ID) and spread across the facets:

```<code>library(sf)
library(ggplot2)

usa <- as(st_as_sf(maps::map(database="usa",fill=T, plot =FALSE)),"Spatial")
usa_states <- as(st_as_sf(maps::map(database="state",fill=T, plot =FALSE)),"Spatial")
usa_states <- usa_states[c(1:5),]

ggplot(data=usa_states)+
  geom_polygon(data=usa, aes(x = long, y = lat,group=id),
               size = 1, colour = "red",fill=NA)+
  geom_polygon(data=usa_states, aes(x = long, y = lat,group=id),
               size = 0.3, fill = "green",color="black",alpha=0.2)+
  facet_grid(facets= id ~.)
</code>```

How can I specify that fact_grid only considers 'id' of the usa_states dataset and does not split up the usa outline?

答:
Here is the solution. There's no need to transform sf to sp. You can use geom_sf function. The problem was because your id values are have the same names in both datasets.

```<code>library(sf)
library(ggplot2)
library(dplyr)

usa <- st_as_sf(maps::map(database="usa",fill=T, plot =FALSE))
usa_states <- st_as_sf(maps::map(database="state",fill=T, plot =FALSE))
usa_states <- usa_states[c(1:5),]

usa_states <- usa_states %>%
  rename(id = ID)

ggplot(data = usa_states)+
  geom_sf(size = 0.3, fill = "green",color="black",alpha=0.2)+
  geom_sf(data = usa ,
               size = 1, colour = "red",fill=NA) +
  facet_wrap(~ id)
</code>```

Body:
I want to plot spatial data from a SpatialPolygonDataframe. More specifically I want to plot single spatial features in single subplots using facet_grid() of ggplot2. In addition I'd like to plot a common spatial polygon as overlay in each of the facets.

Here an example using a spatial dataset of the USA and its single states. Each state (of the subset) should be displayed in a single facet) while the outline of the USA (provided in another spatial dataset) should be plotted as overlay in each facet. With my current attempt, also the USA outline is split (based on ID) and spread across the facets:

library(sf)
library(ggplot2)

usa <- as(st_as_sf(maps::map(database="usa",fill=T, plot =FALSE)),"Spatial")
usa_states <- as(st_as_sf(maps::map(database="state",fill=T, plot =FALSE)),"Spatial")
usa_states <- usa_states[c(1:5),]

ggplot(data=usa_states)+
  geom_polygon(data=usa, aes(x = long, y = lat,group=id),
               size = 1, colour = "red",fill=NA)+
  geom_polygon(data=usa_states, aes(x = long, y = lat,group=id),
               size = 0.3, fill = "green",color="black",alpha=0.2)+
  facet_grid(facets= id ~.)

How can I specify that fact_grid only considers 'id' of the usa_states dataset and does not split up the usa outline?

Body:
Here is the solution. There's no need to transform sf to sp. You can use geom_sf function. The problem was because your id values are have the same names in both datasets.

library(sf)
library(ggplot2)
library(dplyr)

usa <- st_as_sf(maps::map(database="usa",fill=T, plot =FALSE))
usa_states <- st_as_sf(maps::map(database="state",fill=T, plot =FALSE))
usa_states <- usa_states[c(1:5),]

usa_states <- usa_states %>%
  rename(id = ID)

ggplot(data = usa_states)+
  geom_sf(size = 0.3, fill = "green",color="black",alpha=0.2)+
  geom_sf(data = usa ,
               size = 1, colour = "red",fill=NA) +
  facet_wrap(~ id)


问:
Socket IO date becomes string
I try to emit a date from server to client although on client side the date becomes string and I have to always use new Date() on the string to convert it to date again.

Moreover, when I send an event through socket from client to server and then server returns date to client via callback it's also becomes a string.

And it works for both side, i.e. when I send date from client to server it also becomes string on server side.

Is there a way to avoid converting and use it as a date right away?

答:
No. If you send data over the network, you'll have to serialize it. It is here automatically converted as a string, but nothing forbids you to transform it in whatever other format you'd like first, and do the opposite on the other end. Without too much hassle, you can pretty much send anything convertible into a JSON.

What happens is that for the transfer to happen, any data you want to send has to be serialized. The method of choice for socket.io (and JS in general) is to use the JSON standard.

Anything you send will first be transformed into JSON, which can only store a very limited range of elements. Anything will be transformed in either a primitive type like string or number, or in the only two non-primitive types that JSON supports, which are objects and arrays.

So pretty much anything that's not primitive and not an array will be converted into an object, only keeping serializable properties. That's done by calling the toJSON property of the data you want to send. In your case, the toJSON method of a Date returns his string representation, and that's what gets sent in the end.

const date = new Date();    // Your date
console.log(date.toJSON()); // What will be sent```

Title: Socket IO date becomes string


问:
UIPicker and Text Field
I have the same kind of question as this person
How to Sync selected row of UIPicker with previously entered data

I want the picker to load with info from a text field in another tab. I'll explain.

I have a doctor tab where the user fills in all the info about their doctor or add from contacts. In another tab where they need to reference a doctor, instead of asking them to type in the same info I figure just use a picker.

But I would like to know if creating a NSMutableArray in the init, using -viewDidLoad: and then of course dealloc is just as sufficient as iterating. And should I have a separate class for the picker and just reference it?

Hope my question makes sense. Thanks in advance!

I apologize, I forgot to add I'm using Core Data if that makes a difference at all. But thanks to iamsult and the69geeks for the answers, I'll considering both.

答: I would suggest best way is to keep a shared NSMutableArray in AppDelegate, fill it from the UITextField and use it in UIPicker.

Title: UIPicker and Text Field


问:
add HyperLink to  in table with javascript
How can I add an hyperlink to a  in a dynamic table?

I need the 1st  to be an hyperlink to a url + cell value.

Table dynamic creation :

for (var i = 0; i < riskData.length; i++) {
  $("#grdDemo3").append("
" + riskData[i].r_id +
    "	" + riskData[i].r_team + "
");
}
```

答:
Try this

```<code>for (var i = 0; i < riskData.length; i++) {
   $("#grdDemo3").append("<tr><td><a href='https://a.com/"+riskData[i].r_id +"'>" +riskData[i].r_id + "</a></td><td>" + riskData[i].r_team + "</td></tr>");

 }
</code>```

OR

```<code>for (var i = 0; i < riskData.length; i++) {
   $("#grdDemo3").append("<tr><td onclick='window.location.href=\"htts://a.com/"+riskData[i].r_id +"\"'>" +riskData[i].r_id + "</td><td>" + riskData[i].r_team + "</td></tr>");

 }
</code>```

Title: add HyperLink to <td> in table with javascript

Body:
Try this

for (var i = 0; i < riskData.length; i++) {
   $("#grdDemo3").append("<tr><td><a href='https://a.com/"+riskData[i].r_id +"'>" +riskData[i].r_id + "</a></td><td>" + riskData[i].r_team + "</td></tr>");

 }

OR

for (var i = 0; i < riskData.length; i++) {
   $("#grdDemo3").append("<tr><td onclick='window.location.href=\"htts://a.com/"+riskData[i].r_id +"\"'>" +riskData[i].r_id + "</td><td>" + riskData[i].r_team + "</td></tr>");

 }


问:
check for specific key and value pairs in two dictionaries (both dictionary has same key and value pairs)
I have two dictionaries that have the same key and value pairs. I want to compare only the specific key-value pairs and return true.
I am new to python, Please help me to write a function for the same.

The dictionaries are

```<code>A: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}
B: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}
</code>```

Here I want to check if the 'start1', 'end1', 'start2' and 'end2' values are the same are not.

答:
```<code>result = all( A[k]==B[k] for k in ('start1', 'end1', 'start2', 'end2'))
</code>```

Body:
I have two dictionaries that have the same key and value pairs. I want to compare only the specific key-value pairs and return true.
I am new to python, Please help me to write a function for the same.

The dictionaries are

A: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}
B: {'id1': 'target', 'start1': '39', 'end1': '45', \
    'id2': 'query', 'start2': '98', 'end2': '104'}

Here I want to check if the 'start1', 'end1', 'start2' and 'end2' values are the same are not.


问:
Angular Nested subscribe call
I have an Ionic app and trying to implement Login module for this using PHP REST and JWT.

1) User types credentials and api returns with token

2) Storing token in capacitor storage and intercept next http request and add token in header

3) Make call back to api and get logged in user info

4) Store info in capacitor storage and proceed further.

Following is the code.

```<code>loginAction() {
    if (this.validateInputs()) {
        console.log(this.postData);
        this.authService.login(this.postData).subscribe(
            (res: any) => {
                console.log(res);
                if (res.token) {
                    this.storageService.store('accessToken', res.token);
                    this.authService.getUserProfile().subscribe((profile: any) => {
                        console.log(profile);
                        this.storageService
                            .store(AuthConstants.AUTH, profile)
                            .then(res => {
                                this.router.navigate(['home']);
                            });
                    });
                }
            },
            (error: any) => {
                this.toastService.presentToast('Network Issue.');
            }
        );
    } else {
        this.toastService.presentToast(
            'Please enter email/username or password.'
        );
    }
}
</code>```

The only problem I am having is with the capacitor and nested subscribe call.

Sometimes execution to get the profile is quick and intercept returns with null value for accessToken.

How can I make sure that second http call is only executed after the accessToken is stored properly?

```<code>export class StorageService {
  constructor() {}

  // Store the value
  async store(storageKey: string, value: any) {
    const encryptedValue = btoa(escape(JSON.stringify(value)));
    await Storage.set({
      key: storageKey,
      value: encryptedValue
    });
  }
}
</code>```

Thank you

答:
I usually use switchMap to deal with nested subscribes. Try:

```<code>loginAction() {
  if (this.validateInputs()) {
    console.log(this.postData());
    this.authService.login(this.postData).pipe(
      // switch context from this observable to another observable based on its value
      switchMap((res: any) => {
        console.log(res);
        if (res.token) {
          this.storageService.store('accessToken', res.token);
          return this.authService.getUserProfile();
        } else {
          return of(null); // import of from rxjs
        }
      }),
      filter((profile: any) => !!filter), // don't include the null emissions in the subscribe block
    ).subscribe((profile: any) => {
      console.log(profile);
      this.storageService.store(AuthConstants.AUTH, profile)
          .then(res => {
            this.router.navigate(['home']);
           });
   },
     // can also handle errors using the catchError operator.
     (error: any) => this.toastService.presentToast('Network Issue.');
   );
  } else {
    this.toastService.presentToast('Please enter email/username or password.');
  }
}
</code>```

Title: Angular Nested subscribe call

Body:
I have an Ionic app and trying to implement Login module for this using PHP REST and JWT.

1) User types credentials and api returns with token

2) Storing token in capacitor storage and intercept next http request and add token in header

3) Make call back to api and get logged in user info

4) Store info in capacitor storage and proceed further.

Following is the code.

loginAction() {
    if (this.validateInputs()) {
        console.log(this.postData);
        this.authService.login(this.postData).subscribe(
            (res: any) => {
                console.log(res);
                if (res.token) {
                    this.storageService.store('accessToken', res.token);
                    this.authService.getUserProfile().subscribe((profile: any) => {
                        console.log(profile);
                        this.storageService
                            .store(AuthConstants.AUTH, profile)
                            .then(res => {
                                this.router.navigate(['home']);
                            });
                    });
                }
            },
            (error: any) => {
                this.toastService.presentToast('Network Issue.');
            }
        );
    } else {
        this.toastService.presentToast(
            'Please enter email/username or password.'
        );
    }
}

The only problem I am having is with the capacitor and nested subscribe call.

Sometimes execution to get the profile is quick and intercept returns with null value for accessToken.

How can I make sure that second http call is only executed after the accessToken is stored properly?

export class StorageService {
  constructor() {}

  // Store the value
  async store(storageKey: string, value: any) {
    const encryptedValue = btoa(escape(JSON.stringify(value)));
    await Storage.set({
      key: storageKey,
      value: encryptedValue
    });
  }
}

Thank you

Body:
I usually use switchMap to deal with nested subscribes. Try:

loginAction() {
  if (this.validateInputs()) {
    console.log(this.postData());
    this.authService.login(this.postData).pipe(
      // switch context from this observable to another observable based on its value
      switchMap((res: any) => {
        console.log(res);
        if (res.token) {
          this.storageService.store('accessToken', res.token);
          return this.authService.getUserProfile();
        } else {
          return of(null); // import of from rxjs
        }
      }),
      filter((profile: any) => !!filter), // don't include the null emissions in the subscribe block
    ).subscribe((profile: any) => {
      console.log(profile);
      this.storageService.store(AuthConstants.AUTH, profile)
          .then(res => {
            this.router.navigate(['home']);
           });
   },
     // can also handle errors using the catchError operator.
     (error: any) => this.toastService.presentToast('Network Issue.');
   );
  } else {
    this.toastService.presentToast('Please enter email/username or password.');
  }
}


问:
minikube install package using toolbox but the container does not internet conexion
I'm wondering how can install a package inside the minikube VM. I need some tools.
I have tried the /bin/toolbox container, but It does not have internet conexion.

```<code>[root@docker-fedora-24 ~]# dnf update --verbose
cachedir: /var/cache/dnf
DNF version: 1.1.9
Cannot download 'https://mirrors.fedoraproject.org/metalink?repo=updates-released-f24&arch=x86_64': Cannot prepare internal mirrorlist: Curl error (6): Couldn't resolve host name for https://mirrors.fedoraproject.org/metalink?repo=updates-released-f24&arch=x86_64 [Could not resolve host: mirrors.fedoraproject.org].
Error: Failed to synchronize cache for repo 'updates'
</code>```

I have tried the same toolbox script in my computer and it is properly working.

What configuration parameters I'm missing in minikube or systemd-nspaw?
Or how can I cook a customized minikube VM?

Thanks a lot

答:
I had a similar problem when I wanted to use tcpdump in the minikube VM.
I ended up using minikube mount SRC-dir:DST-dir to mount the host folder inside the VM and copying the tcpdump binary along with dependent libs (libcrypto and libpcap) to the mount point.
Then I executed tcpdump from the minikube VM and it worked.

Note: My host arch and the minikube VM arch (x86_64) was the same.
Note also: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:DST-dir has to be done.

Body:
I'm wondering how can install a package inside the minikube VM. I need some tools.
I have tried the /bin/toolbox container, but It does not have internet conexion.

[root@docker-fedora-24 ~]# dnf update --verbose
cachedir: /var/cache/dnf
DNF version: 1.1.9
Cannot download 'https://mirrors.fedoraproject.org/metalink?repo=updates-released-f24&arch=x86_64': Cannot prepare internal mirrorlist: Curl error (6): Couldn't resolve host name for https://mirrors.fedoraproject.org/metalink?repo=updates-released-f24&arch=x86_64 [Could not resolve host: mirrors.fedoraproject.org].
Error: Failed to synchronize cache for repo 'updates'

I have tried the same toolbox script in my computer and it is properly working.

What configuration parameters I'm missing in minikube or systemd-nspaw?
Or how can I cook a customized minikube VM?

Thanks a lot


问:
Creating a new empty branch for a new project
We are using a git repository to store our project. We have our branches departing from the original branch. But now we want to create a small new project to track some documentation. For that we would want to create a new empty branch to start storing our files, and I would want other users of the network to clone that branch.

How can we do that?

I tried some things, but they didn't work.

```<code>$ mkdir proj_doc; cd proj_doc
$ git init
$ git add .
$ git commit -m 'first commit'
$ git br proj_doc
$ git co proj_doc
$ git br -d master
$ git push origin proj_doc
</code>```

It seems to push the branch ok, but when I do a fetch or pull, it downloads information from other branches, and then I also get some extra files from other projects. What's the best solution?

答:
On base this answer from Hiery Nomus.

You can create a branch as an orphan:

```<code>git checkout --orphan <branchname>
</code>```

This will create a new branch with no parents. Then, you can clear the working directory with:

```<code>git rm --cached -r .
</code>```

And then you just commit branch with empty commit and then push

```<code>git commit -m <commit message> --allow-empty
git push origin <newbranch>
</code>```

Body:
We are using a git repository to store our project. We have our branches departing from the original branch. But now we want to create a small new project to track some documentation. For that we would want to create a new empty branch to start storing our files, and I would want other users of the network to clone that branch.

How can we do that?

I tried some things, but they didn't work.

$ mkdir proj_doc; cd proj_doc
$ git init
$ git add .
$ git commit -m 'first commit'
$ git br proj_doc
$ git co proj_doc
$ git br -d master
$ git push origin proj_doc

It seems to push the branch ok, but when I do a fetch or pull, it downloads information from other branches, and then I also get some extra files from other projects. What's the best solution?

Body:
On base this answer from Hiery Nomus.

You can create a branch as an orphan:

git checkout --orphan <branchname>

This will create a new branch with no parents. Then, you can clear the working directory with:

git rm --cached -r .

And then you just commit branch with empty commit and then push

git commit -m <commit message> --allow-empty
git push origin <newbranch>


问:
how to assign variable in json in restrequest c#
Here is my code.Everything works fine when I hard code message attribute in the json. I want to assign variable in 'message' attribute of the json. </p>

```<code>var client = new RestClient("172.16.255.254:2016/settings");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"c3BlZWQgZXhjZWVkZWQh\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
</code>```

答:
Short and ugly answer :

You can concate your JSON string along with your variable, such as

```<code>var MyValue = "bar";
var json = "{\"foo\":\"" + MyValue + "\"}"; // {"foo":"bar"}
</code>```

Long and better (IMHO) way

Do not directly write JSON strings ! Do you notice how unreadable it is ? You can instead create anonymous objects and serialize them, using, in example, json.net :

```<code>var MyValue = "bar";
var MyObject = new
{
    foo = MyValue
};
// using Newtonsoft.Json; // <--- taken from the nugget package newtonsoft.json
var json = JsonConvert.SerializeObject(MyObject, Formatting.Indented);
Console.WriteLine(json);
</code>```

This outputs :

```<code>{
  "foo": "bar"
}
</code>```

Body:
Here is my code.Everything works fine when I hard code message attribute in the json. I want to assign variable in 'message' attribute of the json.

var client = new RestClient("172.16.255.254:2016/settings");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n\r\n\"_id\":
\"98e8d3cd47fad6ce8e3f7b8d42cb4d9b\",\r\n\r\n\"_type\":
\"SetRealtimeMessage\" ,\r\n\r\n\"message\": \"c3BlZWQgZXhjZWVkZWQh\",
\r\n\"width\":240,\r\n\"fontBackground\":0,\r\n\"fontColor\":
0xFFFFBF00,\r\n//\"fontColor\": 0XFFBF00,\r\n\"fontSize\":
24,\r\n\r\n\"lineSpace\": 0,\r\n\r\n\"left\": 0,
\r\n\r\n\"windowBackground\": 0, \r\n\r\n\"verticalPos\": 0,
\r\n\r\n\"horizontalPos\": 0, \r\n\r\n\r\n\"showType\": 0, \r\n\"speed\": 20,
\r\n\r\n\"moveCount\": 1,\r\n\r\n\r\n\"residenceTime\": -1\r\n\r\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Body:
Short and ugly answer :

You can concate your JSON string along with your variable, such as

var MyValue = "bar";
var json = "{\"foo\":\"" + MyValue + "\"}"; // {"foo":"bar"}

Long and better (IMHO) way

Do not directly write JSON strings ! Do you notice how unreadable it is ? You can instead create anonymous objects and serialize them, using, in example, json.net :

var MyValue = "bar";
var MyObject = new
{
    foo = MyValue
};
// using Newtonsoft.Json; // <--- taken from the nugget package newtonsoft.json
var json = JsonConvert.SerializeObject(MyObject, Formatting.Indented);
Console.WriteLine(json);

This outputs :

{
  "foo": "bar"
}


问:
Python Script to get multi table counts
I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.

Expected Output:

```<code>('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])
</code>```

Script:

```<code>import psycopg2

# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()

sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    result = cursor.fetchall()
    print('Counts:',result)

conn.close()
</code>```

Current output:

```<code>[root@pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])
</code>```

Any help is appreciated.

Thanks!

答:
I am a bit reluctant to show this way, because best practices recommend to never build a dynamic SQL string but always use a constant string and parameters, but this is one use case where computing the string is legit:

a table name cannot be a parameter in SQL

the input only comes from the program itself and is fully mastered

Possible code:

```<code>sql = """SELECT count(*) from appuser.{}"""
tables = ['oltptransactions', 'oltpcases']

for t in tables:
    cursor.execute(sql.format(t))
    result = cursor.fetchall()
    print("('", t, "':,", result, ")")
</code>```

Title: Python Script to get multi table counts

Body:
I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.

Expected Output:

('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])

Script:

import psycopg2

# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()

sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    result = cursor.fetchall()
    print('Counts:',result)

conn.close()

Current output:

[root@pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])

Any help is appreciated.

Thanks!

Body:
I am a bit reluctant to show this way, because best practices recommend to never build a dynamic SQL string but always use a constant string and parameters, but this is one use case where computing the string is legit:

a table name cannot be a parameter in SQL

the input only comes from the program itself and is fully mastered

Possible code:

sql = """SELECT count(*) from appuser.{}"""
tables = ['oltptransactions', 'oltpcases']

for t in tables:
    cursor.execute(sql.format(t))
    result = cursor.fetchall()
    print("('", t, "':,", result, ")")


问:
Finding the last occurrence of a string in a sentence in C
I am practicing and I came across an exercise. The exercise says I am to manually write a function that finds the index of the last occurrence in a string. Now, I get that this has maybe been asked before but I cannot find what is the problem with my code. It works for almost all instances, but not so when the last occurrence of the word is at the beginning of the string.

What I have tried: I used pointers to store the addresses of the ends of both the sentence and the word we are looking for. I then used a while loop to iterate through the string. If the current character matches the last character of the word we are searching for, we enter another while loop which compares the two. If the pointer that points to the beginning of the word and the one we used to iterate through the word are equal, the word is found.

Here is some code:

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

int find_last( char *str,  char *word)
{
    char *p, *q;

    char *s, *t;

    p=str;                            /* Pointer p now points to the last character of the sentence*/
    while(*p!='\0') p++;
    p--;

    q = word;
    while(*q!='\0') q++;             /* Pointer q now points to the last character of the word*/
    q--;

    while(p != str) {
        if(*p == *q) {
            s=p;                        /* if a matching character is found, "s" and "t" are used to iterate through */
            /* the string and the word, respectively*/
            t=q;

            while(*s == *t) {
                s--;
                t--;
            }

            if(t == word-1) return s-str+1;  /* if pointer "t" is equal by address to pointer word-1, we have found our match. return s-str+1. */
        }
        p--;
    }
    return -1;
}

int main()
{
    char arr[] = "Today is a great day!";

    printf("%d", find_last(arr, "Today"));

    return 0;
}
</code>```

So, this code should return 0 but it returns -1.

It works in every other instance I tested! When ran in CodeBlocks, the output is as expected (0), but using any other online IDE I could find the output is still -1.

答:
For starters the parameters of the function shall have the qualifier const and its return type should be either size_t or ptrdiff_t.

For example

```<code>ptrdiff_t find_last( const char *str,  const char *word );
</code>```

In any case the function shall be declared at least like

```<code>int find_last( const char *str,  const char *word );
</code>```

The function should emulate the behavior of the standard C function strstr. That is when the second argument is an empty string the function should return 0.

If either of the arguments is an empty string then your function has undefined behavior due to these statements

```<code>p=str;                            /* Pointer p now points to the last character of the sentence*/
while(*p!='\0') p++;
p--;
^^^^

q = word;
while(*q!='\0') q++;             /* Pointer q now points to the last character of the word*/
q--;
^^^^
</code>```

If the string pointed to by str contains only one symbol then your function returns -1 because the condition of the loop

```<code>while(p != str) {
</code>```

evaluates to false independent on whether the both strings are equal each other or not.

This loop

```<code>        while(*s == *t) {
            s--;
            t--;
        }
</code>```

again can invoke undefined behavior because there can be an access to memory that precedes the string word.

And this statement

```<code>if(t == word-1) return s-str+1;
</code>```

also can invoke the undefined behavior by the same reason.

The function can be defined as it is shown in the demonstrative program below.

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

int find_last( const char *str,  const char *word )
{

    const char *p = str;

    int found = !*word;

    if ( !found )
    {
        while ( *p ) ++p;

        const char *q = word;

        while ( *q ) ++q;

        while ( !found && !( p - str < q - word ) )
        {
            const char *s = p;
            const char *t = q;

            while ( t != word && *( s - 1 ) == *( t - 1) )
            {
                --s;
                --t;
            }

            found = t == word;

            if ( found ) p = s;
            else --p;
        }
    }

    return found ? p - str : -1;
}

int main(void)
{
    const char *str = "";
    const char *word = "";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    word = "A";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "A";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABA";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABAB";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABCDEF";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABCDEF";
    word = "BC";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    return 0;
}
</code>```

The program output is

```<code>find_last( str, word ) == 0
find_last( str, word ) == -1
find_last( str, word ) == 0
find_last( str, word ) == 2
find_last( str, word ) == 2
find_last( str, word ) == 0
find_last( str, word ) == 1
</code>```

Body:
I am practicing and I came across an exercise. The exercise says I am to manually write a function that finds the index of the last occurrence in a string. Now, I get that this has maybe been asked before but I cannot find what is the problem with my code. It works for almost all instances, but not so when the last occurrence of the word is at the beginning of the string.

What I have tried: I used pointers to store the addresses of the ends of both the sentence and the word we are looking for. I then used a while loop to iterate through the string. If the current character matches the last character of the word we are searching for, we enter another while loop which compares the two. If the pointer that points to the beginning of the word and the one we used to iterate through the word are equal, the word is found.

Here is some code:

#include <stdio.h>

int find_last( char *str,  char *word)
{
    char *p, *q;

    char *s, *t;

    p=str;                            /* Pointer p now points to the last character of the sentence*/
    while(*p!='\0') p++;
    p--;

    q = word;
    while(*q!='\0') q++;             /* Pointer q now points to the last character of the word*/
    q--;

    while(p != str) {
        if(*p == *q) {
            s=p;                        /* if a matching character is found, "s" and "t" are used to iterate through */
            /* the string and the word, respectively*/
            t=q;

            while(*s == *t) {
                s--;
                t--;
            }

            if(t == word-1) return s-str+1;  /* if pointer "t" is equal by address to pointer word-1, we have found our match. return s-str+1. */
        }
        p--;
    }
    return -1;
}

int main()
{
    char arr[] = "Today is a great day!";

    printf("%d", find_last(arr, "Today"));

    return 0;
}

So, this code should return 0 but it returns -1.

It works in every other instance I tested! When ran in CodeBlocks, the output is as expected (0), but using any other online IDE I could find the output is still -1.

Body:
For starters the parameters of the function shall have the qualifier const and its return type should be either size_t or ptrdiff_t.

For example

ptrdiff_t find_last( const char *str,  const char *word );

In any case the function shall be declared at least like

int find_last( const char *str,  const char *word );

The function should emulate the behavior of the standard C function strstr. That is when the second argument is an empty string the function should return 0.

If either of the arguments is an empty string then your function has undefined behavior due to these statements

p=str;                            /* Pointer p now points to the last character of the sentence*/
while(*p!='\0') p++;
p--;
^^^^

q = word;
while(*q!='\0') q++;             /* Pointer q now points to the last character of the word*/
q--;
^^^^

If the string pointed to by str contains only one symbol then your function returns -1 because the condition of the loop

while(p != str) {

evaluates to false independent on whether the both strings are equal each other or not.

This loop

        while(*s == *t) {
            s--;
            t--;
        }

again can invoke undefined behavior because there can be an access to memory that precedes the string word.

And this statement

if(t == word-1) return s-str+1;

also can invoke the undefined behavior by the same reason.

The function can be defined as it is shown in the demonstrative program below.

#include <stdio.h>

int find_last( const char *str,  const char *word )
{

    const char *p = str;

    int found = !*word;

    if ( !found )
    {
        while ( *p ) ++p;

        const char *q = word;

        while ( *q ) ++q;

        while ( !found && !( p - str < q - word ) )
        {
            const char *s = p;
            const char *t = q;

            while ( t != word && *( s - 1 ) == *( t - 1) )
            {
                --s;
                --t;
            }

            found = t == word;

            if ( found ) p = s;
            else --p;
        }
    }

    return found ? p - str : -1;
}

int main(void)
{
    const char *str = "";
    const char *word = "";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    word = "A";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "A";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABA";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABAB";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABCDEF";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    str = "ABCDEF";
    word = "BC";

    printf( "find_last( str, word ) == %d\n", find_last( str, word ) );

    return 0;
}

The program output is

find_last( str, word ) == 0
find_last( str, word ) == -1
find_last( str, word ) == 0
find_last( str, word ) == 2
find_last( str, word ) == 2
find_last( str, word ) == 0
find_last( str, word ) == 1


问:
cumulative product in pySpark data frame
I have the following spark DataFrame:

```<code>+---+---+
|  a|  b|
+---+---+
|  1|  1|
|  1|  2|
|  1|  3|
|  1|  4|
+---+---+
</code>```

I want to make another column named "c" which contains the cumulative product of "b" over "a". The resulting DataFrame should look like:

```<code>+---+---+---+
|  a|  b|  c|
+---+---+---+
|  1|  1|  1|
|  1|  2|  2|
|  1|  3|  6|
|  1|  4| 24|
+---+---+---+
</code>```

How can this be done?

Body:
I have the following spark DataFrame:

+---+---+
|  a|  b|
+---+---+
|  1|  1|
|  1|  2|
|  1|  3|
|  1|  4|
+---+---+

I want to make another column named "c" which contains the cumulative product of "b" over "a". The resulting DataFrame should look like:

+---+---+---+
|  a|  b|  c|
+---+---+---+
|  1|  1|  1|
|  1|  2|  2|
|  1|  3|  6|
|  1|  4| 24|
+---+---+---+

How can this be done?

Body:
Here is an alternative approach not using a user-defined function

df = spark.createDataFrame([(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)], ['a', 'b'])
wind = Window.partitionBy("a").rangeBetween(Window.unboundedPreceding, Window.currentRow).orderBy("b")
df2 = df.withColumn("foo", collect_list("b").over(wind))
df2.withColumn("foo2", expr("aggregate(foo, cast(1 as bigint), (acc, x) -> acc * x)")).show()

+---+---+---------------+----+
|  a|  b|            foo|foo2|
+---+---+---------------+----+
|  1|  1|            [1]|   1|
|  1|  2|         [1, 2]|   2|
|  1|  3|      [1, 2, 3]|   6|
|  1|  4|   [1, 2, 3, 4]|  24|
|  1|  5|[1, 2, 3, 4, 5]| 120|
+---+---+---------------+----+

and if you don't really care about the precision you can build a shorter version

import pyspark.sql.functions as psf

df.withColumn("foo", psf.exp(psf.sum(psf.log("b")).over(wind))).show()
+---+---+------------------+
|  a|  b|               foo|
+---+---+------------------+
|  1|  1|               1.0|
|  1|  2|               2.0|
|  1|  3|               6.0|
|  1|  4|23.999999999999993|
|  1|  5|119.99999999999997|
+---+---+------------------


问:
How to make Flutter Workmanager plugin and Location plugin work together
1. Problem description

My goal is to build a Flutter app that gets periodic location updates using this workmanager plugin and using this location plugin. But I can't get the Location plugin to be loaded properly when my Workmanager callback fires. I get this error:

```<code>MissingPluginException(No implementation found for method getLocation on channel lyokone/location)
</code>```

So basically, the problem is that when the Workmanager plugin tries to run dart code, it doesn't load up the Location plugin.

2. Other resources I have researched

I found others facing the same issue, here, here, and here.

As far as I understand, the solution provided to these questions boils down to: create a file named CustomApplication.java, which extends FlutterApplication, and which registers your plugin(s). And then register the CustomApplication.java file inside you AndoidManifest.xml file.

3. My code thus far

I have tried to make a bare-minimum app that implements the features I require:

I implemented Workmanager plugin (works fine)

I implemented Location plugin (works fine)

I attempted to combine these features (does not work)

To see exactly what I have done at each step, please look here: https://gitlab.com/tomoerlemans/workmanager_with_location/-/commits/master. (This repository can also be used to quickly replicate the issue).

The relevant code files are as follows:

main.dart

```<code>import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
import 'package:location/location.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager.initialize(callbackDispatcher, isInDebugMode: true);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                Workmanager.registerPeriodicTask(
                    "1", "simpleTask");
              },
              child: Text("Start workmanager"),
            ),
            RaisedButton(
              onPressed: () {
                getLocation();
              },
              child: Text("Get current location"),
            ),
          ],
        ),
      ),
    );
  }
}

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
    print("Native called background task at ${DateTime.now().toString()}");
    getLocation();
    return Future.value(true);
  });
}

void getLocation() async {
  LocationData currentLocation;
  var location = new Location();
  try {
    currentLocation = await location.getLocation();
  } on Exception catch (e) {
    print("Error obtaining location: $e");
    currentLocation = null;
  }
  print("Location altitude: ${currentLocation.altitude}");
  print("Location longitude: ${currentLocation.longitude}");
}
</code>```

pubspec.yaml

```<code>name: background_location
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  workmanager: ^0.2.0
  location: ^2.3.5

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true
</code>```

CustomApplication.java

```<code>package io.flutter.plugins;

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import be.tramckrijte.workmanager.WorkmanagerPlugin;
import com.lyokone.location.LocationPlugin;

public class CustomApplication extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        WorkmanagerPlugin.setPluginRegistrantCallback(this);

    }
    @Override
    public void registerWith(PluginRegistry registry) {
        WorkmanagerPlugin.registerWith(registry.registrarFor("be.tramckrijte.workmanager.WorkmanagerPlugin"));
        LocationPlugin.registerWith(registry.registrarFor("com.lyokone.location.LocationPlugin"));
    }
}
</code>```

AndroidManifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.background_location">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:name="io.flutter.plugins.CustomApplication"
        android:label="background_location"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>
</code>```

Finally, I am running the following versions of Dart/Flutter/etc:

```<code>Flutter 1.12.13+hotfix.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 27321ebbad (10 weeks ago) • 2019-12-10 18:15:01 -0800
Engine • revision 2994f7e1e6
Tools • Dart 2.7.0
</code>```

答:
With these two plugins, you could schedule a one-off task and pass the current location into it.

be.tramckrijte.workmanager has  limitations (it even states that not everything is being supported). And combining these two plugins through Dart might lead nowhere, because the application is not always running. Even if there is a simple_callback_dispatcher_registration.dart, which shows how it works, this will call back to the Flutter engine and not query the other plugin.

Writing & scheduling a location-aware ListenableWorker might be the best option available to get a GPS fix while running a task - unless there is any way to query the LocationPlugin plugin through the Flutter engine, while running in the background. I mean, if the ListenableWorker is location aware, it does not need to obtain the location elsewhere. Threading in WorkManager literally states it:

ListenableWorker is the base class for Worker, CoroutineWorker, and RxWorker. It is intended for Java developers who have to interact with callback-based asynchronous APIs such as FusedLocationProviderClient ...

Therefore ListenableWorker, Worker and CoroutineWorker would be applicable classes to extend from. The equivalent for the iOS implementation would be a location-aware background service. The Flutter engine may start/stop them, provide start parameters or receive callbacks, but the code which is running in the background usually won't be Dart, since it should run independently.

Body:
1. Problem description

My goal is to build a Flutter app that gets periodic location updates using this workmanager plugin and using this location plugin. But I can't get the Location plugin to be loaded properly when my Workmanager callback fires. I get this error:

MissingPluginException(No implementation found for method getLocation on channel lyokone/location)

So basically, the problem is that when the Workmanager plugin tries to run dart code, it doesn't load up the Location plugin.

2. Other resources I have researched

I found others facing the same issue, here, here, and here.

As far as I understand, the solution provided to these questions boils down to: create a file named CustomApplication.java, which extends FlutterApplication, and which registers your plugin(s). And then register the CustomApplication.java file inside you AndoidManifest.xml file.

3. My code thus far

I have tried to make a bare-minimum app that implements the features I require:

I implemented Workmanager plugin (works fine)

I implemented Location plugin (works fine)

I attempted to combine these features (does not work)

To see exactly what I have done at each step, please look here: https://gitlab.com/tomoerlemans/workmanager_with_location/-/commits/master. (This repository can also be used to quickly replicate the issue).

The relevant code files are as follows:

main.dart

import 'package:flutter/material.dart';
import 'package:workmanager/workmanager.dart';
import 'package:location/location.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager.initialize(callbackDispatcher, isInDebugMode: true);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                Workmanager.registerPeriodicTask(
                    "1", "simpleTask");
              },
              child: Text("Start workmanager"),
            ),
            RaisedButton(
              onPressed: () {
                getLocation();
              },
              child: Text("Get current location"),
            ),
          ],
        ),
      ),
    );
  }
}

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) {
    print("Native called background task at ${DateTime.now().toString()}");
    getLocation();
    return Future.value(true);
  });
}

void getLocation() async {
  LocationData currentLocation;
  var location = new Location();
  try {
    currentLocation = await location.getLocation();
  } on Exception catch (e) {
    print("Error obtaining location: $e");
    currentLocation = null;
  }
  print("Location altitude: ${currentLocation.altitude}");
  print("Location longitude: ${currentLocation.longitude}");
}

pubspec.yaml

name: background_location
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  workmanager: ^0.2.0
  location: ^2.3.5

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

CustomApplication.java

package io.flutter.plugins;

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import be.tramckrijte.workmanager.WorkmanagerPlugin;
import com.lyokone.location.LocationPlugin;

public class CustomApplication extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        WorkmanagerPlugin.setPluginRegistrantCallback(this);

    }
    @Override
    public void registerWith(PluginRegistry registry) {
        WorkmanagerPlugin.registerWith(registry.registrarFor("be.tramckrijte.workmanager.WorkmanagerPlugin"));
        LocationPlugin.registerWith(registry.registrarFor("com.lyokone.location.LocationPlugin"));
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.background_location">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:name="io.flutter.plugins.CustomApplication"
        android:label="background_location"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

Finally, I am running the following versions of Dart/Flutter/etc:

Flutter 1.12.13+hotfix.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 27321ebbad (10 weeks ago) • 2019-12-10 18:15:01 -0800
Engine • revision 2994f7e1e6
Tools • Dart 2.7.0


问:
How to skip the first three elements in first instance of loop
How can I achieve this using python

```<code>for season in seasons:
    print('Season:',season)
    season_response = requests.get(season, headers=headers, cookies=cookies)
    season_content = season_response.content
    season_doc = html.fromstring(season_content)
    dates = [base + date for date in season_doc.xpath('//*[@id="bloccontenu"]//div[@class="select-container select-game"]/select/option/@value')]
    for date in dates:
        print(date)
        # print dates
        # exclude the first three dates of only the first instance of loop
</code>```

How can I print excluding the first three dates of the first season, but print all the other dates of every other season?

for example, season 1 has 6 dates, season 2 has 5 dates :
I expect such an output, where the first 3 dates of season 1 are excluded :

```<code>Season: season 1
date4
date5
date6
Season: season 2
date1
date2
date3
date4
date5
</code>```

答:
```<code>for season in seasons:
    print('Season:',season)
    season_response = requests.get(season, headers=headers, cookies=cookies)
    season_content = season_response.content
    season_doc = html.fromstring(season_content)
    dates = [base + date for date in season_doc.xpath('//*[@id="bloccontenu"]//div[@class="select-container select-game"]/select/option/@value')]

    if season == seasons[0]:
        dates = dates[3:]

    for date in dates:
        print(date)
</code>```

When the season is equal to season 1, discard the first 3 dates?

Body:
How can I achieve this using python

for season in seasons:
    print('Season:',season)
    season_response = requests.get(season, headers=headers, cookies=cookies)
    season_content = season_response.content
    season_doc = html.fromstring(season_content)
    dates = [base + date for date in season_doc.xpath('//*[@id="bloccontenu"]//div[@class="select-container select-game"]/select/option/@value')]
    for date in dates:
        print(date)
        # print dates
        # exclude the first three dates of only the first instance of loop

How can I print excluding the first three dates of the first season, but print all the other dates of every other season?

for example, season 1 has 6 dates, season 2 has 5 dates :
I expect such an output, where the first 3 dates of season 1 are excluded :

Season: season 1
date4
date5
date6
Season: season 2
date1
date2
date3
date4
date5

Body:
for season in seasons:
    print('Season:',season)
    season_response = requests.get(season, headers=headers, cookies=cookies)
    season_content = season_response.content
    season_doc = html.fromstring(season_content)
    dates = [base + date for date in season_doc.xpath('//*[@id="bloccontenu"]//div[@class="select-container select-game"]/select/option/@value')]

    if season == seasons[0]:
        dates = dates[3:]

    for date in dates:
        print(date)

When the season is equal to season 1, discard the first 3 dates?


问:
How to split a dataframe and attach the splitted part in new column?
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

```<code>#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)
</code>```

答:
Maybe you can try the following code

```<code>df_goal <- data.frame(t(c(t(df))))
</code>```

such that

```<code>> df_goal
  X1       X2  X3 X4       X5 X6 X7       X8 X9
1  1 20200101 4.5  2 20200101  5  3 20200101  7
</code>```

Body:
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)

Body:
Maybe you can try the following code

df_goal <- data.frame(t(c(t(df))))

such that

> df_goal
  X1       X2  X3 X4       X5 X6 X7       X8 X9
1  1 20200101 4.5  2 20200101  5  3 20200101  7


问:
JSON-Schema add property to the item conditionally
I have the following JSON data

```<code>[
  {
    "type": "social_media_profiles",
    "data": {
      "profiles": [
        {
          "key": "twitter",
          "data": "username",
          "field": "handle",
          "label": "Tweet"
        },
        {
          "key": "customLink",
          "data": "abc",
          "field": "url",
          "label": "Click",
          "color": {
            "button": "red",
            "text": "green",
            "border": "yellow"
          }
        }
      ]
    }
  }
]
</code>```

and following jsong schema

```<code>{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "additionalProperties": false,
  "items": {
    "type": "object",
    "required": ["type", "data"],
    "additionalProperties": false,
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "social_media_profiles"
        ]
      },
      "data": {
        "type": "object"
      }
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "type": {
              "const": "social_media_profiles"
            }
          }
        },
        "then": {
          "properties": {
            "data": {
              "type": "object",
              "required": ["profiles"],
              "additionalProperties": false,
              "properties": {
                "profiles": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": ["data", "field", "key"],
                    "additionalProperties": false,
                    "properties": {
                      "data": {
                        "type": "string",
                        "description": "Data contains either profile url, handle id, etc."
                      },
                      "field": {
                        "type": "string",
                        "enum": ["url", "handle", "id", "tel"],
                        "description": "Type of field value."
                      },
                      "key": {
                        "type": "string",
                        "description": "Social media name used to distinguish each social network"
                      },
                      "label": {
                        "type": "string",
                        "description": "Label to display on the landing page"
                      }
                    },
                    "allOf": [
                      {
                        "if": {
                          "properties": {
                            "key": {
                              "const": "customLink"
                            }
                          }
                        },
                        "then": {
                          "properties": {
                            "color": {
                              "type": "object",
                              "additionalProperties": false,
                              "required": [],
                              "properties": {
                                "button": {
                                  "type": "string"
                                },
                                "text": {
                                  "type": "string"
                                },
                                "border": {
                                  "type": "string"
                                }
                              }
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              }
            }
          }
        }
      }
    ]
  }
}
</code>```

I want to add new property color to the profiles item based on the condition when key of the item is customLink.

If key is not customLink then color property should not be there.

Validating the schema from https://www.jsonschemavalidator.net/ is giving error

```<code> Found 2 error(s)

 Message: JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0.
 Schema path: #/items/allOf

    Message: JSON does not match schema from 'then'.
    Schema path: #/items/allOf/0/then/then
</code>```

How can I append new property conditionally based on the sibling property value?

答:
In your profiles.items schema, you defined additionalProperties: false.

additionalProperties depends on the properties defined in the same schema object, meaning that color would always be dissallowed.

You can separate out your concerns into "what properties are allowed", and "if their values are valid".

Moving the validation for the color object into profiles.properties allows you to maintain additionalProperties: false in that object level.

The schema values of the properties object are only applied to the instance location for the keys, if they exist (hence needing to use required to require that specific keys are... required).

Having simplified the condional section, you end up with a cleaner Schema.

You now only need to define the condition under which color is required, without worrying about what the value should look like.

Sudo code: if key is customLink, then require color, else dissallow color.

```<code>{
  "if": {
    "properties": {
      "key": {
        "const": "customLink"
      }
    }
  },
  "then": {
    "required": [
      "color"
    ]
  },
  "else": {
    "not": {
      "required": [
        "color"
      ]
    }
  }
}
</code>```

Using not, you can invert the validation result of the applied subschema, which is what you need to do when you want to define that a specific property is NOT allowed.

Here's a live demo to play with: https://jsonschema.dev/s/C9V6N

And for prosperity, here's the full schema, with one or two redundancies removed.

```<code>{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "required": [
      "type",
      "data"
    ],
    "additionalProperties": false,
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "social_media_profiles"
        ]
      },
      "data": {
        "type": "object"
      }
    },
    "allOf": [
      {
        "properties": {
          "data": {
            "type": "object",
            "required": [
              "profiles"
            ],
            "additionalProperties": false,
            "properties": {
              "profiles": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "data",
                    "field",
                    "key"
                  ],
                  "additionalProperties": false,
                  "properties": {
                    "data": {
                      "type": "string",
                      "description": "Data contains either profile url, handle id, etc."
                    },
                    "field": {
                      "type": "string",
                      "enum": [
                        "url",
                        "handle",
                        "id",
                        "tel"
                      ],
                      "description": "Type of field value."
                    },
                    "key": {
                      "type": "string",
                      "description": "Social media name used to distinguish each social network"
                    },
                    "label": {
                      "type": "string",
                      "description": "Label to display on the landing page"
                    },
                    "color": {
                      "type": "object",
                      "additionalProperties": false,
                      "properties": {
                        "button": {
                          "type": "string"
                        },
                        "text": {
                          "type": "string"
                        },
                        "border": {
                          "type": "string"
                        }
                      }
                    }
                  },
                  "allOf": [
                    {
                      "if": {
                        "properties": {
                          "key": {
                            "const": "customLink"
                          }
                        }
                      },
                      "then": {
                        "required": [
                          "color"
                        ]
                      },
                      "else": {
                        "not": {
                          "required": [
                            "color"
                          ]
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      }
    ]
  }
}
</code>```

Body:
I have the following JSON data

[
  {
    "type": "social_media_profiles",
    "data": {
      "profiles": [
        {
          "key": "twitter",
          "data": "username",
          "field": "handle",
          "label": "Tweet"
        },
        {
          "key": "customLink",
          "data": "abc",
          "field": "url",
          "label": "Click",
          "color": {
            "button": "red",
            "text": "green",
            "border": "yellow"
          }
        }
      ]
    }
  }
]

and following jsong schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "additionalProperties": false,
  "items": {
    "type": "object",
    "required": ["type", "data"],
    "additionalProperties": false,
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "social_media_profiles"
        ]
      },
      "data": {
        "type": "object"
      }
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "type": {
              "const": "social_media_profiles"
            }
          }
        },
        "then": {
          "properties": {
            "data": {
              "type": "object",
              "required": ["profiles"],
              "additionalProperties": false,
              "properties": {
                "profiles": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "required": ["data", "field", "key"],
                    "additionalProperties": false,
                    "properties": {
                      "data": {
                        "type": "string",
                        "description": "Data contains either profile url, handle id, etc."
                      },
                      "field": {
                        "type": "string",
                        "enum": ["url", "handle", "id", "tel"],
                        "description": "Type of field value."
                      },
                      "key": {
                        "type": "string",
                        "description": "Social media name used to distinguish each social network"
                      },
                      "label": {
                        "type": "string",
                        "description": "Label to display on the landing page"
                      }
                    },
                    "allOf": [
                      {
                        "if": {
                          "properties": {
                            "key": {
                              "const": "customLink"
                            }
                          }
                        },
                        "then": {
                          "properties": {
                            "color": {
                              "type": "object",
                              "additionalProperties": false,
                              "required": [],
                              "properties": {
                                "button": {
                                  "type": "string"
                                },
                                "text": {
                                  "type": "string"
                                },
                                "border": {
                                  "type": "string"
                                }
                              }
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              }
            }
          }
        }
      }
    ]
  }
}

I want to add new property color to the profiles item based on the condition when key of the item is customLink.

If key is not customLink then color property should not be there.

Validating the schema from https://www.jsonschemavalidator.net/ is giving error

 Found 2 error(s)

 Message: JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0.
 Schema path: #/items/allOf

    Message: JSON does not match schema from 'then'.
    Schema path: #/items/allOf/0/then/then

How can I append new property conditionally based on the sibling property value?

Body:
In your profiles.items schema, you defined additionalProperties: false.

additionalProperties depends on the properties defined in the same schema object, meaning that color would always be dissallowed.

You can separate out your concerns into "what properties are allowed", and "if their values are valid".

Moving the validation for the color object into profiles.properties allows you to maintain additionalProperties: false in that object level.

The schema values of the properties object are only applied to the instance location for the keys, if they exist (hence needing to use required to require that specific keys are... required).

Having simplified the condional section, you end up with a cleaner Schema.

You now only need to define the condition under which color is required, without worrying about what the value should look like.

Sudo code: if key is customLink, then require color, else dissallow color.

{
  "if": {
    "properties": {
      "key": {
        "const": "customLink"
      }
    }
  },
  "then": {
    "required": [
      "color"
    ]
  },
  "else": {
    "not": {
      "required": [
        "color"
      ]
    }
  }
}

Using not, you can invert the validation result of the applied subschema, which is what you need to do when you want to define that a specific property is NOT allowed.

Here's a live demo to play with: https://jsonschema.dev/s/C9V6N

And for prosperity, here's the full schema, with one or two redundancies removed.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "required": [
      "type",
      "data"
    ],
    "additionalProperties": false,
    "properties": {
      "type": {
        "type": "string",
        "enum": [
          "social_media_profiles"
        ]
      },
      "data": {
        "type": "object"
      }
    },
    "allOf": [
      {
        "properties": {
          "data": {
            "type": "object",
            "required": [
              "profiles"
            ],
            "additionalProperties": false,
            "properties": {
              "profiles": {
                "type": "array",
                "items": {
                  "type": "object",
                  "required": [
                    "data",
                    "field",
                    "key"
                  ],
                  "additionalProperties": false,
                  "properties": {
                    "data": {
                      "type": "string",
                      "description": "Data contains either profile url, handle id, etc."
                    },
                    "field": {
                      "type": "string",
                      "enum": [
                        "url",
                        "handle",
                        "id",
                        "tel"
                      ],
                      "description": "Type of field value."
                    },
                    "key": {
                      "type": "string",
                      "description": "Social media name used to distinguish each social network"
                    },
                    "label": {
                      "type": "string",
                      "description": "Label to display on the landing page"
                    },
                    "color": {
                      "type": "object",
                      "additionalProperties": false,
                      "properties": {
                        "button": {
                          "type": "string"
                        },
                        "text": {
                          "type": "string"
                        },
                        "border": {
                          "type": "string"
                        }
                      }
                    }
                  },
                  "allOf": [
                    {
                      "if": {
                        "properties": {
                          "key": {
                            "const": "customLink"
                          }
                        }
                      },
                      "then": {
                        "required": [
                          "color"
                        ]
                      },
                      "else": {
                        "not": {
                          "required": [
                            "color"
                          ]
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        }
      }
    ]
  }
}


问:
Submit button won't line up vertically with other fields on the same line
Can anybody shed some light on why this submit button won't line up vertically with the other form fields on the line?

http://www.e-fluential.com/offline/castoff/

答: add style="float:left" to the span and two inputs.</p>