问:
Reducer thrown " error object null is not iterable" in ngrx
I have a component called doctors.list.component.ts which renders a list of doctors. I getting this doctor from API using @ngrx/effect. I want to add a new doctor to this list in using ng-modal. the flow is when the user selects the doctor form ng-modal it has to be added to the existing doctor-list.for that I wrote new action and reducer. this reducer throws error object null is not iterable

this my doctorlist.action.ts

```<code>import { createAction, props } from '@ngrx/store';
import { Doctors } from 'src/app/admin/models/doctorProfileAdmin'

export const loadDoctors = createAction('[Doctors] Doctors List Request', props<{ hospitalId: string }>())

export const loadDoctorsSuccess = createAction('[Doctors] Doctors List Load Success', props<{ doctors: Doctors[] }>())

export const loadDoctorsFail = createAction('[Doctors] Doctors List Load Fail', props<{ errorMessage: string }>())

export const addExistingDoctorToList = createAction('[Doctors] Doctors List Load Success', props<{ doctor: Doctors }>())
</code>```

in my doctor.list.reducer.ts

```<code>import { createReducer, on, Action } from '@ngrx/store';
import { DoctorListState } from '../state/doctorList.state';
import { loadDoctors, loadDoctorsSuccess, loadDoctorsFail,addExistingDoctorToList } from '../actions/doctorList.actions';

const initialState: DoctorListState = {
    doctors:null,
    error: null,
    isLoading: false
};

const doctorListReducer = createReducer(initialState,
    on(loadDoctors, (state) => {
        return { ...state, isLoading: true };
    }),
    on(loadDoctorsSuccess, (state, { doctors }) => {
        return { ...state, doctors: doctors, isLoading: false };
    }),
    on(loadDoctorsFail, ((state, { errorMessage }) => {
        return { ...state, errorMes: errorMessage, isLoading: false };
    })),
    on(addExistingDoctorToList, (state, { doctor }) => {
        return { ...state, doctors:[...state.doctors,doctor], isLoading: false };
    }),

);

export function reducer(state: DoctorListState | undefined, action: Action) {
    return doctorListReducer(state, action);
}
</code>```

I change my initialState doctors property to the empty array as well .then this error not appears but my doctor list also not displayed in the component

this how I get doctors to my doctors.list.component.ts when component initializes.

```<code> this.store.pipe(select(selectDoctorsList)).pipe(skip(1)).subscribe(payload => {
        this.doctorList = payload;
 })
</code>```

add new docotr event click function

```<code>addNewDoctor(){
   this.store.dispatch(addExistingDoctorToList({doctor:selectedDoctor}))
}
</code>```

i couldn't understand what i am doing wrong here.

答:
look at actions definition

```<code>export const loadDoctorsSuccess = createAction('[Doctors] Doctors List Load Success', props<{ doctors: Doctors[] }>())

export const addExistingDoctorToList = createAction('[Doctors] Doctors List Load Success', props<{ doctor: Doctors }>())
</code>```

these 2 actions have the same String which is used as action.type. they should be unique so ngrx will treat them as different actions.

Body:
I have a component called doctors.list.component.ts which renders a list of doctors. I getting this doctor from API using @ngrx/effect. I want to add a new doctor to this list in using ng-modal. the flow is when the user selects the doctor form ng-modal it has to be added to the existing doctor-list.for that I wrote new action and reducer. this reducer throws error object null is not iterable

this my doctorlist.action.ts

import { createAction, props } from '@ngrx/store';
import { Doctors } from 'src/app/admin/models/doctorProfileAdmin'

export const loadDoctors = createAction('[Doctors] Doctors List Request', props<{ hospitalId: string }>())

export const loadDoctorsSuccess = createAction('[Doctors] Doctors List Load Success', props<{ doctors: Doctors[] }>())

export const loadDoctorsFail = createAction('[Doctors] Doctors List Load Fail', props<{ errorMessage: string }>())

export const addExistingDoctorToList = createAction('[Doctors] Doctors List Load Success', props<{ doctor: Doctors }>())

in my doctor.list.reducer.ts

import { createReducer, on, Action } from '@ngrx/store';
import { DoctorListState } from '../state/doctorList.state';
import { loadDoctors, loadDoctorsSuccess, loadDoctorsFail,addExistingDoctorToList } from '../actions/doctorList.actions';

const initialState: DoctorListState = {
    doctors:null,
    error: null,
    isLoading: false
};

const doctorListReducer = createReducer(initialState,
    on(loadDoctors, (state) => {
        return { ...state, isLoading: true };
    }),
    on(loadDoctorsSuccess, (state, { doctors }) => {
        return { ...state, doctors: doctors, isLoading: false };
    }),
    on(loadDoctorsFail, ((state, { errorMessage }) => {
        return { ...state, errorMes: errorMessage, isLoading: false };
    })),
    on(addExistingDoctorToList, (state, { doctor }) => {
        return { ...state, doctors:[...state.doctors,doctor], isLoading: false };
    }),

);

export function reducer(state: DoctorListState | undefined, action: Action) {
    return doctorListReducer(state, action);
}

I change my initialState doctors property to the empty array as well .then this error not appears but my doctor list also not displayed in the component

this how I get doctors to my doctors.list.component.ts when component initializes.

 this.store.pipe(select(selectDoctorsList)).pipe(skip(1)).subscribe(payload => {
        this.doctorList = payload;
 })

add new docotr event click function

addNewDoctor(){
   this.store.dispatch(addExistingDoctorToList({doctor:selectedDoctor}))
}

i couldn't understand what i am doing wrong here.

Body:
look at actions definition

export const loadDoctorsSuccess = createAction('[Doctors] Doctors List Load Success', props<{ doctors: Doctors[] }>())

export const addExistingDoctorToList = createAction('[Doctors] Doctors List Load Success', props<{ doctor: Doctors }>())

these 2 actions have the same String which is used as action.type. they should be unique so ngrx will treat them as different actions.


来源: stackexchange

问:
microsoft cpprestsdk listen to multiple url with same ip?
I want to use cpprestsdk to make a restful API,
I copied some code from here :

```<code>int main()
{
    http_listener listener("http://0.0.0.0:9080/demo/work1");
    cout<<"start server!"<<endl;
    listener.support(methods::GET,  handle_get);
    listener.support(methods::POST, handle_post);
    listener.support(methods::PUT,  handle_put);
    listener.support(methods::DEL,  handle_del);

    try
    {
        listener
                .open()
                .then([&listener]() {TRACE(L"\nstarting to listen\n"); })
                .wait();

        while (true);
    }
    catch (exception const & e)
    {
        cout << e.what() << endl;
    }

    return 0;
}
</code>```

now I have to listen to not only "http://0.0.0.0:9080/demo/work1" , but also "http://0.0.0.0:9080/demo/work2", "http://0.0.0.0:9080/realfunction/work1". All in the same IP and port, but different sub-path

Should I use multiple listener to handle all the url one by one in multi-thread? Or there is any other way to handle this?

答:
You can set </p>

```<code>http_listener listener("http://0.0.0.0:9080/");
</code>```

<p>And then in the handler check the request. In the examples linked in cpprestsdk's github I saw things like </p>

```<code>void handle_get(http_request message) {
    auto path = uri::split_path(uri::decode(message.relative_uri().path()));

    if (path.size() == 2 && path[0] == "demo" && path[1] == "work1") {
           // ...
    } else if (path.size() == 2 && path[0] == "demo" && path[1] == "work2") {
          // ...
    } else {
          message.reply(status_codes::NotFound);

    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use cpprestsdk to make a restful API,
I copied some code from here :

int main()
{
    http_listener listener("http://0.0.0.0:9080/demo/work1");
    cout<<"start server!"<<endl;
    listener.support(methods::GET,  handle_get);
    listener.support(methods::POST, handle_post);
    listener.support(methods::PUT,  handle_put);
    listener.support(methods::DEL,  handle_del);

    try
    {
        listener
                .open()
                .then([&listener]() {TRACE(L"\nstarting to listen\n"); })
                .wait();

        while (true);
    }
    catch (exception const & e)
    {
        cout << e.what() << endl;
    }

    return 0;
}

now I have to listen to not only "http://0.0.0.0:9080/demo/work1" , but also "http://0.0.0.0:9080/demo/work2", "http://0.0.0.0:9080/realfunction/work1". All in the same IP and port, but different sub-path

Should I use multiple listener to handle all the url one by one in multi-thread? Or there is any other way to handle this?

Body:
You can set

http_listener listener("http://0.0.0.0:9080/");

And then in the handler check the request. In the examples linked in cpprestsdk's github I saw things like

void handle_get(http_request message) {
    auto path = uri::split_path(uri::decode(message.relative_uri().path()));

    if (path.size() == 2 && path[0] == "demo" && path[1] == "work1") {
           // ...
    } else if (path.size() == 2 && path[0] == "demo" && path[1] == "work2") {
          // ...
    } else {
          message.reply(status_codes::NotFound);

    }
}


问:
Azure Cosmos MongoDB - Create collection with shard key
I need to create a collection in Azure's Cosmos MongoDB but with a partition/shard key as the required configuration is that the database will have a provisioned throughput (a set amount of RU's) and the collections in it will have a shared throughput.

The cluster's API is set to Cosmos DB Mongo API - If i create the collection in the cosmos i have no issues with Insert/Delete, but if i create the collection using the code below i will get an error saying {"Command insert failed: document does not contain shard key."} even though viewing the collection made in the portal and in the code look identical.

```<code>client.CreateDocumentCollectionAsync(database.SelfLink,
new DocumentCollection
{
    Id = "CollectionName",
    PartitionKey = new PartitionKeyDefinition { Paths = new Collection<string> { "/_id" } }
}).Wait();
</code>```

I have talked to a microsoft representative but i get lacking "answers". He advised to use Mongo CSharp Driver but it seems this driver is unable to define a partition key (which makes sense).

How can i create a collection with a partition key?

Thank you.

答:
You can use customCommand to create a collection with ShardKey. Something likes this:</p>

```<code>var createCollectionCommand = new BsonDocument
                {
                    { "customAction", "CreateCollection" },
                    { "collection", "YourCollectionName" },
                    { "shardKey", "YourShardKey" }
                };
cosmosDatabase.RunCommand<BsonDocument>(createCollectionCommand);
</code>```

Body:
I need to create a collection in Azure's Cosmos MongoDB but with a partition/shard key as the required configuration is that the database will have a provisioned throughput (a set amount of RU's) and the collections in it will have a shared throughput.

The cluster's API is set to Cosmos DB Mongo API - If i create the collection in the cosmos i have no issues with Insert/Delete, but if i create the collection using the code below i will get an error saying {"Command insert failed: document does not contain shard key."} even though viewing the collection made in the portal and in the code look identical.

client.CreateDocumentCollectionAsync(database.SelfLink,
new DocumentCollection
{
    Id = "CollectionName",
    PartitionKey = new PartitionKeyDefinition { Paths = new Collection<string> { "/_id" } }
}).Wait();

I have talked to a microsoft representative but i get lacking "answers". He advised to use Mongo CSharp Driver but it seems this driver is unable to define a partition key (which makes sense).

How can i create a collection with a partition key?

Thank you.

Body:
You can use customCommand to create a collection with ShardKey. Something likes this:

var createCollectionCommand = new BsonDocument
                {
                    { "customAction", "CreateCollection" },
                    { "collection", "YourCollectionName" },
                    { "shardKey", "YourShardKey" }
                };
cosmosDatabase.RunCommand<BsonDocument>(createCollectionCommand);


问:
Why does the Rust compiler complain that I use a moved value when I've replaced it with a new value?
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}
```

<p>However, the compiler complains on the second while loop that</p>

```error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move
```

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

答:
Looks like the destructuring on line 7 moves the value even when the block afterwards is not evaluated. (Edit: as @Sven Marnach pointed out in the comments, a temporary tuple gets created here which causes the move)
I've uglyfied your code to prove that point :)

```<code>struct List {
    next: Option<Box<List>>
}

fn drain_lists(mut shorter: Option<Box<List>>,
               mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    match(shorter, longer) {
        (Some(node1), Some(node2)) => {
            shorter = node1.next;
            longer = node2.next;
        },
        (_, _) => return  // without this you get the error
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}
</code>```

When I added the return for the default case, the code compiled.

Body:
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}

However, the compiler complains on the second while loop that

error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

Body:
Looks like the destructuring on line 7 moves the value even when the block afterwards is not evaluated. (Edit: as @Sven Marnach pointed out in the comments, a temporary tuple gets created here which causes the move)
I've uglyfied your code to prove that point :)

struct List {
    next: Option<Box<List>>
}

fn drain_lists(mut shorter: Option<Box<List>>,
               mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    match(shorter, longer) {
        (Some(node1), Some(node2)) => {
            shorter = node1.next;
            longer = node2.next;
        },
        (_, _) => return  // without this you get the error
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}

When I added the return for the default case, the code compiled.


问:
How to delete a XML child node using SQL Server 2016
I have the following Xml example snippet taken from a larger file:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>
</code>```

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>
</code>```

I have used the following to SQL query the XML and isolate the above snippet(first one)

```<code>select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0
</code>```

I have tried

```<code>SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')
</code>```

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers

答:
Hi All and thank you for your comments.

apologies for not making my code clear, i thought it was in my head and it was late in the day! lol.

The SET @XMLData.modify('delete(/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')
worked a treat.. I had tried that before but i was getting errors, I know realise that the parentheses after the delete, is kinda key to it working ha!
thank you all again!!

Body:
I have the following Xml example snippet taken from a larger file:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>

I have used the following to SQL query the XML and isolate the above snippet(first one)

select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0

I have tried

SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers


问:
Checking position of newly added unique_ptr to priority_queue
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

```<code>bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}
</code>```

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

```<code>bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}
</code>```

Can it be done better way?

答:
Use a shared pointer

You could use a shared ownership pointer type. That is, just use a std::shared_ptr instead. That one won't have the same issue at all. The code then is almost as before:

```<code>bool foo(std::shared_ptr<SchedulerTask> task)
{
  eventList_.push(task);
  return task == eventList_.top();
}
</code>```

Use a proxy with id

Your issue is basicly this: once you move the unique pointer into the container, you no longer can identify it. Therefore, another solution could be to stick with the std::unique_ptr but add a mechanism of unique identification. This could be in a proxy type of object:

```<code>struct SchedulerTaskInfo {
  std::unique_ptr<SchedulerTask> task_;
  int id_;
};
</code>```

Now you can compare using the id_:

```<code>bool foo(SchedulerTaskInfo task)
{
  eventList_.push(std::move(task));
  return task.id_ == eventList_.top().id_;
}
</code>```

You could even create the operator== on the proxy if you wanted.

Body:
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}

Can it be done better way?

Body:
Use a shared pointer

You could use a shared ownership pointer type. That is, just use a std::shared_ptr instead. That one won't have the same issue at all. The code then is almost as before:

bool foo(std::shared_ptr<SchedulerTask> task)
{
  eventList_.push(task);
  return task == eventList_.top();
}

Use a proxy with id

Your issue is basicly this: once you move the unique pointer into the container, you no longer can identify it. Therefore, another solution could be to stick with the std::unique_ptr but add a mechanism of unique identification. This could be in a proxy type of object:

struct SchedulerTaskInfo {
  std::unique_ptr<SchedulerTask> task_;
  int id_;
};

Now you can compare using the id_:

bool foo(SchedulerTaskInfo task)
{
  eventList_.push(std::move(task));
  return task.id_ == eventList_.top().id_;
}

You could even create the operator== on the proxy if you wanted.


问:
Pyspark FP growth implementation running slow
I am using the pyspark.ml.fpm (FP Growth) implementation of association rule mining on Spark v2.3.

The spark UI shows that the tasks as the end run very slowly. This seems to be a common problem and might be related to data skew.

Is this the real reason? Is there any solution for this?

I don't want to change the minSupport or minConfidence thresholds because that would effect by results. Removing the columns isn't a solution either.

答:
I was facing a similar issue. One solution you might try is setting a threshold on the amount of products in a transaction. If there are a couple of transactions that have way more products than the average, the tree computed by FP Growth blows up. This causes the runtime increases significantly and the risk for memory errors is much higher.

Hence, doing outlier removal on the transactions with disproportional amount of products might do the trick.

Hope this helps you out a bit :)


问:
I'm unable to understand below c# code fragment
I only have this part of the code. I'm unable to make sense is "next" another method of ptr or is it the random.next method. Just want to know if this is a common code fragment used by experts. </p>

```<code>Node mystery(Node ptr) {
    Node temp;
    Node previous = null;
    while (ptr != null) {
        temp = ptr.next;
        ptr.next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}

</code>```

答:
Usually Node object has a value (e.g of type int) and another property that holds the next node

```<code>public class Node{
 public int Value {get; set;}
 public Node Next {get; set;}
 //...
}
</code>```

For example here the next node of n1 is n2 node

```<code>Node n1=new Node(5);
Node n2=new Node(2);
n1.Next=n2;
</code>```

Body:
I only have this part of the code. I'm unable to make sense is "next" another method of ptr or is it the random.next method. Just want to know if this is a common code fragment used by experts.

Node mystery(Node ptr) {
    Node temp;
    Node previous = null;
    while (ptr != null) {
        temp = ptr.next;
        ptr.next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}

Body:
Usually Node object has a value (e.g of type int) and another property that holds the next node

public class Node{
 public int Value {get; set;}
 public Node Next {get; set;}
 //...
}

For example here the next node of n1 is n2 node

Node n1=new Node(5);
Node n2=new Node(2);
n1.Next=n2;


问:
SQL DimCalendar dynamic fiscal week for calendar 5-4-4
My aims is to create a 5-4-4 calendar where my Accounting starting period = '2019-04-01' and ending period = '2020-03-31'
 My Fiscal Week should start from Week 1 to Week 52.
 Below is my SQL query which display my accounting calendar

```<code>DECLARE @START_DATE DATE
DECLARE @END_DATE DATE
DECLARE @COUNTER INT

SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'
SET @COUNTER = 1

DECLARE @TABLE TABLE(
  CALENDAR_DATE DATE,
  WEEK_NUM INTEGER,
  START_WEEK DATE,
  END_WEEK DATE
)

WHILE @START_DATE <= @END_DATE
BEGIN

SET DATEFIRST 4

INSERT INTO @TABLE (CALENDAR_DATE,START_WEEK,END_WEEK)

SELECT
 @START_DATE,
 DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE),
 DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE) Sunday

SET @START_DATE = DATEADD(day, 1, @START_DATE)
SET @COUNTER = @COUNTER + 1

END

SELECT DISTINCT
  START_WEEK,
  END_WEEK,
  CASE
    WHEN START_WEEK = '2019-04-01' AND END_WEEK = '2019-04-07' THEN 'WEEK 1'
    WHEN START_WEEK = '2019-04-08' AND END_WEEK = '2019-04-14' THEN 'WEEK 2'
    WHEN START_WEEK = '2019-04-15' AND END_WEEK = '2019-04-21' THEN 'WEEK 3'
    WHEN START_WEEK = '2019-04-22' AND END_WEEK = '2019-04-28' THEN 'WEEK 4'
    WHEN START_WEEK = '2019-04-29' AND END_WEEK = '2019-05-05' THEN 'WEEK 5'
    WHEN START_WEEK = '2019-05-06' AND END_WEEK = '2019-05-12' THEN 'WEEK 6'
    WHEN START_WEEK = '2019-05-13' AND END_WEEK = '2019-05-19' THEN 'WEEK 7'
    WHEN START_WEEK = '2019-05-20' AND END_WEEK = '2019-05-26' THEN 'WEEK 8'
    WHEN START_WEEK = '2019-05-27' AND END_WEEK = '2019-06-02' THEN 'WEEK 9'
    WHEN START_WEEK = '2019-06-03' AND END_WEEK = '2019-06-09' THEN 'WEEK 10'
    WHEN START_WEEK = '2019-06-10' AND END_WEEK = '2019-06-16' THEN 'WEEK 11'
    WHEN START_WEEK = '2019-06-17' AND END_WEEK = '2019-06-23' THEN 'WEEK 12'
    WHEN START_WEEK = '2019-06-24' AND END_WEEK = '2019-06-30' THEN 'WEEK 13'
    WHEN START_WEEK = '2019-07-01' AND END_WEEK = '2019-07-07' THEN 'WEEK 14'
    WHEN START_WEEK = '2019-07-08' AND END_WEEK = '2019-07-14' THEN 'WEEK 15'
    WHEN START_WEEK = '2019-07-15' AND END_WEEK = '2019-07-21' THEN 'WEEK 16'
    WHEN START_WEEK = '2019-07-22' AND END_WEEK = '2019-07-28' THEN 'WEEK 17'
    WHEN START_WEEK = '2019-07-29' AND END_WEEK = '2019-08-04' THEN 'WEEK 18'
    WHEN START_WEEK = '2019-08-05' AND END_WEEK = '2019-08-11' THEN 'WEEK 19'
    WHEN START_WEEK = '2019-08-12' AND END_WEEK = '2019-08-18' THEN 'WEEK 20'
    WHEN START_WEEK = '2019-08-19' AND END_WEEK = '2019-08-25' THEN 'WEEK 21'
    WHEN START_WEEK = '2019-08-26' AND END_WEEK = '2019-09-01' THEN 'WEEK 22'
    WHEN START_WEEK = '2019-09-02' AND END_WEEK = '2019-09-08' THEN 'WEEK 23'
    WHEN START_WEEK = '2019-09-09' AND END_WEEK = '2019-09-15' THEN 'WEEK 24'
    WHEN START_WEEK = '2019-09-16' AND END_WEEK = '2019-09-22' THEN 'WEEK 25'
    WHEN START_WEEK = '2019-09-23' AND END_WEEK = '2019-09-29' THEN 'WEEK 26'
    WHEN START_WEEK = '2019-09-30' AND END_WEEK = '2019-10-06' THEN 'WEEK 27'
    WHEN START_WEEK = '2019-10-07' AND END_WEEK = '2019-10-13' THEN 'WEEK 28'
    WHEN START_WEEK = '2019-10-14' AND END_WEEK = '2019-10-20' THEN 'WEEK 29'
    WHEN START_WEEK = '2019-10-21' AND END_WEEK = '2019-10-27' THEN 'WEEK 30'
    WHEN START_WEEK = '2019-10-28' AND END_WEEK = '2019-11-03' THEN 'WEEK 31'
    WHEN START_WEEK = '2019-11-04' AND END_WEEK = '2019-11-10' THEN 'WEEK 32'
    WHEN START_WEEK = '2019-11-11' AND END_WEEK = '2019-11-17' THEN 'WEEK 33'
    WHEN START_WEEK = '2019-11-18' AND END_WEEK = '2019-11-24' THEN 'WEEK 34'
    WHEN START_WEEK = '2019-11-25' AND END_WEEK = '2019-12-01' THEN 'WEEK 35'
    WHEN START_WEEK = '2019-12-02' AND END_WEEK = '2019-12-08' THEN 'WEEK 36'
    WHEN START_WEEK = '2019-12-09' AND END_WEEK = '2019-12-15' THEN 'WEEK 37'
    WHEN START_WEEK = '2019-12-16' AND END_WEEK = '2019-12-22' THEN 'WEEK 38'
    WHEN START_WEEK = '2019-12-23' AND END_WEEK = '2019-12-29' THEN 'WEEK 39'
    WHEN START_WEEK = '2019-12-30' AND END_WEEK = '2020-01-05' THEN 'WEEK 40'
    WHEN START_WEEK = '2020-01-06' AND END_WEEK = '2020-01-12' THEN 'WEEK 41'
    WHEN START_WEEK = '2020-01-13' AND END_WEEK = '2020-01-19' THEN 'WEEK 42'
    WHEN START_WEEK = '2020-01-20' AND END_WEEK = '2020-01-26' THEN 'WEEK 43'
    WHEN START_WEEK = '2020-01-27' AND END_WEEK = '2020-02-02' THEN 'WEEK 44'
    WHEN START_WEEK = '2020-02-03' AND END_WEEK = '2020-02-09' THEN 'WEEK 45'
    WHEN START_WEEK = '2020-02-10' AND END_WEEK = '2020-02-16' THEN 'WEEK 46'
    WHEN START_WEEK = '2020-02-17' AND END_WEEK = '2020-02-23' THEN 'WEEK 47'
    WHEN START_WEEK = '2020-02-24' AND END_WEEK = '2020-03-01' THEN 'WEEK 48'
    WHEN START_WEEK = '2020-03-02' AND END_WEEK = '2020-03-08' THEN 'WEEK 49'
    WHEN START_WEEK = '2020-03-09' AND END_WEEK = '2020-03-15' THEN 'WEEK 50'
    WHEN START_WEEK = '2020-03-16' AND END_WEEK = '2020-03-22' THEN 'WEEK 51'
    WHEN START_WEEK = '2020-03-23' AND END_WEEK = '2020-03-29' THEN 'WEEK 52'
  END AS FY_WEEK
 FROM @TABLE
 ORDER BY START_WEEK,END_WEEK;
</code>```

My problem is the Fiscal Week (FY_WEEK) column, I don't want to hard-code those START_WEEK and END_WEEK value.

I'm looking for a way where I can dynamically populate my fiscal week column instead of hardcoding values.

答:
You can use recursive cte (as below shown in below query) or tally table without the temp table / table variable

```<code>DECLARE @START_DATE DATE
DECLARE @END_DATE DATE

SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'

-- Change the start date to the `Monday` of the week
SELECT  @START_DATE = DATEADD(DAY,
                            - (@@DATEFIRST+ DATEPART(WEEKDAY, @START_DATE) - 1 + 6) % 7,
                              @START_DATE)

; WITH CTE as
(
    SELECT  START_WEEK = @START_DATE, END_WEEK = DATEADD(DAY, 6, @START_DATE),
            FY_WEEK = 1

    UNION ALL

    SELECT  START_WEEK = DATEADD(DAY, 7, START_WEEK), END_WEEK = DATEADD(DAY, 7, END_WEEK),
            FY_WEEK = FY_WEEK + 1
    FROM    CTE
    WHERE   DATEADD(DAY, 7, START_WEEK) <= @END_DATE
)
SELECT  *
FROM    CTE
OPTION (MAXRECURSION 52)
</code>```

this does not depends on the DATEFIRST settings

Body:
My aims is to create a 5-4-4 calendar where my Accounting starting period = '2019-04-01' and ending period = '2020-03-31'
 My Fiscal Week should start from Week 1 to Week 52.
 Below is my SQL query which display my accounting calendar

DECLARE @START_DATE DATE
DECLARE @END_DATE DATE
DECLARE @COUNTER INT

SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'
SET @COUNTER = 1

DECLARE @TABLE TABLE(
  CALENDAR_DATE DATE,
  WEEK_NUM INTEGER,
  START_WEEK DATE,
  END_WEEK DATE
)

WHILE @START_DATE <= @END_DATE
BEGIN

SET DATEFIRST 4

INSERT INTO @TABLE (CALENDAR_DATE,START_WEEK,END_WEEK)

SELECT
 @START_DATE,
 DATEADD(dd, 0 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE),
 DATEADD(dd, 6 - (@@DATEFIRST + 5 + DATEPART(dw, @START_DATE)) % 7, @START_DATE) Sunday

SET @START_DATE = DATEADD(day, 1, @START_DATE)
SET @COUNTER = @COUNTER + 1

END

SELECT DISTINCT
  START_WEEK,
  END_WEEK,
  CASE
    WHEN START_WEEK = '2019-04-01' AND END_WEEK = '2019-04-07' THEN 'WEEK 1'
    WHEN START_WEEK = '2019-04-08' AND END_WEEK = '2019-04-14' THEN 'WEEK 2'
    WHEN START_WEEK = '2019-04-15' AND END_WEEK = '2019-04-21' THEN 'WEEK 3'
    WHEN START_WEEK = '2019-04-22' AND END_WEEK = '2019-04-28' THEN 'WEEK 4'
    WHEN START_WEEK = '2019-04-29' AND END_WEEK = '2019-05-05' THEN 'WEEK 5'
    WHEN START_WEEK = '2019-05-06' AND END_WEEK = '2019-05-12' THEN 'WEEK 6'
    WHEN START_WEEK = '2019-05-13' AND END_WEEK = '2019-05-19' THEN 'WEEK 7'
    WHEN START_WEEK = '2019-05-20' AND END_WEEK = '2019-05-26' THEN 'WEEK 8'
    WHEN START_WEEK = '2019-05-27' AND END_WEEK = '2019-06-02' THEN 'WEEK 9'
    WHEN START_WEEK = '2019-06-03' AND END_WEEK = '2019-06-09' THEN 'WEEK 10'
    WHEN START_WEEK = '2019-06-10' AND END_WEEK = '2019-06-16' THEN 'WEEK 11'
    WHEN START_WEEK = '2019-06-17' AND END_WEEK = '2019-06-23' THEN 'WEEK 12'
    WHEN START_WEEK = '2019-06-24' AND END_WEEK = '2019-06-30' THEN 'WEEK 13'
    WHEN START_WEEK = '2019-07-01' AND END_WEEK = '2019-07-07' THEN 'WEEK 14'
    WHEN START_WEEK = '2019-07-08' AND END_WEEK = '2019-07-14' THEN 'WEEK 15'
    WHEN START_WEEK = '2019-07-15' AND END_WEEK = '2019-07-21' THEN 'WEEK 16'
    WHEN START_WEEK = '2019-07-22' AND END_WEEK = '2019-07-28' THEN 'WEEK 17'
    WHEN START_WEEK = '2019-07-29' AND END_WEEK = '2019-08-04' THEN 'WEEK 18'
    WHEN START_WEEK = '2019-08-05' AND END_WEEK = '2019-08-11' THEN 'WEEK 19'
    WHEN START_WEEK = '2019-08-12' AND END_WEEK = '2019-08-18' THEN 'WEEK 20'
    WHEN START_WEEK = '2019-08-19' AND END_WEEK = '2019-08-25' THEN 'WEEK 21'
    WHEN START_WEEK = '2019-08-26' AND END_WEEK = '2019-09-01' THEN 'WEEK 22'
    WHEN START_WEEK = '2019-09-02' AND END_WEEK = '2019-09-08' THEN 'WEEK 23'
    WHEN START_WEEK = '2019-09-09' AND END_WEEK = '2019-09-15' THEN 'WEEK 24'
    WHEN START_WEEK = '2019-09-16' AND END_WEEK = '2019-09-22' THEN 'WEEK 25'
    WHEN START_WEEK = '2019-09-23' AND END_WEEK = '2019-09-29' THEN 'WEEK 26'
    WHEN START_WEEK = '2019-09-30' AND END_WEEK = '2019-10-06' THEN 'WEEK 27'
    WHEN START_WEEK = '2019-10-07' AND END_WEEK = '2019-10-13' THEN 'WEEK 28'
    WHEN START_WEEK = '2019-10-14' AND END_WEEK = '2019-10-20' THEN 'WEEK 29'
    WHEN START_WEEK = '2019-10-21' AND END_WEEK = '2019-10-27' THEN 'WEEK 30'
    WHEN START_WEEK = '2019-10-28' AND END_WEEK = '2019-11-03' THEN 'WEEK 31'
    WHEN START_WEEK = '2019-11-04' AND END_WEEK = '2019-11-10' THEN 'WEEK 32'
    WHEN START_WEEK = '2019-11-11' AND END_WEEK = '2019-11-17' THEN 'WEEK 33'
    WHEN START_WEEK = '2019-11-18' AND END_WEEK = '2019-11-24' THEN 'WEEK 34'
    WHEN START_WEEK = '2019-11-25' AND END_WEEK = '2019-12-01' THEN 'WEEK 35'
    WHEN START_WEEK = '2019-12-02' AND END_WEEK = '2019-12-08' THEN 'WEEK 36'
    WHEN START_WEEK = '2019-12-09' AND END_WEEK = '2019-12-15' THEN 'WEEK 37'
    WHEN START_WEEK = '2019-12-16' AND END_WEEK = '2019-12-22' THEN 'WEEK 38'
    WHEN START_WEEK = '2019-12-23' AND END_WEEK = '2019-12-29' THEN 'WEEK 39'
    WHEN START_WEEK = '2019-12-30' AND END_WEEK = '2020-01-05' THEN 'WEEK 40'
    WHEN START_WEEK = '2020-01-06' AND END_WEEK = '2020-01-12' THEN 'WEEK 41'
    WHEN START_WEEK = '2020-01-13' AND END_WEEK = '2020-01-19' THEN 'WEEK 42'
    WHEN START_WEEK = '2020-01-20' AND END_WEEK = '2020-01-26' THEN 'WEEK 43'
    WHEN START_WEEK = '2020-01-27' AND END_WEEK = '2020-02-02' THEN 'WEEK 44'
    WHEN START_WEEK = '2020-02-03' AND END_WEEK = '2020-02-09' THEN 'WEEK 45'
    WHEN START_WEEK = '2020-02-10' AND END_WEEK = '2020-02-16' THEN 'WEEK 46'
    WHEN START_WEEK = '2020-02-17' AND END_WEEK = '2020-02-23' THEN 'WEEK 47'
    WHEN START_WEEK = '2020-02-24' AND END_WEEK = '2020-03-01' THEN 'WEEK 48'
    WHEN START_WEEK = '2020-03-02' AND END_WEEK = '2020-03-08' THEN 'WEEK 49'
    WHEN START_WEEK = '2020-03-09' AND END_WEEK = '2020-03-15' THEN 'WEEK 50'
    WHEN START_WEEK = '2020-03-16' AND END_WEEK = '2020-03-22' THEN 'WEEK 51'
    WHEN START_WEEK = '2020-03-23' AND END_WEEK = '2020-03-29' THEN 'WEEK 52'
  END AS FY_WEEK
 FROM @TABLE
 ORDER BY START_WEEK,END_WEEK;

My problem is the Fiscal Week (FY_WEEK) column, I don't want to hard-code those START_WEEK and END_WEEK value.

I'm looking for a way where I can dynamically populate my fiscal week column instead of hardcoding values.

Body:
You can use recursive cte (as below shown in below query) or tally table without the temp table / table variable

DECLARE @START_DATE DATE
DECLARE @END_DATE DATE

SET @START_DATE = '2019-04-01'
SET @END_DATE = '2020-03-31'

-- Change the start date to the `Monday` of the week
SELECT  @START_DATE = DATEADD(DAY,
                            - (@@DATEFIRST+ DATEPART(WEEKDAY, @START_DATE) - 1 + 6) % 7,
                              @START_DATE)

; WITH CTE as
(
    SELECT  START_WEEK = @START_DATE, END_WEEK = DATEADD(DAY, 6, @START_DATE),
            FY_WEEK = 1

    UNION ALL

    SELECT  START_WEEK = DATEADD(DAY, 7, START_WEEK), END_WEEK = DATEADD(DAY, 7, END_WEEK),
            FY_WEEK = FY_WEEK + 1
    FROM    CTE
    WHERE   DATEADD(DAY, 7, START_WEEK) <= @END_DATE
)
SELECT  *
FROM    CTE
OPTION (MAXRECURSION 52)

this does not depends on the DATEFIRST settings


问:
How to delete files end with a substring and older than N days
I want to delete extensionless files older than 7 days whose names end with _C.

Example files:

```<code>B_C_A1_C
B_C_A2_C
B_C_A3_A
test.txt
</code>```

My code:

```<code>SET mypath=%cd%\downloads
ForFiles /p %mypath% /d -7 /c "cmd /c del /q %mypath%\*_C
</code>```

When I execute the code, it deletes all files which contains _C, but I want to delete only files which end with _C and are older than 7 days.

How can I fix this?

答:
For more information about the forfiles documention, see Batch file to delete files older than N days.

The wildcard expression *_C selects any files which end with _C, regardless of whether it has an extension.

The final code is insanely complicated:

```<code>forfiles /p "%cd%" /m *_C /C "cmd /c \"echo @file^|find \".\" ^|^| del @path\""
</code>```

Using *_C will select the following:

```<code>anything without periods_C
</code>```

It will NOT select the following:

```<code>any.thing_C
anything.txt._C
anything containing periods_C
</code>```

Body:
I want to delete extensionless files older than 7 days whose names end with _C.

Example files:

B_C_A1_C
B_C_A2_C
B_C_A3_A
test.txt

My code:

SET mypath=%cd%\downloads
ForFiles /p %mypath% /d -7 /c "cmd /c del /q %mypath%\*_C

When I execute the code, it deletes all files which contains _C, but I want to delete only files which end with _C and are older than 7 days.

How can I fix this?

Body:
For more information about the forfiles documention, see Batch file to delete files older than N days.

The wildcard expression *_C selects any files which end with _C, regardless of whether it has an extension.

The final code is insanely complicated:

forfiles /p "%cd%" /m *_C /C "cmd /c \"echo @file^|find \".\" ^|^| del @path\""

Using *_C will select the following:

anything without periods_C

It will NOT select the following:

any.thing_C
anything.txt._C
anything containing periods_C


问:
Accessing Windows Contacts (pre Win10) from JScript (or any ActiveScripting)
I want to use the COM object with the progID Windows.Contact.1 via ActiveScripting (JScript, VBScript, Python, etc).

This COM resides in C:\Program Files (x86)\Common Files\System\wab32.dll. It seems, there is no TypeLib available for it. The COM delivers, amongst others, IContact for the "Windows Address Book" (storing contacts as XML in folders, as in Windows 7). IContact is documented here.

In JScript I did:

var co = new ActiveXObject("Windows.Contact.1");
typeof co;  // results in: unknown
```

Since it results in unknown, I have the suspicion, that this COM could not be usable for scripting. Somewhere I read, that everything, that inherits from IUnknown can not be used for scripting, instead it must inherit from IDispatch. But I am unsure, as to how much of this is valid, and whether there are workarounds.

I would like to ask for acknowledgement of my suspicions (since I am new to all of this and have no C++ or C# background) or to ask for a way, as to how to use Windows.Contact.1 from scripting, including a way, to find out, which methods/objects I can use, without resorting to a TypeLib.

I have access to pages like Programming Windows Contacts and related ones, but first I need to get an instance in ActiveScript (JScript, VBScript, Python, Lua will do). I also have access to applications like "MS OLE View" and "OLEView DotNet". Thank you.

答:
There are entire books on the subject, but here's a very simplified story. There are basically 3 "categories" of COM interfaces:

Interfaces deriving from IUnknown

aliases for programming against: early binding, (custom) vtable binding

the simplest way to implement a COM "server"

it's only a binary contract (methods layout, method signature, parameters behavior like in/out for cross-apartment/process support, ...)

you need to somewhow tell your callers what is this binary contract you support (you can use .idl, .tlb or anything that your caller can understand)

there are some official ways of documenting your IUnknown-derived interfaces: .idl -> .h and .tlb is the most standard one

only supported by a certain class of languages (for example C/C++, .NET, Delphi), those who understand .tlb (or .idl, or equivalent .h), or those who allow redefining layout manually (like .NET). You can perfectly define a language that can do that w/o ever using .tlb. That's the beauty of COM, it's just a binary contract.

if your language doesn't support it, you just can't use it, you'll have to write or use a wrapper with a language that supports it and exposes it in a way your language supports. Powershell for example doesn't support IUnknown-derived interfaces (I'm not 100% sure) but supports .NET so it can use .NET as a "super wrapper".

IDispatch interface

only requires one IUnknown well-known interface implementation: IDispatch

aliases for programming against: late binding, OLE automation, COM automation, or simply Automation (not to confuse with UI Automation)

invented for higher level languages (VB/VBA first, ActiveScripting a bit later)

only supported by a certain class of language, and the way it's supported varies (for example it's supported in C++ of course but it's not super easy w/o wrappers or tooling like Visual Studio's C++ #import directive). JScript and VBScript don't exactly support the same set of features with regards to Automation.

you're supposed to use only a predefined list of types "Automation-Compatible types":

these types where initially very related to VB/VBA (VARIANT, SAFEARRAY, BSTR which means "Basic String"...)

from the higher level language, it really makes COM much transparent and easier as that was the whole point (and can make it harder from the lower level ones...), it also allows "syntactic sugar" niceties

note the IDispatch implementation can be very dynamic and really late-bound at runtime (get id of name -> invoke) but most available programming tooling quite freezes the list of ids/names at compile time (ex: .NET) because they support Dual interfaces.

Dual interfaces:

interfaces that implement a custom IDispatch-derived interface and implement IDispatch itself to match the custom interface (both implementations supposedly being "equivalent" of course). Have a look at the link below, it has nice images.

because of IDispatch, you're supposed to use only Automation compatible data types in the IDispatch-derived method.

it's more work to implement (so it's usually done by programming tools, for ex: ATL)

a bit easier for native (C/C++, etc.) callers (no need to use IDispatch wrappers) but you still have to digest automation data types

IMHO, one of the best 1-page introduction to COM is here: Introduction to COM

Body:
I want to use the COM object with the progID Windows.Contact.1 via ActiveScripting (JScript, VBScript, Python, etc).

This COM resides in C:\Program Files (x86)\Common Files\System\wab32.dll. It seems, there is no TypeLib available for it. The COM delivers, amongst others, IContact for the "Windows Address Book" (storing contacts as XML in folders, as in Windows 7). IContact is documented here.

In JScript I did:

var co = new ActiveXObject("Windows.Contact.1");
typeof co;  // results in: unknown

Since it results in unknown, I have the suspicion, that this COM could not be usable for scripting. Somewhere I read, that everything, that inherits from IUnknown can not be used for scripting, instead it must inherit from IDispatch. But I am unsure, as to how much of this is valid, and whether there are workarounds.

I would like to ask for acknowledgement of my suspicions (since I am new to all of this and have no C++ or C# background) or to ask for a way, as to how to use Windows.Contact.1 from scripting, including a way, to find out, which methods/objects I can use, without resorting to a TypeLib.

I have access to pages like Programming Windows Contacts and related ones, but first I need to get an instance in ActiveScript (JScript, VBScript, Python, Lua will do). I also have access to applications like "MS OLE View" and "OLEView DotNet". Thank you.


问:
How to align an image at the end of the first line of a paragraph?
I have the following HTML code, which is very simple, just an image inside a paragraph.

```<code>  <p>
    <img src="https://www.w3schools.com/css/pineapple.jpg" />
      Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.
  </p>
</code>```

And it looks like this:

And I want the image to "float" to the end of the first paragraph like below:

The only way I was able to obtain this design is to insert the image at the end of the first line, but is it any CSS code that could do that?

My HTML solution is not generic and you have to manually place the image inside paragraph:

```<code>  <p>
    Lorem ipsum dolor sit amet, consectetur
    <img src="https://www.w3schools.com/css/pineapple.jpg" />
       adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.
  </p>
</code>```

答:
Just use align attribute for the image tag element,

I think this is what you want

      Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.

```
</div>
</div>
</p>

<p>As per the document on MDN the align attribute is deprecated, so CSS would be a better way to go:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  float: right;
}</code>```

      Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.

```
</div>
</div>
</p>

<p><strong>Update</strong>:</p>

<p>Solution combined from the answers: The idea is to align the image to the right with the deprecated attribute "align":</p>

<p>HTML code:</p>

```

       Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.

```

<p>CSS code:</p>

```img {
  height: 100px;
  width: 100px;
  margin-top: -85px /* this allows you to put the image upper */
}

div {
  margin-top: 100px; /* gives you space above to display the image */
}
```

Body:
I have the following HTML code, which is very simple, just an image inside a paragraph.

      Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.

And it looks like this:

And I want the image to "float" to the end of the first paragraph like below:

The only way I was able to obtain this design is to insert the image at the end of the first line, but is it any CSS code that could do that?

My HTML solution is not generic and you have to manually place the image inside paragraph:

    Lorem ipsum dolor sit amet, consectetur

       adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.

Body:
Just use align attribute for the image tag element,

I think this is what you want

<p>
    <img  align="right" src="https://www.w3schools.com/css/pineapple.jpg" />
      Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.
 </p>

As per the document on MDN the align attribute is deprecated, so CSS would be a better way to go:

img {
  float: right;
}

<p>
    <img src="https://www.w3schools.com/css/pineapple.jpg" />
      Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta. Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.  Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.
 </p>

Update:

Solution combined from the answers: The idea is to align the image to the right with the deprecated attribute "align":

HTML code:

<div>
    <p>
     <img align="right" src="https://www.w3schools.com/css/pineapple.jpg" />
       Lorem ipsum dolor sit amet, consectetur  adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates iusto, odit. Numquam, sunt, dicta.
    </p>
</div>

CSS code:

img {
  height: 100px;
  width: 100px;
  margin-top: -85px /* this allows you to put the image upper */
}

div {
  margin-top: 100px; /* gives you space above to display the image */
}


问:
How to execute a python console using Qt on win10?
I'm trying to execute a python console using QProcess and show the content of the console in a QTextEdit.
Below is my major codes:

```<code>    connect(&process, SIGNAL(readyReadStandardOutput()), this, SLOT(PrintStandardOutput()));
    connect(&process, SIGNAL(started()), this, SLOT(Started()));
    ...
    void Widget::PrintStandardOutput()
    {
        QString stdOtuput = QString::fromLocal8Bit(process.readAllStandardOutput());
        ui->textEdit_Output->append(stdOtuput);
    }

    void Widget::Started()
    {
        ui->stateLabel->setText("Process started...");
    }

</code>```

I used QProcess::start("python") to start a new process and QProcess::write() to write my python codes, but I can see nothing shown in my QTextEdit, by the way, the python process is indeed executed according to the stateLabel showning "Process started...". How to let the python output shown in the QTextEdit? Thanks.

答:
Try :

```<code>        connect(&process, SIGNAL(readyReadStandardOutput()), this, SLOT(PrintStandardOutput()));

        connect(&process, SIGNAL(started()), this, SLOT(Started()));

        process.setProcessChannelMode(QProcess::MergedChannels);
        process.start(processToStart, arguments)

        void Widget::PrintStandardOutput()
        {

            // Get the output
            QString output;
            if (process.waitForStarted(-1)) {
                while(process.waitForReadyRead(-1)) {
                    output += process.readAll();
                    ui->textEdit_Output->append(output);
                }
            }
            process.waitForFinished();
        }

        void Widget::Started()
        {
        ui->stateLabel->setText("Process started...");
        }
</code>```

setProcessChannelMode(QProcess::MergedChannels) will merge the output channels. Various programs write to different outputs. Some use the error output for their normal logging, some use the "standard" output, some both. Better to merge them.

readAll() reads everything available so far.

It is put in a loop with waitForReadyRead(-1) (-1 means no timeout), which will block until something is available to read. This is to make sure that everything is actually read.
Simply calling readAll() after the process is finished has turned out to be highly unreliable (buffer might already be empty).

Body:
I'm trying to execute a python console using QProcess and show the content of the console in a QTextEdit.
Below is my major codes:

    connect(&process, SIGNAL(readyReadStandardOutput()), this, SLOT(PrintStandardOutput()));
    connect(&process, SIGNAL(started()), this, SLOT(Started()));
    ...
    void Widget::PrintStandardOutput()
    {
        QString stdOtuput = QString::fromLocal8Bit(process.readAllStandardOutput());
        ui->textEdit_Output->append(stdOtuput);
    }

    void Widget::Started()
    {
        ui->stateLabel->setText("Process started...");
    }

I used QProcess::start("python") to start a new process and QProcess::write() to write my python codes, but I can see nothing shown in my QTextEdit, by the way, the python process is indeed executed according to the stateLabel showning "Process started...". How to let the python output shown in the QTextEdit? Thanks.

Body:
Try :

        connect(&process, SIGNAL(readyReadStandardOutput()), this, SLOT(PrintStandardOutput()));

        connect(&process, SIGNAL(started()), this, SLOT(Started()));

        process.setProcessChannelMode(QProcess::MergedChannels);
        process.start(processToStart, arguments)

        void Widget::PrintStandardOutput()
        {

            // Get the output
            QString output;
            if (process.waitForStarted(-1)) {
                while(process.waitForReadyRead(-1)) {
                    output += process.readAll();
                    ui->textEdit_Output->append(output);
                }
            }
            process.waitForFinished();
        }

        void Widget::Started()
        {
        ui->stateLabel->setText("Process started...");
        }

setProcessChannelMode(QProcess::MergedChannels) will merge the output channels. Various programs write to different outputs. Some use the error output for their normal logging, some use the "standard" output, some both. Better to merge them.

readAll() reads everything available so far.

It is put in a loop with waitForReadyRead(-1) (-1 means no timeout), which will block until something is available to read. This is to make sure that everything is actually read.
Simply calling readAll() after the process is finished has turned out to be highly unreliable (buffer might already be empty).


问:
'Where' method is not working inside the 'onChange' method
I'm trying to filter data inside a list based on search field input value. I'm running the where method on the list. Since a list has different items on different indexes, therefore I'm running this code in for loop.

Below is an example of the first item in the list;

print(pageData[0].person);

// ###### OUTPUT ######

Person(id: 2, name: james, nickname: , role: guest, phone: , email: , physical_address: s, created: 2020-02-18 09:12:56.000, updated: 2020-02-18 09:12:56.000)
```

<p>Below I'm trying to find matches using the <code>where</code> Method but I'm getting non. </p>

<pre class="lang-dart prettyprint-override"><code>Widget _buildSearchField() {
    return new TextField(
      controller: new TextEditingController(),
      autofocus: true,
      decoration: const InputDecoration(
        hintText: 'Search...',
        border: InputBorder.none,
        hintStyle: const TextStyle(color: Colors.white30),
      ),
      style: const TextStyle(color: Colors.white, fontSize: 16.0),
      onChanged: (val) {
        var i;
        var results = [];

        for (i = 0; i < pageData.length; i++) {
          print('in pageData for loop');
          var matches = pageData[i].where((data) =>
              (data.person.name.toLowerCase().contains('james') ||
                  data.person.nickname.toLowerCase().contains('james')));

/// Code below is not executing

          if (matches != null) {
            print('matches found');
            results.add(matches);
          }
          if (i == pageData.length) {
            setState(() {
              searchResults = results;
            });
          }
        }
      },
    );
  }
</code>```

How do I fix this? What I'm I doing wrong?

Thank you, posted with Love.

答:
I think you don't need both the for-loop AND the where-statement.
Try something like this:</p>

```<code>Widget _buildSearchField() {
return new TextField(
  controller: new TextEditingController(),
  autofocus: true,
  decoration: const InputDecoration(
    hintText: 'Search...',
    border: InputBorder.none,
    hintStyle: const TextStyle(color: Colors.white30),
  ),
  style: const TextStyle(color: Colors.white, fontSize: 16.0),
  onChanged: (val) {
    var i;
    var results = [];

      results = pageData.where((data) =>
       data.person.name.toLowerCase().contains('james') ||
              data.person.nickname.toLowerCase().contains('james');

      );

      setState(() {
        searchResults = results;
      });
    }
  }
);
}
</code>```

Body:
I'm trying to filter data inside a list based on search field input value. I'm running the where method on the list. Since a list has different items on different indexes, therefore I'm running this code in for loop.

Below is an example of the first item in the list;

print(pageData[0].person);

// ###### OUTPUT ######

Person(id: 2, name: james, nickname: , role: guest, phone: , email: , physical_address: s, created: 2020-02-18 09:12:56.000, updated: 2020-02-18 09:12:56.000)

Below I'm trying to find matches using the where Method but I'm getting non.

Widget _buildSearchField() {
    return new TextField(
      controller: new TextEditingController(),
      autofocus: true,
      decoration: const InputDecoration(
        hintText: 'Search...',
        border: InputBorder.none,
        hintStyle: const TextStyle(color: Colors.white30),
      ),
      style: const TextStyle(color: Colors.white, fontSize: 16.0),
      onChanged: (val) {
        var i;
        var results = [];

        for (i = 0; i < pageData.length; i++) {
          print('in pageData for loop');
          var matches = pageData[i].where((data) =>
              (data.person.name.toLowerCase().contains('james') ||
                  data.person.nickname.toLowerCase().contains('james')));

/// Code below is not executing

          if (matches != null) {
            print('matches found');
            results.add(matches);
          }
          if (i == pageData.length) {
            setState(() {
              searchResults = results;
            });
          }
        }
      },
    );
  }

How do I fix this? What I'm I doing wrong?

Thank you, posted with Love.

Body:
I think you don't need both the for-loop AND the where-statement.
Try something like this:

Widget _buildSearchField() {
return new TextField(
  controller: new TextEditingController(),
  autofocus: true,
  decoration: const InputDecoration(
    hintText: 'Search...',
    border: InputBorder.none,
    hintStyle: const TextStyle(color: Colors.white30),
  ),
  style: const TextStyle(color: Colors.white, fontSize: 16.0),
  onChanged: (val) {
    var i;
    var results = [];

      results = pageData.where((data) =>
       data.person.name.toLowerCase().contains('james') ||
              data.person.nickname.toLowerCase().contains('james');

      );

      setState(() {
        searchResults = results;
      });
    }
  }
);
}


问:
Why does my selection sort fail when I hardcode a non-zero minimum value?
My code isn't performing a selection sort successfully when I specify min = arr[0] before entering the loop to process the array, it fails.

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

int main()
{
    int arr[11] = {7, 12, 4, 28, 3, 15, 7, 3, 89, 1, 12};
    int x, i, next_index;

    /* Select first element (i = 0) first for loop and compare it with all
       elements of array till the end of array second for loop (so next
       iteration, when i = 1 the first element will be the smallest one */

    for (i = 0; i <= 10; i++)
    {
        // min = arr[0]; /* <-- WHEN I UNCOMMENT THIS THE CODE FAILS. WHY? */

        /* Select min element */
        for (next_index = i + 1; next_index <= 10; next_index++)
        {
            if (arr[next_index] < arr[i])
            {
                 /* Swap arr[i] with min value */
                 x = arr[i];
                 arr[i] = arr[next_index];
                 arr[next_index] = x;
            }
        }
     }
     printf("Sorted array: \n");

     for (i = 0; i <= 10; i++)
        printf(" %d \n", arr[i]);

     return 0;
}
</code>```

答:
For starters the both approaches are inefficient because there are redundant swaps of elements of the array.

In the second program instead of using in the body of the outer loop the statement

```<code>min=arr[i];
</code>```

you are using

```<code>min=arr[0];
</code>```

In this loop

```<code>printf("sorting array is : \n");
       for(i=0;i<=10;i++)
           {
    printf(" %d \n",min); // as i put value of min in i
           }
</code>```

you are always outputting the last value of the variable min outside the loops that sort the array.
.
Also it is a bad idea to use magic numbers like 10.

And you should declare variables in the smallest scope where they are used.

The program can look the following way

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

int main( void )
{
    int arr[] = { 7, 12, 4, 28, 3, 15, 7, 3, 89, 1, 12 };
    const size_t N = sizeof( arr ) / sizeof( *arr );

    printf( "Unsorted array: " );
    for ( size_t  i = 0; i < N; i++ )
    {
        printf(" %2d ", arr[i] );
    }
    putchar( '\n' );

    for ( size_t i = 0; i < N; i++ )
    {
        size_t min_i = i;

        for ( size_t j = i + 1; j < N; j++ )
        {
            if ( arr[j] < arr[min_i] ) min_i = j;
        }

        if ( min_i != i )
        {
            int tmp = arr[i];
            arr[i] = arr[min_i];
            arr[min_i] = tmp;
        }
    }

    printf( "sorted array:   " );
    for ( size_t  i = 0; i < N; i++ )
    {
        printf(" %2d ", arr[i] );
    }
    putchar( '\n' );

    return 0;
}
</code>```

Its output is

```<code>Unsorted array:   7  12   4  28   3  15   7   3  89   1  12
sorted array:     1   3   3   4   7   7  12  12  15  28  89
</code>```

Body:
My code isn't performing a selection sort successfully when I specify min = arr[0] before entering the loop to process the array, it fails.

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

int main()
{
    int arr[11] = {7, 12, 4, 28, 3, 15, 7, 3, 89, 1, 12};
    int x, i, next_index;

    /* Select first element (i = 0) first for loop and compare it with all
       elements of array till the end of array second for loop (so next
       iteration, when i = 1 the first element will be the smallest one */

    for (i = 0; i <= 10; i++)
    {
        // min = arr[0]; /* <-- WHEN I UNCOMMENT THIS THE CODE FAILS. WHY? */

        /* Select min element */
        for (next_index = i + 1; next_index <= 10; next_index++)
        {
            if (arr[next_index] < arr[i])
            {
                 /* Swap arr[i] with min value */
                 x = arr[i];
                 arr[i] = arr[next_index];
                 arr[next_index] = x;
            }
        }
     }
     printf("Sorted array: \n");

     for (i = 0; i <= 10; i++)
        printf(" %d \n", arr[i]);

     return 0;
}

Body:
For starters the both approaches are inefficient because there are redundant swaps of elements of the array.

In the second program instead of using in the body of the outer loop the statement

min=arr[i];

you are using

min=arr[0];

In this loop

printf("sorting array is : \n");
       for(i=0;i<=10;i++)
           {
    printf(" %d \n",min); // as i put value of min in i
           }

you are always outputting the last value of the variable min outside the loops that sort the array.
.
Also it is a bad idea to use magic numbers like 10.

And you should declare variables in the smallest scope where they are used.

The program can look the following way

#include <stdio.h>

int main( void )
{
    int arr[] = { 7, 12, 4, 28, 3, 15, 7, 3, 89, 1, 12 };
    const size_t N = sizeof( arr ) / sizeof( *arr );

    printf( "Unsorted array: " );
    for ( size_t  i = 0; i < N; i++ )
    {
        printf(" %2d ", arr[i] );
    }
    putchar( '\n' );

    for ( size_t i = 0; i < N; i++ )
    {
        size_t min_i = i;

        for ( size_t j = i + 1; j < N; j++ )
        {
            if ( arr[j] < arr[min_i] ) min_i = j;
        }

        if ( min_i != i )
        {
            int tmp = arr[i];
            arr[i] = arr[min_i];
            arr[min_i] = tmp;
        }
    }

    printf( "sorted array:   " );
    for ( size_t  i = 0; i < N; i++ )
    {
        printf(" %2d ", arr[i] );
    }
    putchar( '\n' );

    return 0;
}

Its output is

Unsorted array:   7  12   4  28   3  15   7   3  89   1  12
sorted array:     1   3   3   4   7   7  12  12  15  28  89


问:
I am trying to display data using fetch api but It doesn't display anything
```<code> window.addEventListener('load',()=>{
     let dTitle = document.getElementById('display');
     let dDescription = document.getElementById('description');
     const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
     fetch(api).then(response=>{
       return response.json();
     })
     .then(data=>{
       console.log(data);
       const{title,description}=data.articles;
       //set dom elements
       dTitle.textContent=data.title;
       dDescription.textContent=data.description;
    })
});
</code>```

dTitle, dDescription is not displayed in html tag.
I am new to JavaScript. Please help me.

答:
```<code>  dTitle.innerHTML = data.articles[0].title;
  dDescription.innerHTML = data.articles[0].description
</code>```

window.addEventListener('load', () => {
  let dTitle = document.getElementById('display');
  let dDescription = document.getElementById('description');
  const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
  fetch(api).then(response => {
      return response.json();
    })
    .then(data => {

      //set dom elements
      dTitle.innerHTML = data.articles[0].title;
      dDescription.innerHTML = data.articles[0].description;
    })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 id="display">
</h3>
<p id="description">
</p></code>```

Body:
 window.addEventListener('load',()=>{
     let dTitle = document.getElementById('display');
     let dDescription = document.getElementById('description');
     const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
     fetch(api).then(response=>{
       return response.json();
     })
     .then(data=>{
       console.log(data);
       const{title,description}=data.articles;
       //set dom elements
       dTitle.textContent=data.title;
       dDescription.textContent=data.description;
    })
});

dTitle, dDescription is not displayed in html tag.
I am new to JavaScript. Please help me.

Body:
  dTitle.innerHTML = data.articles[0].title;
  dDescription.innerHTML = data.articles[0].description

window.addEventListener('load', () => {
  let dTitle = document.getElementById('display');
  let dDescription = document.getElementById('description');
  const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
  fetch(api).then(response => {
      return response.json();
    })
    .then(data => {

      //set dom elements
      dTitle.innerHTML = data.articles[0].title;
      dDescription.innerHTML = data.articles[0].description;
    })
});

<h3 id="display">
</h3>
<p id="description">
</p>


问:
row number increases by specific conditions in more fast way R
The data frame I have looked like this.

"rank" variable has to be increased once the differences between the [i]th row of "start" and the [i-1]th row of "end" are over 14.(also, when encountered the different "ID")

I tried the code below and it worked very well.

But the thing is.. it is way too slow because I have like over 700000 rows.

 So, is there any way to make it perform much faster?

```<code>
df$rank <- 1

for(i in 2:nrow(l50.df)){
  df[i,"rank"] <- ifelse((df[i,"ID"]==df[i-1,"ID"])&
                                   (df[i-1,"diff"]<=14),
                         df[i,"rank"] <- df[i-1,"rank"],
                         df[i,"rank"] <- df[i-1,"rank"] + 1)
}
</code>```

答:
Here is a base R solution using ave + ifelse

```<code>df <- within(df,rank <- ave(diff>14, diff>14,ID,FUN = function(x) ifelse(x,seq(x),+!x)))
</code>```

Body:
The data frame I have looked like this.

"rank" variable has to be increased once the differences between the [i]th row of "start" and the [i-1]th row of "end" are over 14.(also, when encountered the different "ID")

I tried the code below and it worked very well.

But the thing is.. it is way too slow because I have like over 700000 rows.

 So, is there any way to make it perform much faster?

df$rank <- 1

for(i in 2:nrow(l50.df)){
  df[i,"rank"] <- ifelse((df[i,"ID"]==df[i-1,"ID"])&
                                   (df[i-1,"diff"]<=14),
                         df[i,"rank"] <- df[i-1,"rank"],
                         df[i,"rank"] <- df[i-1,"rank"] + 1)
}

Body:
Here is a base R solution using ave + ifelse

df <- within(df,rank <- ave(diff>14, diff>14,ID,FUN = function(x) ifelse(x,seq(x),+!x)))


问:
Where to keep git submodules inside of a go project?
I want to add a submodule to my go project.

The submodule will contain some .proto files and some go files. I will use protos to generate grpc-gateway files using my Makefile, which will have the same package as the go files in the repo. The repo which contains these protos is not mine, and others are developing it. I won't commit these gateway files generated.

Is there any specific structure for such files in golang projects? Should I keep them in pkg directory?

I have three folders of build, configs, templates currently in my project.

答:
If you want to keep your project dependencies inside your project then you better keep them inside a vendor directory.

But usually I use go modules for that.

Also might be useful for you:
https://github.com/golang-standards/project-layout


问:
How to create buttons of diffrent sizes in a toolbar control (Win32 API)
I want to insert buttons of diffrent sizes in a toolbar.
Lets say for example 2 buttons. One have a size of 32x16, the Other 16x16.
I used Two Image Lists. Each image list has it's own image size (1st 32x16 - 2nd 16x16).
But the problem is, when I compile the code i get the images loaded correctly but the buttons have the same width(32).

code:

```<code>//(1) Create the Toolbar ImageList
HIMAGELIST hImageListLarge = ImageList_Create(32, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListLarge)
    return false;

HIMAGELIST hImageListSmall = ImageList_Create(16, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListSmall)
    return false;

//(2) Fill the Image List
if (ImageList_Add(hImageListLarge,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO_MASK))) == -1)
    return false;

if (ImageList_Add(hImageListSmall,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP_MASK))) == -1)
    return false;

//(3) Create the Toolbar window
m_hToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, nullptr,
    WS_CHILD | TBSTYLE_WRAPABLE | TBSTYLE_AUTOSIZE | TBSTYLE_LIST | TBSTYLE_TOOLTIPS ,
    0, 0, 0, 0, m_hWnd, nullptr, m_hInstance, nullptr);

if (m_hToolbar == nullptr)
    return false;

//(4) Sets the Image list for the Toolbar
SendMessage(m_hToolbar, CCM_SETVERSION, 5, 0);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 0, (LPARAM)hImageListLarge);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 1, (LPARAM)hImageListSmall);

//(5) Initialize the TBBUTTON structures for each button
m_tbButtons[0].fsStyle = BTNS_SEP;

m_tbButtons[1].iBitmap = MAKELONG(0, 0);
m_tbButtons[1].idCommand = ID_CONNECTIONS_CONNECT_TO;
m_tbButtons[1].fsState = TBSTATE_ENABLED;
m_tbButtons[1].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE;
m_tbButtons[1].iString = (INT_PTR)TEXT("Connect to");

m_tbButtons[2].iBitmap = MAKELONG(0, 1);
m_tbButtons[2].idCommand = ID_HELP_ABOUT;
m_tbButtons[2].fsState = TBSTATE_ENABLED;
m_tbButtons[2].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE ;
m_tbButtons[2].iString = (INT_PTR)TEXT("Help");

//(6) Add buttons to the toolbar
SendMessage(m_hToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
SendMessage(m_hToolbar, TB_ADDBUTTONS, 3, (LPARAM)m_tbButtons);

//(7) auto Resize the toolbar
SendMessage(m_hToolbar, TB_AUTOSIZE, 0, 0);
SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
ShowWindow(m_hToolbar, SW_SHOW);

//(8) Modify the size of the separator that will hold the combobox
TBBUTTONINFO tbbi;
tbbi.cbSize = sizeof(tbbi);
tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
tbbi.cx = 500;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)0, (LPARAM)& tbbi);

tbbi.cx = 32;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)1, (LPARAM)& tbbi);

tbbi.cx = 16;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)2, (LPARAM)& tbbi);

//(9) Get the Rectangle occupied by the separator
RECT rcSep;
SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

//(10) Create the hosts comboBox
m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
    rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
    (HMENU)IDC_COMBO_HOSTS, m_hInstance, nullptr);

if (!m_hComboHosts)
    return false;

return true;
</code>```

答:
After a quick check, please modify the following code:

Comment this line of code：

```<code>SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
</code>```

TBSTYLE_EX_MIXEDBUTTONS

Version 5.81. This style allows you to set text for all buttons, but
  only display it for those buttons with the BTNS_SHOWTEXT button style.
  The TBSTYLE_LIST style must also be set. Normally, when a button does
  not display text, your application must handle TBN_GETINFOTIP or
  TTN_GETDISPINFO to display a tooltip. With the TBSTYLE_EX_MIXEDBUTTONS
  extended style, text that is set but not displayed on a button will
  automatically be used as the button's tooltip text. Your application
  only needs to handle TBN_GETINFOTIP or or TTN_GETDISPINFO if it needs
  more flexibility in specifying the tooltip text.

When you set TBSTYLE_EX_MIXEDBUTTONS style, it will allow you to set text for all buttons.

After testing, this style will prevent you from changing the width of the button.

If you want to display the button text, just add the BTNS_SHOWTEXT style.

Modified code:

```<code>//(1) Create the Toolbar ImageList
    HIMAGELIST hImageListLarge = ImageList_Create(32, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
    if (!hImageListLarge)
        return false;

    HIMAGELIST hImageListSmall = ImageList_Create(16, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
    if (!hImageListSmall)
        return false;

    //(2) Fill the Image List
    if (ImageList_Add(hImageListLarge,
        LoadBitmap(hInst, MAKEINTRESOURCE(IDB_TB_CONNECT_TO)),
        LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO_MASK))) == -1)
        return false;

    if (ImageList_Add(hImageListSmall,
        LoadBitmap(hInst, MAKEINTRESOURCE(IDB_TB_HELP)),
        LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP_MASK))) == -1)
        return false;

    //(3) Create the Toolbar window
    m_hToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, nullptr,
        WS_CHILD | TBSTYLE_WRAPABLE | TBSTYLE_AUTOSIZE | TBSTYLE_LIST | TBSTYLE_TOOLTIPS,
        0, 0, 0, 0, m_hWnd, nullptr, hInst, nullptr);

    if (m_hToolbar == nullptr)
        return false;

    //(4) Sets the Image list for the Toolbar
    SendMessage(m_hToolbar, CCM_SETVERSION, 5, 0);
    SendMessage(m_hToolbar, TB_SETIMAGELIST, 0, (LPARAM)hImageListLarge);
    SendMessage(m_hToolbar, TB_SETIMAGELIST, 1, (LPARAM)hImageListSmall);

    //(5) Initialize the TBBUTTON structures for each button

    m_tbButtons[0].fsStyle = BTNS_SEP;

    m_tbButtons[1].iBitmap = MAKELONG(0, 0);
    m_tbButtons[1].idCommand = ID_CONNECTIONS_CONNECT_TO;
    m_tbButtons[1].fsState = TBSTATE_ENABLED;
    m_tbButtons[1].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE; // If you want display text, you can add BTNS_SHOWTEXT
    m_tbButtons[1].iString = (INT_PTR)TEXT("Connect to");

    m_tbButtons[2].iBitmap = MAKELONG(0, 1);
    m_tbButtons[2].idCommand = ID_HELP_ABOUT;
    m_tbButtons[2].fsState = TBSTATE_ENABLED;
    m_tbButtons[2].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE;
    m_tbButtons[2].iString = (INT_PTR)TEXT("Help");

    //(6) Add buttons to the toolbar
    SendMessage(m_hToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
    SendMessage(m_hToolbar, TB_ADDBUTTONS, 3, (LPARAM)m_tbButtons);

    //(7) auto Resize the toolbar
    SendMessage(m_hToolbar, TB_AUTOSIZE, 0, 0);
    //SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
    ShowWindow(m_hToolbar, SW_SHOW);

    //(8) Modify the size of the separator that will hold the combobox
    TBBUTTONINFO tbbi;
    tbbi.cbSize = sizeof(tbbi);
    tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
    tbbi.cx = 44;
    SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)1, (LPARAM)& tbbi);

    tbbi.cx = 27;
    SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)2, (LPARAM)& tbbi);

    //(9) Get the Rectangle occupied by the separator
    RECT rcSep;
    SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

    //(10) Create the hosts comboBox
    m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
        rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
        (HMENU)IDC_COMBO_HOSTS, hInst, nullptr);

    if (!m_hComboHosts)
        return false;

return true;
</code>```

Body:
I want to insert buttons of diffrent sizes in a toolbar.
Lets say for example 2 buttons. One have a size of 32x16, the Other 16x16.
I used Two Image Lists. Each image list has it's own image size (1st 32x16 - 2nd 16x16).
But the problem is, when I compile the code i get the images loaded correctly but the buttons have the same width(32).

code:

//(1) Create the Toolbar ImageList
HIMAGELIST hImageListLarge = ImageList_Create(32, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListLarge)
    return false;

HIMAGELIST hImageListSmall = ImageList_Create(16, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
if (!hImageListSmall)
    return false;

//(2) Fill the Image List
if (ImageList_Add(hImageListLarge,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO_MASK))) == -1)
    return false;

if (ImageList_Add(hImageListSmall,
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP)),
    LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP_MASK))) == -1)
    return false;

//(3) Create the Toolbar window
m_hToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, nullptr,
    WS_CHILD | TBSTYLE_WRAPABLE | TBSTYLE_AUTOSIZE | TBSTYLE_LIST | TBSTYLE_TOOLTIPS ,
    0, 0, 0, 0, m_hWnd, nullptr, m_hInstance, nullptr);

if (m_hToolbar == nullptr)
    return false;

//(4) Sets the Image list for the Toolbar
SendMessage(m_hToolbar, CCM_SETVERSION, 5, 0);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 0, (LPARAM)hImageListLarge);
SendMessage(m_hToolbar, TB_SETIMAGELIST, 1, (LPARAM)hImageListSmall);

//(5) Initialize the TBBUTTON structures for each button
m_tbButtons[0].fsStyle = BTNS_SEP;

m_tbButtons[1].iBitmap = MAKELONG(0, 0);
m_tbButtons[1].idCommand = ID_CONNECTIONS_CONNECT_TO;
m_tbButtons[1].fsState = TBSTATE_ENABLED;
m_tbButtons[1].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE;
m_tbButtons[1].iString = (INT_PTR)TEXT("Connect to");

m_tbButtons[2].iBitmap = MAKELONG(0, 1);
m_tbButtons[2].idCommand = ID_HELP_ABOUT;
m_tbButtons[2].fsState = TBSTATE_ENABLED;
m_tbButtons[2].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE ;
m_tbButtons[2].iString = (INT_PTR)TEXT("Help");

//(6) Add buttons to the toolbar
SendMessage(m_hToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
SendMessage(m_hToolbar, TB_ADDBUTTONS, 3, (LPARAM)m_tbButtons);

//(7) auto Resize the toolbar
SendMessage(m_hToolbar, TB_AUTOSIZE, 0, 0);
SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
ShowWindow(m_hToolbar, SW_SHOW);

//(8) Modify the size of the separator that will hold the combobox
TBBUTTONINFO tbbi;
tbbi.cbSize = sizeof(tbbi);
tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
tbbi.cx = 500;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)0, (LPARAM)& tbbi);

tbbi.cx = 32;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)1, (LPARAM)& tbbi);

tbbi.cx = 16;
SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)2, (LPARAM)& tbbi);

//(9) Get the Rectangle occupied by the separator
RECT rcSep;
SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

//(10) Create the hosts comboBox
m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
    rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
    (HMENU)IDC_COMBO_HOSTS, m_hInstance, nullptr);

if (!m_hComboHosts)
    return false;

return true;

Body:
After a quick check, please modify the following code:

Comment this line of code：

SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);

TBSTYLE_EX_MIXEDBUTTONS

Version 5.81. This style allows you to set text for all buttons, but
  only display it for those buttons with the BTNS_SHOWTEXT button style.
  The TBSTYLE_LIST style must also be set. Normally, when a button does
  not display text, your application must handle TBN_GETINFOTIP or
  TTN_GETDISPINFO to display a tooltip. With the TBSTYLE_EX_MIXEDBUTTONS
  extended style, text that is set but not displayed on a button will
  automatically be used as the button's tooltip text. Your application
  only needs to handle TBN_GETINFOTIP or or TTN_GETDISPINFO if it needs
  more flexibility in specifying the tooltip text.

When you set TBSTYLE_EX_MIXEDBUTTONS style, it will allow you to set text for all buttons.

After testing, this style will prevent you from changing the width of the button.

If you want to display the button text, just add the BTNS_SHOWTEXT style.

Modified code:

//(1) Create the Toolbar ImageList
    HIMAGELIST hImageListLarge = ImageList_Create(32, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
    if (!hImageListLarge)
        return false;

    HIMAGELIST hImageListSmall = ImageList_Create(16, 16, ILC_COLOR8 | ILC_MASK, 1, 0);
    if (!hImageListSmall)
        return false;

    //(2) Fill the Image List
    if (ImageList_Add(hImageListLarge,
        LoadBitmap(hInst, MAKEINTRESOURCE(IDB_TB_CONNECT_TO)),
        LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_CONNECT_TO_MASK))) == -1)
        return false;

    if (ImageList_Add(hImageListSmall,
        LoadBitmap(hInst, MAKEINTRESOURCE(IDB_TB_HELP)),
        LoadBitmap(m_hInstance, MAKEINTRESOURCE(IDB_TB_HELP_MASK))) == -1)
        return false;

    //(3) Create the Toolbar window
    m_hToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, nullptr,
        WS_CHILD | TBSTYLE_WRAPABLE | TBSTYLE_AUTOSIZE | TBSTYLE_LIST | TBSTYLE_TOOLTIPS,
        0, 0, 0, 0, m_hWnd, nullptr, hInst, nullptr);

    if (m_hToolbar == nullptr)
        return false;

    //(4) Sets the Image list for the Toolbar
    SendMessage(m_hToolbar, CCM_SETVERSION, 5, 0);
    SendMessage(m_hToolbar, TB_SETIMAGELIST, 0, (LPARAM)hImageListLarge);
    SendMessage(m_hToolbar, TB_SETIMAGELIST, 1, (LPARAM)hImageListSmall);

    //(5) Initialize the TBBUTTON structures for each button

    m_tbButtons[0].fsStyle = BTNS_SEP;

    m_tbButtons[1].iBitmap = MAKELONG(0, 0);
    m_tbButtons[1].idCommand = ID_CONNECTIONS_CONNECT_TO;
    m_tbButtons[1].fsState = TBSTATE_ENABLED;
    m_tbButtons[1].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE; // If you want display text, you can add BTNS_SHOWTEXT
    m_tbButtons[1].iString = (INT_PTR)TEXT("Connect to");

    m_tbButtons[2].iBitmap = MAKELONG(0, 1);
    m_tbButtons[2].idCommand = ID_HELP_ABOUT;
    m_tbButtons[2].fsState = TBSTATE_ENABLED;
    m_tbButtons[2].fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE;
    m_tbButtons[2].iString = (INT_PTR)TEXT("Help");

    //(6) Add buttons to the toolbar
    SendMessage(m_hToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
    SendMessage(m_hToolbar, TB_ADDBUTTONS, 3, (LPARAM)m_tbButtons);

    //(7) auto Resize the toolbar
    SendMessage(m_hToolbar, TB_AUTOSIZE, 0, 0);
    //SendMessage(m_hToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
    ShowWindow(m_hToolbar, SW_SHOW);

    //(8) Modify the size of the separator that will hold the combobox
    TBBUTTONINFO tbbi;
    tbbi.cbSize = sizeof(tbbi);
    tbbi.dwMask = TBIF_SIZE | TBIF_BYINDEX;
    tbbi.cx = 44;
    SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)1, (LPARAM)& tbbi);

    tbbi.cx = 27;
    SendMessage(m_hToolbar, TB_SETBUTTONINFO, (WPARAM)2, (LPARAM)& tbbi);

    //(9) Get the Rectangle occupied by the separator
    RECT rcSep;
    SendMessage(m_hToolbar, TB_GETITEMRECT, (WPARAM)0, (LPARAM)& rcSep);

    //(10) Create the hosts comboBox
    m_hComboHosts = CreateWindow(WC_COMBOBOXW, nullptr, WS_CHILD | CBS_DROPDOWN | WS_VISIBLE,
        rcSep.left, rcSep.top, rcSep.right - rcSep.left, rcSep.bottom - rcSep.top, m_hToolbar,
        (HMENU)IDC_COMBO_HOSTS, hInst, nullptr);

    if (!m_hComboHosts)
        return false;

return true;


答:
Add this css code..

Css

p img {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  <img src="https://www.w3schools.com/css/pineapple.jpg" /> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates
  iusto, odit. Numquam, sunt, dicta.
</p></code>```

Title: How to align an image at the end of the first line of a paragraph?

Body:
Add this css code..

Css

p img {
  float: right;
}

<p>
  <img src="https://www.w3schools.com/css/pineapple.jpg" /> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus incidunt recusandae quae molestias corporis veniam repellat provident aliquam amet odio cupiditate animi rerum neque voluptates
  iusto, odit. Numquam, sunt, dicta.
</p>


问:
my express api works in postman but not when calling from react.It gives "TypeError: NetworkError when attempting to fetch resource."
I am creating url shortner using react and nodejs. user inputs url in react and then press submit to triggerpost request. It works fine with postman but doesn't when calling from react. I tried calling post request on different url, it works but it doesn't with work with express url
This is react front end part which calls post after submitting url

```<code>handleSubmit = async (e) => {
    e.preventDefault();
    const url = {
      originalUrl: this.state.originalUrl
    }

    const item = await fetch("http://localhost:5000/api/post", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(url)
    })
    console.log("item",item)
  }
</code>```

This is express part which works fine with postman

```<code>router.post('/post', async (req,res) => {
    const originalUrl = req.body.originalUrl;

    const urlCode = random()

    var newInput = new model({
        originalUrl,
        urlCode
    })

    var item = await newInput.save()

    return res.json({
        originalUrl:originalUrl,
        urlCode:urlCode,

    })
</code>```

答:
It might be an error of cors. You need to use the cors npm package in your server code. Use the cors as middleware. You can include this line in your index file at server-side code:-

```<code>app.use(cors())
</code>```

Visit the site given below for using cors.

https://www.npmjs.com/package/cors

Let me know if that works.

Body:
I am creating url shortner using react and nodejs. user inputs url in react and then press submit to triggerpost request. It works fine with postman but doesn't when calling from react. I tried calling post request on different url, it works but it doesn't with work with express url
This is react front end part which calls post after submitting url

handleSubmit = async (e) => {
    e.preventDefault();
    const url = {
      originalUrl: this.state.originalUrl
    }

    const item = await fetch("http://localhost:5000/api/post", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(url)
    })
    console.log("item",item)
  }

This is express part which works fine with postman

router.post('/post', async (req,res) => {
    const originalUrl = req.body.originalUrl;

    const urlCode = random()

    var newInput = new model({
        originalUrl,
        urlCode
    })

    var item = await newInput.save()

    return res.json({
        originalUrl:originalUrl,
        urlCode:urlCode,

    })

Body:
It might be an error of cors. You need to use the cors npm package in your server code. Use the cors as middleware. You can include this line in your index file at server-side code:-

app.use(cors())

Visit the site given below for using cors.

https://www.npmjs.com/package/cors

Let me know if that works.