问:
Python / Pytest: how test a CLI command?
I have a simple class with Flask_restx:

from flask_restx import Namespace, Resource

from flask import current_app

ping_namespace = Namespace("ping")

class Ping(Resource):
    def get(self):
        return {
            "status": "success",
            "message": "system up and running",
            "api_version": current_app.config["APP_VERSION"],
        }

    def pingFromCommand():
        print(current_app.config["APP_VERSION"])

ping_namespace.add_resource(Ping, "")
```

<p>This is the simple command in manage.py</p>

<pre class="lang-py prettyprint-override"><code>[...]
app = create_app()
cli = FlaskGroup(create_app=create_app)

from project.batch.v2.ping.ping import Ping

@cli.command('ping')
def ping():
    Ping.pingFromCommand()
</code>```

If I run from command line, I get the desiderated result:

(env) $ python manage.py ping
(env) $ 2.0.0
```

<p>I know how write tests for API resources with pytest, but I don't know how can I write a test for the <code>pingFromCommand</code> method.</p>

<p>I did try:</p>

<pre class="lang-py prettyprint-override"><code>from project.batch.v2.ping.ping import Ping

def test_ping_command(test_app):
    assert Ping.pingFromCommand() == "0.0.0"
</code>```

But I get

>       assert Ping.pingFromCommand() == "0.0.0"
E       AssertionError: assert None == '0.0.0'
E        +  where None = <function Ping.pingFromCommand at 0x7fd41c619160>()
E        +    where <function Ping.pingFromCommand at 0x7fd41c619160> = Ping.pingFromCommand
```

Someone can help me or address me? Thank you in advance.

答:
In the pingFromCommand function, print is used to print the current app version. That function returns None which is what you get in the AssertionError.

You can update the function to return the app version

```<code>def pingFromCommand():
    return current_app.config["APP_VERSION"]
</code>```

Or you might be able to use capsys fixture provided by pytest which will capture
standard output:

```<code>def test_ping_command(capsys, test_app):
    Ping.pingFromCommand()
    captured = capsys.readouterr()  # Capture output
    assert captured.out == "0.0.0"  # Assert stdout
</code>```

Body:
I have a simple class with Flask_restx:

from flask_restx import Namespace, Resource

from flask import current_app

ping_namespace = Namespace("ping")

class Ping(Resource):
    def get(self):
        return {
            "status": "success",
            "message": "system up and running",
            "api_version": current_app.config["APP_VERSION"],
        }

    def pingFromCommand():
        print(current_app.config["APP_VERSION"])

ping_namespace.add_resource(Ping, "")

This is the simple command in manage.py

[...]
app = create_app()
cli = FlaskGroup(create_app=create_app)

from project.batch.v2.ping.ping import Ping

@cli.command('ping')
def ping():
    Ping.pingFromCommand()

If I run from command line, I get the desiderated result:

(env) $ python manage.py ping
(env) $ 2.0.0

I know how write tests for API resources with pytest, but I don't know how can I write a test for the pingFromCommand method.

I did try:

from project.batch.v2.ping.ping import Ping

def test_ping_command(test_app):
    assert Ping.pingFromCommand() == "0.0.0"

But I get

>       assert Ping.pingFromCommand() == "0.0.0"
E       AssertionError: assert None == '0.0.0'
E        +  where None = <function Ping.pingFromCommand at 0x7fd41c619160>()
E        +    where <function Ping.pingFromCommand at 0x7fd41c619160> = Ping.pingFromCommand

Someone can help me or address me? Thank you in advance.

Body:
In the pingFromCommand function, print is used to print the current app version. That function returns None which is what you get in the AssertionError.

You can update the function to return the app version

def pingFromCommand():
    return current_app.config["APP_VERSION"]

Or you might be able to use capsys fixture provided by pytest which will capture
standard output:

def test_ping_command(capsys, test_app):
    Ping.pingFromCommand()
    captured = capsys.readouterr()  # Capture output
    assert captured.out == "0.0.0"  # Assert stdout


来源: stackexchange

问:
Attempt to invoke virtual method 'android.view.View android.widget.ImageView.findViewById(int)' on a null object reference
I am trying to retrieve data from firebase but my app is keep crashing. i have tried many solution but nothing is working.
In my app i am trying to retrieve name,image,descriptions,price form my Firebase database.
I have written this flowing code to display data in Card view.

my code:-
Main Activity

```<code>public class MainActivity extends AppCompatActivity {
private DatabaseReference ProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
    recyclerView = findViewById(R.id.recycler_menu);
    recyclerView.setHasFixedSize(true);
    layoutManager= new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    FirebaseRecyclerOptions<Products> options =
            new FirebaseRecyclerOptions.Builder<Products>()
                    .setQuery(ProductsRef, Products.class)
                    .build();
    FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
            new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull ProductViewHolder holder, int position, @NonNull Products model) {
                    holder.textProductName.setText(model.getName());
                    holder.textProductDescription.setText(model.getDescription());
                    holder.textProductPrice.setText("Price = ₹"+model.getPrice());
                    Picasso.get().load(model.getImage()).into(holder.imageView);
                }

                @NonNull
                @Override
                public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent,false);
                    ProductViewHolder holder = new ProductViewHolder(view);
                    return holder;
                }
            };
    recyclerView.setAdapter(adapter);
    adapter.startListening();
}
</code>```

}

Products Activity

```<code>public class Products {
private String  description, image,name,price ;
public Products() {
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}
</code>```

}

ProductViewHolder Activity

```<code>              [enter image description here][1]public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textProductName, textProductDescription, textProductPrice;
public ImageView imageView;
public ProductViewHolder(@NonNull View itemView) {
    super(itemView);
    imageView= imageView.findViewById(R.id.product_image);
    textProductName = textProductName.findViewById(R.id.product_name);
    textProductDescription = textProductDescription.findViewById(R.id.product_description);
    textProductPrice = textProductPrice.findViewById(R.id.product_price);
}

@Override
public void onClick(View v) {

}
</code>```

}

答:
It seems that your assignments at ProductViewHolder are wrong, try this:

```<code>public ProductViewHolder(@NonNull View itemView) {
super(itemView);
imageView= itemView.findViewById(R.id.product_image);
textProductName = itemView.findViewById(R.id.product_name);
textProductDescription = itemView.findViewById(R.id.product_description);
textProductPrice = itemView.findViewById(R.id.product_price);}
</code>```

Hope I helped!

ContentLicense: CC BY-SA 4.0

Body:
I am trying to retrieve data from firebase but my app is keep crashing. i have tried many solution but nothing is working.
In my app i am trying to retrieve name,image,descriptions,price form my Firebase database.
I have written this flowing code to display data in Card view.

my code:-
Main Activity

public class MainActivity extends AppCompatActivity {
private DatabaseReference ProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
    recyclerView = findViewById(R.id.recycler_menu);
    recyclerView.setHasFixedSize(true);
    layoutManager= new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    FirebaseRecyclerOptions<Products> options =
            new FirebaseRecyclerOptions.Builder<Products>()
                    .setQuery(ProductsRef, Products.class)
                    .build();
    FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
            new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull ProductViewHolder holder, int position, @NonNull Products model) {
                    holder.textProductName.setText(model.getName());
                    holder.textProductDescription.setText(model.getDescription());
                    holder.textProductPrice.setText("Price = ₹"+model.getPrice());
                    Picasso.get().load(model.getImage()).into(holder.imageView);
                }

                @NonNull
                @Override
                public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent,false);
                    ProductViewHolder holder = new ProductViewHolder(view);
                    return holder;
                }
            };
    recyclerView.setAdapter(adapter);
    adapter.startListening();
}

}

Products Activity

public class Products {
private String  description, image,name,price ;
public Products() {
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

}

ProductViewHolder Activity

              [enter image description here][1]public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textProductName, textProductDescription, textProductPrice;
public ImageView imageView;
public ProductViewHolder(@NonNull View itemView) {
    super(itemView);
    imageView= imageView.findViewById(R.id.product_image);
    textProductName = textProductName.findViewById(R.id.product_name);
    textProductDescription = textProductDescription.findViewById(R.id.product_description);
    textProductPrice = textProductPrice.findViewById(R.id.product_price);
}

@Override
public void onClick(View v) {

}

}

Body:
It seems that your assignments at ProductViewHolder are wrong, try this:

public ProductViewHolder(@NonNull View itemView) {
super(itemView);
imageView= itemView.findViewById(R.id.product_image);
textProductName = itemView.findViewById(R.id.product_name);
textProductDescription = itemView.findViewById(R.id.product_description);
textProductPrice = itemView.findViewById(R.id.product_price);}

Hope I helped!


问:
osx - How to get a process id (PID) programmatically?
How can I get a process' ID? I require the ID in order to kill that process. I know the name of the process.

Thanks!

答: The best approach is to use -[NSWorkspace launchedApplications] for 10.5- and -[NSWorkspace runningApplicattions] for 10.6+ apps. One returns a dictionary with specified keys, including process ID and bundle name and location info (when available), the other an NSRunningApplication object.</p>

ContentLicense: CC BY-SA 3.0


问:
Problems to get the data from Ionic Storage
I have a problem with the Ionic-Storage.
I want to save a boolean into the storage. The action is triggered by an ion-toggle. If the toggle is on= true, otherwise false. So I have create a service, which can save and get the data.

Storage-Service.ts

```<code>const ITEM_KEY = 'modal-myworkplace';
[...]

async setItem(value){
  const res = await this.storage.set(ITEM_KEY,value)
   console.log(res)
 }

  async getItem() {
      await this.storage.get(ITEM_KEY).then((name) => {
          console.log('The Keyvalue is: '+name)
      })
  }
</code>```

Here is the problem...
I want to get this data in an component. Like this:
Component.ts

```<code>let saveWorkplace: boolean;
[...]
async setData(){
    await this.storage.getItem().then((name) => {
      console.log("Key: "+ name)
    })
  }
</code>```

I want to get the value from the Storage (true or false) and this should then be defined in saveWorkplace.

If I console.log this properties in the Component.ts I get an undefined object. But if i console.log the property in Storage.ts I get an Value(See Image)

I dont know how I can get only the Value true or false.

I hope anyone can help me

答:
You need to make sure you track what you return (Promise or value) and update your code accordingly:

Service:

```<code>setItem(value):Promise<any> {

  this.storage.set(ITEM_KEY,value) // you can use .then here to check saved value.

}

getItem():Promise<any> {

  return this.storage.get(ITEM_KEY);

}
</code>```

In your component since you are returning promise you can use async:

```<code>async getData() {

  return this.saveWorkplace = await this.storage.getItem()

};
</code>```

Now if you feel the need to leverage async method and read these values at the page initialization time (ngOnInit), you can do so this way:

```<code>ngOnInit() {
    this.getData().then( saved => {
        console.log(saved)
        // the rest of init code that depends on the value;

    })
};
</code>```

Body:
I have a problem with the Ionic-Storage.
I want to save a boolean into the storage. The action is triggered by an ion-toggle. If the toggle is on= true, otherwise false. So I have create a service, which can save and get the data.

Storage-Service.ts

const ITEM_KEY = 'modal-myworkplace';
[...]

async setItem(value){
  const res = await this.storage.set(ITEM_KEY,value)
   console.log(res)
 }

  async getItem() {
      await this.storage.get(ITEM_KEY).then((name) => {
          console.log('The Keyvalue is: '+name)
      })
  }

Here is the problem...
I want to get this data in an component. Like this:
Component.ts

let saveWorkplace: boolean;
[...]
async setData(){
    await this.storage.getItem().then((name) => {
      console.log("Key: "+ name)
    })
  }

I want to get the value from the Storage (true or false) and this should then be defined in saveWorkplace.

If I console.log this properties in the Component.ts I get an undefined object. But if i console.log the property in Storage.ts I get an Value(See Image)

I dont know how I can get only the Value true or false.

I hope anyone can help me

Body:
You need to make sure you track what you return (Promise or value) and update your code accordingly:

Service:

setItem(value):Promise<any> {

  this.storage.set(ITEM_KEY,value) // you can use .then here to check saved value.

}

getItem():Promise<any> {

  return this.storage.get(ITEM_KEY);

}

In your component since you are returning promise you can use async:

async getData() {

  return this.saveWorkplace = await this.storage.getItem()

};

Now if you feel the need to leverage async method and read these values at the page initialization time (ngOnInit), you can do so this way:

ngOnInit() {
    this.getData().then( saved => {
        console.log(saved)
        // the rest of init code that depends on the value;

    })
};


问:
Directory trees in C
So I have an assignment for my finals homework. It wants me to make a directory tree with some commands, similar to CMD. For example it will give me "make " and I will add directories to the tree. I got all the commands, syntax checking etc. down but I can't think how can I create the tree.

I thought about making a general tree for it, but there's a problem. When I add new folders, I need to check if it's already there and print a message if it is. I don't know a lot about tree structure but from what I know, to check them, I need to do firstChild, secondChild... until there is none which seems not the best way to do it.

I need ideas on this. I don't want you to do my homework, just a guideline for me to study would be more than enough.

答:
To check if a directory path exists you can use fstat (see: https://linux.die.net/man/2/fstat).

But if you have the full path, you will parse that and check all if every part's parent exists.

For example if the path is /usr/local/bin/test you should check if /usr exists, then /usr/local, then /usr/local/bin and finally /usr/local/bin/test.

To do this you could write a recursive function calling itself with the last folder part stripped (unless you're at the root level) before checking if the specified path exists.

Title: Directory trees in C


问:
How do I get Sum of a column in Ms Access database using Java?
I want to take the value of total sum of a column and display it in a textfield.

I used this code but it's not working.

```<code>public static String invoice() throws SQLException{
          Connection con = connect();
   String query="SELECT SUM(costM) AS totalsum from Meals";
   Statement s =con.createStatement();
   s.execute(query);
   ResultSet rs=s.getResultSet();
     String result =rs.getString("totalsum");
      return result;
     }

 //Method to apply when button clicked
    public void message() throws SQLException{

                textinv.setText(db.invoice());
    }

</code>```

答:
Please see this answer to this issue.

```<code>import java.sql.*;

class TestJava{
public static void main(String args[]){
try{
  Class.forName("com.mysql.jdbc.Driver");
  Connection con=DriverManager.getConnection(
   "jdbc:mysql://localhost:3306/shopping_cart","root","root");

   String query = "select sum(meal_cost) as totalSum from customers";
   Statement stmt=con.createStatement();
   stmt.executeQuery(query);
   ResultSet rs=stmt.getResultSet();
   while(rs.next())
      System.out.println(rs.getString(1));
      con.close();
    }
   catch(Exception e){ System.out.println(e);}
   }
   }
</code>```

Issue, you are facing is due to the cursor is not moved to the specified row. next() function is used for this.

Body:
I want to take the value of total sum of a column and display it in a textfield.

I used this code but it's not working.

public static String invoice() throws SQLException{
          Connection con = connect();
   String query="SELECT SUM(costM) AS totalsum from Meals";
   Statement s =con.createStatement();
   s.execute(query);
   ResultSet rs=s.getResultSet();
     String result =rs.getString("totalsum");
      return result;
     }

 //Method to apply when button clicked
    public void message() throws SQLException{

                textinv.setText(db.invoice());
    }

Body:
Please see this answer to this issue.

import java.sql.*;

class TestJava{
public static void main(String args[]){
try{
  Class.forName("com.mysql.jdbc.Driver");
  Connection con=DriverManager.getConnection(
   "jdbc:mysql://localhost:3306/shopping_cart","root","root");

   String query = "select sum(meal_cost) as totalSum from customers";
   Statement stmt=con.createStatement();
   stmt.executeQuery(query);
   ResultSet rs=stmt.getResultSet();
   while(rs.next())
      System.out.println(rs.getString(1));
      con.close();
    }
   catch(Exception e){ System.out.println(e);}
   }
   }

Issue, you are facing is due to the cursor is not moved to the specified row. next() function is used for this.


问:
multidimensional array merge into one array if key is same without using nested loop
```

    [
      {
        "status": true,
        "data": [
          {
            "id": 2,
            "name": "Algeria",
            "country_code": "DZ",
            "regions": [
              {
                "id": 2,
                "country_id": 2,
                "region_code": "RG01",
                "depots": [
                  {
                    "id": 5,
                    "region_id": 2,
                    "depot_code": "DP04",
                    "depot_name": "North Depot",
                    "area": [
                      {
                        "id": 1,
                        "depot_id": 5,
                        "area_code": "AR1",
                        "area_name": "Area-1"
                      },
                      {
                        "id": 2,
                        "depot_id": 5,
                        "area_code": "AR2",
                        "area_name": "Area-2"
                      }
                    ]
                  },
                  {
                    "id": 6,
                    "region_id": 2,
                    "depot_code": "DP06",
                    "depot_name": "east Depot",
                    "area": [
                      {
                        "id": 3,
                        "depot_id": 6,
                        "area_code": "AR3",
                        "area_name": "Area-3"
                      }
                    ]
                  }
                ]
              },
              {
                "id": 3,
                "country_id": 2,
                "region_code": "RG02",
                "depots": []
              }
            ]
          }
        ]
      }
    ]

 ```

i want to merge area into single array like

```

    "area": [
      {
        "id": 1,
        "depot_id": 5,
        "area_code": "AR1",
        "area_name": "Area-1"
      },
      {
        "id": 2,
        "depot_id": 5,
        "area_code": "AR2",
        "area_name": "Area-2"
      },
      {
        "id": 3,
        "depot_id": 6,
        "area_code": "AR3",
        "area_name": "Area-3"
      }
    ]

 ```

i don't want to use multiple foreach.
thanks in advance.

答:
I would not overcomplicate things, loop through you data structure. Add all areas to a collection. Prepare your data structure and i added a check to secure there is no duplicates with unique().

```<code>$data = 'your-data';
$areas = collect();

foreach($data->data as $country) {
    foreach($country->regions as $region) {
        foreach ($region->depots as $depot) {
            $areas->concat($depot->area);
        }
    }
}

$result = ['area' => $areas->unique('id')->all()];
</code>```

Body:
    [
      {
        "status": true,
        "data": [
          {
            "id": 2,
            "name": "Algeria",
            "country_code": "DZ",
            "regions": [
              {
                "id": 2,
                "country_id": 2,
                "region_code": "RG01",
                "depots": [
                  {
                    "id": 5,
                    "region_id": 2,
                    "depot_code": "DP04",
                    "depot_name": "North Depot",
                    "area": [
                      {
                        "id": 1,
                        "depot_id": 5,
                        "area_code": "AR1",
                        "area_name": "Area-1"
                      },
                      {
                        "id": 2,
                        "depot_id": 5,
                        "area_code": "AR2",
                        "area_name": "Area-2"
                      }
                    ]
                  },
                  {
                    "id": 6,
                    "region_id": 2,
                    "depot_code": "DP06",
                    "depot_name": "east Depot",
                    "area": [
                      {
                        "id": 3,
                        "depot_id": 6,
                        "area_code": "AR3",
                        "area_name": "Area-3"
                      }
                    ]
                  }
                ]
              },
              {
                "id": 3,
                "country_id": 2,
                "region_code": "RG02",
                "depots": []
              }
            ]
          }
        ]
      }
    ]

i want to merge area into single array like

    "area": [
      {
        "id": 1,
        "depot_id": 5,
        "area_code": "AR1",
        "area_name": "Area-1"
      },
      {
        "id": 2,
        "depot_id": 5,
        "area_code": "AR2",
        "area_name": "Area-2"
      },
      {
        "id": 3,
        "depot_id": 6,
        "area_code": "AR3",
        "area_name": "Area-3"
      }
    ]

i don't want to use multiple foreach.
thanks in advance.

Body:
I would not overcomplicate things, loop through you data structure. Add all areas to a collection. Prepare your data structure and i added a check to secure there is no duplicates with unique().

$data = 'your-data';
$areas = collect();

foreach($data->data as $country) {
    foreach($country->regions as $region) {
        foreach ($region->depots as $depot) {
            $areas->concat($depot->area);
        }
    }
}

$result = ['area' => $areas->unique('id')->all()];


问:
Navigation drawer title according to the Drawer item
I have used getSupportActionBar().setTitle("drawer_title"); and the title changes according to drawer item. But when I go back the title does not get updated. for eg: If I'm at dashboard-fragment toolbar-title is dashboard and after that when I go to message-fragment toolbar-title changes to message, but, after when I press back button it goes back to dashboard-fragment but the title does not updated to dashboard it remains message.

How could I update the title again??

答:
Add following line in onViewCreated method of your fragment:</p>

```<code>getSupportActionBar().setTitle("Your title here");
</code>```

Body:
Add following line in onViewCreated method of your fragment:

getSupportActionBar().setTitle("Your title here");


问:
Turning an ASP.NET Website into an AJAX-Enabled one
I have successfully downloaded and installed AJAX framework, and the control toolkit.

While trying to insert any AJAX controls such as UpdatePanels or ScriptManagers into an existent ASP.NET Web Site (which currently has no AJAX functionalities) I get the following error:

"Attempret do read or write protected memory. This is often an indicator that other memory is corrupt."

So as a test, I've created a brand new project, as an ASP.NET AJAX-Enabled Web Site, as follows:

And in the default page of this project there is an ScriptManager already, and I've been able to insert an UpdatePanel, do a little test with a label and a button updating its content to the current time.

The question is: What does an "ASP.NET AJAX-Enabled Web Site" have that an "ASP.NET Web Site" does not that prevents me from adding AJAX controls ?

答:
As far as I remember (it's been a while since I used AjaxControlToolkit) this error occurs when you attempt to modify the response stream from your code behind (ie: perform a Response.Write(); , or Response.End(); etc etc...

if the method your AsyncPostback trigger is calling is doing any kind of response stream modification then comment it out and try it again as a "proof of concept"..

hopefully this gets you going on the right track.

Dave


问:
How to post data to specific URL using WebClient in C#
I need to use "HTTP Post" with WebClient to post some data to a specific URL I have.

Now, I know this can be accomplished with WebRequest but for some reasons I want to use WebClient instead. Is that possible? If so, can someone show me some example or point me to the right direction?

答:
Here is the crisp answer:</p>

```<code>public String sendSMS(String phone, String token) {
    WebClient webClient = WebClient.create(smsServiceUrl);

    SMSRequest smsRequest = new SMSRequest();
    smsRequest.setMessage(token);
    smsRequest.setPhoneNo(phone);
    smsRequest.setTokenId(smsServiceTokenId);

    Mono<String> response = webClient.post()
          .uri(smsServiceEndpoint)
          .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
          .body(Mono.just(smsRequest), SMSRequest.class)
          .retrieve().bodyToMono(String.class);

    String deliveryResponse = response.block();
    if (deliveryResponse.equalsIgnoreCase("success")) {
      return deliveryResponse;
    }
    return null;
}
</code>```

Body:
Here is the crisp answer:

public String sendSMS(String phone, String token) {
    WebClient webClient = WebClient.create(smsServiceUrl);

    SMSRequest smsRequest = new SMSRequest();
    smsRequest.setMessage(token);
    smsRequest.setPhoneNo(phone);
    smsRequest.setTokenId(smsServiceTokenId);

    Mono<String> response = webClient.post()
          .uri(smsServiceEndpoint)
          .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
          .body(Mono.just(smsRequest), SMSRequest.class)
          .retrieve().bodyToMono(String.class);

    String deliveryResponse = response.block();
    if (deliveryResponse.equalsIgnoreCase("success")) {
      return deliveryResponse;
    }
    return null;
}


问:
what type of windows device driver can modify FindFirstFile and FindNextFile?
i need to add some files to results returned by FindFirstFile and FindNextFile under windows. Is this possible by file system filter driver or what type of drivers?

Thank you

答:
You can do this by File System Filter Driver. But you can do this by implementing a system wide API hook. I have not tried it before but you really don't need to take the pains of writing the drivers and making the system unstable in case of spoiling the driver stack.

System Wide API Hooking

API Hooking Revealed


问:
User Impersonation using Web API
How can I retrieve records behalf of another user.

Xrm.WebApi.retrieveMultipleRecords("account", "?$select=name&$top=3").then(
    function success(result) {
        for (var i = 0; i < result.entities.length; i++) {
            console.log(result.entities[i]);
        }
        // perform additional operations on retrieved records
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    }
);```

答:
I know we can do impersonation using XMLHttpRequest by passing MSCRMCallerID header. Not sure we can achieve the same in Xrm.WebApi.

This is my Prod code, doing some update/assign operation under Admin impersonation from a HTML webresource.

```<code>var entity = {};
entity["ownerid@odata.bind"] = "/systemusers(" + currentUserId + ")";

var req = new XMLHttpRequest();
req.open("PATCH", parent.Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/new_customentity(" + opptyid + ")", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("MSCRMCallerID", "0AFB2F7E-D323-E511-80F0-C4346BAC29F0"); //CRM Admin impersoantion
req.onreadystatechange = function () {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            //Success - No Return Data - Do Something
        } else {
            //Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));
</code>```

Update

Passing header is the only way and Xrm.WebApi cannot accept request headers.

Documentation says:

There are two ways you can impersonate a user, both of which are made possible by passing in a header with the corresponding user id.

Preferred: Impersonate a user based on their Azure Active Directory (AAD) object id by passing that value along with the header CallerObjectId.

Legacy: To impersonate a user based on their systemuserid you can leverage MSCRMCallerID with the corresponding guid value.

Title: User Impersonation using Web API

Body:
I know we can do impersonation using XMLHttpRequest by passing MSCRMCallerID header. Not sure we can achieve the same in Xrm.WebApi.

This is my Prod code, doing some update/assign operation under Admin impersonation from a HTML webresource.

var entity = {};
entity["ownerid@odata.bind"] = "/systemusers(" + currentUserId + ")";

var req = new XMLHttpRequest();
req.open("PATCH", parent.Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/new_customentity(" + opptyid + ")", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("MSCRMCallerID", "0AFB2F7E-D323-E511-80F0-C4346BAC29F0"); //CRM Admin impersoantion
req.onreadystatechange = function () {
    if (this.readyState === 4) {
        req.onreadystatechange = null;
        if (this.status === 204) {
            //Success - No Return Data - Do Something
        } else {
            //Xrm.Utility.alertDialog(this.statusText);
        }
    }
};
req.send(JSON.stringify(entity));

Update

Passing header is the only way and Xrm.WebApi cannot accept request headers.

Documentation says:

There are two ways you can impersonate a user, both of which are made possible by passing in a header with the corresponding user id.

Preferred: Impersonate a user based on their Azure Active Directory (AAD) object id by passing that value along with the header CallerObjectId.

Legacy: To impersonate a user based on their systemuserid you can leverage MSCRMCallerID with the corresponding guid value.


问:
Why does adding a Swift protocol in some situations not require all the normally required methods?
For example, these are valid and will compile without (all) protocol stubs

```<code>public class ViewController: UIViewController, SFSpeechRecognizerDelegate {

}

class BLEController: CBCentralManager, CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {

    }
}
</code>```

Edit:  Solved!  Creating a class without inheriting from UIViewController or CBCentralManager still does comply with the delegate protocols, but it does not comply with NSObjectProtocol.  It just seems to be that I'm attempting to use the frameworks in an unintended way.

答:
It compiles without needing the protocol stubs because all the requirement is optional. Check within the declaration of SFSpeechRecognizerDelegate it has only one requirement for a method called availabilityDidChange and you can see that it's optional from the keyword given at the beginning of the function.

In the second case, the class you have created doesn't inherit from NSObject but the first one does because it's a sub-class of UIViewController which in-turn is a sub-class of NSObject.

Body:
For example, these are valid and will compile without (all) protocol stubs

public class ViewController: UIViewController, SFSpeechRecognizerDelegate {

}

class BLEController: CBCentralManager, CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {

    }
}

Edit:  Solved!  Creating a class without inheriting from UIViewController or CBCentralManager still does comply with the delegate protocols, but it does not comply with NSObjectProtocol.  It just seems to be that I'm attempting to use the frameworks in an unintended way.


问:
Difference between keras.backend.max and keras.backend.argmax
I am a beginner in Deep Learning and while performing a practical assignment, came across the Keras documentation on keras.backend.

I went through the explanation a number of times. however, i cannot exactly understand the difference between max and argmax function.

答:
argmax is the index of maximum in an array and max is maximum value in that array. Please check the example given below

```<code>import tensorflow as tf
x = tf.constant([1,10,2,4,15])
print(tf.keras.backend.argmax(x, axis=-1).numpy()) # output 4 (index of max value 15, which is 4)
print(tf.keras.backend.max(x, axis=-1).numpy()) # output 15
</code>```

Body:
argmax is the index of maximum in an array and max is maximum value in that array. Please check the example given below

import tensorflow as tf
x = tf.constant([1,10,2,4,15])
print(tf.keras.backend.argmax(x, axis=-1).numpy()) # output 4 (index of max value 15, which is 4)
print(tf.keras.backend.max(x, axis=-1).numpy()) # output 15


问:
How to sort javascript array where first record should be specific and then follow by descending order
input array as list object like,  [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

Expected sorted descending order output as, "active" object should be first and all other descending sorted by numbers after "active" record.
Tried with below approach but it does not give me active as first entry. this sort the descending by number but active not coming first.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return (x['Active'] === true ? 1 : (y - x));
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))```

Expected output:
Active object to be first in result array and then all entries descending by numbers. like, [{ number: 2.3 , Active: true },{ number: 13.23 , Active: false },{ number: 2.21 , Active: false }]

答:
You can do something like this. Priortise selecting an element if it's active. Then, select whose number is greater.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

  arr.sort((a, b)=>{
  if(a.Active && !b.Active){
     return -1
  }else if(!a.Active && b.Active){
     return 1
  }
  return b.number - a.number //since you want in the descending number. For ascending order a.number - b.number
});

console.log(arr)```

Body:
input array as list object like,  [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

Expected sorted descending order output as, "active" object should be first and all other descending sorted by numbers after "active" record.
Tried with below approach but it does not give me active as first entry. this sort the descending by number but active not coming first.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return (x['Active'] === true ? 1 : (y - x));
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))

Expected output:
Active object to be first in result array and then all entries descending by numbers. like, [{ number: 2.3 , Active: true },{ number: 13.23 , Active: false },{ number: 2.21 , Active: false }]


问:
Can I create a dataframe from few 1d arrays as columns?
Is it possible to create a dataframe from few 1d arrays and place them as columns?
If I create a dataframe from 1 1d array everything is ok:

```<code>arr1 = np.array([11, 12, 13, 14, 15])
arr1_arr2_df = pd.DataFrame(data=arr1, index=None, columns=None)
arr1_arr2_df
Out:
    0
0  11
1  12
2  13
3  14
4  15
</code>```

But If make a datafreme form 2 arrays they are placed is rows:

```<code>arr1 = np.array([11, 12, 13, 14, 15])
arr2 = np.array([21, 22, 23, 24, 25])
arr1_arr2_df = pd.DataFrame(data=(arr1,arr2), index=None, columns=None)
arr1_arr2_df
Out:
    0   1   2   3   4
0  11  12  13  14  15
1  21  22  23  24  25
</code>```

I know that I can achieve it by using transpose:

```<code>arr1_arr2_df = arr1_arr2_df.transpose()
arr1_arr2_df
Out:
    0   1
0  11  21
1  12  22
2  13  23
3  14  24
4  15  25
</code>```

But is it possible to get it from the start?

答:
You can use a dictionary:</p>

```<code>arr1_arr2_df = pd.DataFrame(data={0:arr1,1:arr2})
</code>```

Body:
Is it possible to create a dataframe from few 1d arrays and place them as columns?
If I create a dataframe from 1 1d array everything is ok:

arr1 = np.array([11, 12, 13, 14, 15])
arr1_arr2_df = pd.DataFrame(data=arr1, index=None, columns=None)
arr1_arr2_df
Out:
    0
0  11
1  12
2  13
3  14
4  15

But If make a datafreme form 2 arrays they are placed is rows:

arr1 = np.array([11, 12, 13, 14, 15])
arr2 = np.array([21, 22, 23, 24, 25])
arr1_arr2_df = pd.DataFrame(data=(arr1,arr2), index=None, columns=None)
arr1_arr2_df
Out:
    0   1   2   3   4
0  11  12  13  14  15
1  21  22  23  24  25

I know that I can achieve it by using transpose:

arr1_arr2_df = arr1_arr2_df.transpose()
arr1_arr2_df
Out:
    0   1
0  11  21
1  12  22
2  13  23
3  14  24
4  15  25

But is it possible to get it from the start?

Body:
You can use a dictionary:

arr1_arr2_df = pd.DataFrame(data={0:arr1,1:arr2})


问:
Creating a new Dataframe using existing data in a column
I am trying to create a new dataframe based on the data shown in the below Dataframe link. Basically I need to create 6 new columns based on the value of "Keyword Type" Which gives me each article per row and all the corresponding keyword type information. So the columns would be Article ID, Sport, Competition, Context, etc... and the first row would be Article 1's corresponding info. I need it per article so I can join it to another dataframe's article column and bring this info in. Is there an efficient way to do this? Click here to view  Dataframe

Current Structure:

```<code>Article ID  | Keyword Type | Keyword Value
Article 1   | Sport        | Football
Article 1   | Team         | Manchester United
Article 1   | Language     | English
Article 1   | Context      | News
</code>```

Expected Output:

```<code>Article ID | Sport    | Team              | Language  | Context
Article 1  | Football | Manchester United | English   | News
</code>```

答:
A combination of set_index and unstack could get you your desired output:</p>
```<code>df.set_index(['Article ID','Keyword Type'])
  .unstack()
  .droplevel(0,axis=1)
  .rename_axis(None,axis=1)

            Context     Language     Sport         Team
Article ID
Article 1   News        English     Football    Manchester United
</code>```

Body:
I am trying to create a new dataframe based on the data shown in the below Dataframe link. Basically I need to create 6 new columns based on the value of "Keyword Type" Which gives me each article per row and all the corresponding keyword type information. So the columns would be Article ID, Sport, Competition, Context, etc... and the first row would be Article 1's corresponding info. I need it per article so I can join it to another dataframe's article column and bring this info in. Is there an efficient way to do this? Click here to view  Dataframe

Current Structure:

Article ID  | Keyword Type | Keyword Value
Article 1   | Sport        | Football
Article 1   | Team         | Manchester United
Article 1   | Language     | English
Article 1   | Context      | News

Expected Output:

Article ID | Sport    | Team              | Language  | Context
Article 1  | Football | Manchester United | English   | News

Body:
A combination of set_index and unstack could get you your desired output:

df.set_index(['Article ID','Keyword Type'])
  .unstack()
  .droplevel(0,axis=1)
  .rename_axis(None,axis=1)

            Context     Language     Sport         Team
Article ID
Article 1   News        English     Football    Manchester United


问:
How to embed an iframe with ActionText/Trix on Ruby on Rails?
I can't find a way to implement the functionality of embeding youtube/vimeo video is actiontext/trix.

This is what I want to achieve:

GIF source: https://github.com/basecamp/trix/issues/206#issuecomment-198479999

I've looked at all the similar questions/solutions, but nothing seems to provide an answer:

https://github.com/basecamp/trix#inserting-a-content-attachment

Can't render youtube embed iframe with rails 6 actiontext

How to display embed video with ActionText

How can we embed an iframe correctly with actiontext/trix using Ruby on Rails?

答: Check out the RailsConf2020 talk on Action Text by Chris Oliver. He goes over this exact scenario.</p>


问:
Adding an Image to a Current UIGraphics Context
I've got a slideshow that allows users to annotate slides with a simple drawing tool. Just allows you to draw on the screen with your finger and then 'save'. The save feature uses UIImagePNGRepresentation and works rather well. What I need to work out is how to 'continue' existing annotations so when a save happens it also takes into account what is already on the slide.

It works using UIImageContext and saving that image context into a file. When an image is saved it opens onto an overlay UIImageView, so if you are 'continuing' then your drawing onto an existing png file.

Is there a way I can add an existing image to the UIImageContext? Here I control the addition of the lines upon movement:

```<code>- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if(drawToggle){
        UITouch *touch = [touches anyObject];
        CGPoint currentPoint = [touch locationInView:self.view];
        currentPoint.y -= 40;

        //Define Properties
        [drawView.image drawInRect:CGRectMake(0, 0, drawView.frame.size.width, drawView.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineJoin(UIGraphicsGetCurrentContext(), kCGLineJoinBevel);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
        //Start Path
        CGContextBeginPath(UIGraphicsGetCurrentContext());
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        //Save Path to Image
        drawView.image = UIGraphicsGetImageFromCurrentImageContext();

        lastPoint = currentPoint;
    }
}
</code>```

Here is the magic saving line:

```<code>NSData *saveDrawData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
NSError *error = nil;
[saveDrawData writeToFile:dataFilePath options:NSDataWritingAtomic error:&error];
</code>```

Thanks for any help you can offer.

UPDATE:

Oops I forgot to add, when an annotation is 'saved' the Image Context is ended, so I can't use any Get Current Image Context style methods.

答:
I achieved this by adding this between my Start and End lines:

```<code>UIImage *image = [[UIImage alloc] initWithContentsOfFile:saveFilePath];
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, image.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);
</code>```

The Context Translate and Scales are necessary because converting a UIImage to a CGImage flips the image - it does this because a CGImage draws from a bottom left origin and the UIImage draws from a top left origin, the same co-ordinates on a flipped scale results in a flipped image.

Because I drew the existing image into the UIGraphicsGetCurrentContext() when I save the file it'll take this into account.

Body:
I've got a slideshow that allows users to annotate slides with a simple drawing tool. Just allows you to draw on the screen with your finger and then 'save'. The save feature uses UIImagePNGRepresentation and works rather well. What I need to work out is how to 'continue' existing annotations so when a save happens it also takes into account what is already on the slide.

It works using UIImageContext and saving that image context into a file. When an image is saved it opens onto an overlay UIImageView, so if you are 'continuing' then your drawing onto an existing png file.

Is there a way I can add an existing image to the UIImageContext? Here I control the addition of the lines upon movement:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if(drawToggle){
        UITouch *touch = [touches anyObject];
        CGPoint currentPoint = [touch locationInView:self.view];
        currentPoint.y -= 40;

        //Define Properties
        [drawView.image drawInRect:CGRectMake(0, 0, drawView.frame.size.width, drawView.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineJoin(UIGraphicsGetCurrentContext(), kCGLineJoinBevel);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
        //Start Path
        CGContextBeginPath(UIGraphicsGetCurrentContext());
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        //Save Path to Image
        drawView.image = UIGraphicsGetImageFromCurrentImageContext();

        lastPoint = currentPoint;
    }
}

Here is the magic saving line:

NSData *saveDrawData = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
NSError *error = nil;
[saveDrawData writeToFile:dataFilePath options:NSDataWritingAtomic error:&error];

Thanks for any help you can offer.

UPDATE:

Oops I forgot to add, when an annotation is 'saved' the Image Context is ended, so I can't use any Get Current Image Context style methods.

Body:
I achieved this by adding this between my Start and End lines:

UIImage *image = [[UIImage alloc] initWithContentsOfFile:saveFilePath];
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, image.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
CGContextDrawImage(UIGraphicsGetCurrentContext(), imageRect, image.CGImage);

The Context Translate and Scales are necessary because converting a UIImage to a CGImage flips the image - it does this because a CGImage draws from a bottom left origin and the UIImage draws from a top left origin, the same co-ordinates on a flipped scale results in a flipped image.

Because I drew the existing image into the UIGraphicsGetCurrentContext() when I save the file it'll take this into account.


问:
Why do I have ORA-00904 even when the column is present?
I see an error   while executing hibernate sql query.

java.sql.SQLException: ORA-00904: "table_name"."column_name": invalid identifier

When I open up the table in sqldeveloper, the column is present.

The error is only happening in PROD, not in DEV.

What should I check?

答:
I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.

For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'.  This query may give you a ORA-00904 error:

```<code>select * from table_name where x='test';
</code>```

Prefixing the table_name with the table owner eliminated the error and gives results:

```<code>select * from
</code>```

Body:
I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.

For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'.  This query may give you a ORA-00904 error:

select * from table_name where x='test';

Prefixing the table_name with the table owner eliminated the error and gives results:

select * from


问:
How to emit only last request in subscribe method
I send a form using complex logic inside concatMap operator. And all works fine, but in my subscribe method I have additional http requests, which fires 2 times instead of 1. I tried to use takeLast operator, but it didn't help. I need to make requests in subscribe method only after all requests completed in concatMap.
For example, if I have two updateMember() events, after each request I get invoked function from subscribe method.

```<code>makeRequest(value) {
  const team = toFormData(this.form.controls.profile.value);

  this.teamService
  .sendTeam(team)
  .pipe(
    concatMap(() => {
      const tasks$ = [];

      for (const [index, m] of this.form.controls.members.value.entries()) {
        const member = toFormData(m);

        if (m.id) {
          tasks$.push(this.teamService.updateMember(member, m.id).pipe(take(1)));
        } else if (!member.entries().next().done) {
          if (member.has('name')) {
            tasks$.push(this.teamService.createMember(member).pipe(take(1)));
          } else {
            (this.form.controls.members as FormArray).controls[index].markAllAsTouched();
            this.scrollToFirstInvalidControl();
          }
        }
      }

      return tasks$.length ? concat(...tasks$) : EMPTY;
    }),
  )
  .subscribe(() => {

    this.teamService.getMembers().subscribe();

  });
}
</code>```

What should I use to make only necessary requests?

答:
You are not using any value from sendTeam, you're only waiting for the completion so you can subscribe to the response an then process your data.</p>

```<code>makeRequest(value) {
  const team = toFormData(this.form.controls.profile.value);
  new Observable(subscription => {
    this.teamService
    .sendTeam(team)
    .subscribe(() => {
      const tasks$ = [];
        for (const [index, m] of this.form.controls.members.value.entries()) {
          const member = toFormData(m);

          if (m.id) {
            tasks$.push(this.teamService.updateMember(member, m.id).pipe(take(1)));
          } else if (!member.entries().next().done) {
            if (member.has('name')) {
              tasks$.push(this.teamService.createMember(member).pipe(take(1)));
            } else {
              (this.form.controls.members as FormArray).controls[index].markAllAsTouched();
              this.scrollToFirstInvalidControl();
            }
          }
        }

        subscription.next(tasks$.length ? concat(...tasks$) : EMPTY);
    });
  }).subscribe(() => {

    this.teamService.getMembers().subscribe();

  });
}
</code>```

Body:
I send a form using complex logic inside concatMap operator. And all works fine, but in my subscribe method I have additional http requests, which fires 2 times instead of 1. I tried to use takeLast operator, but it didn't help. I need to make requests in subscribe method only after all requests completed in concatMap.
For example, if I have two updateMember() events, after each request I get invoked function from subscribe method.

makeRequest(value) {
  const team = toFormData(this.form.controls.profile.value);

  this.teamService
  .sendTeam(team)
  .pipe(
    concatMap(() => {
      const tasks$ = [];

      for (const [index, m] of this.form.controls.members.value.entries()) {
        const member = toFormData(m);

        if (m.id) {
          tasks$.push(this.teamService.updateMember(member, m.id).pipe(take(1)));
        } else if (!member.entries().next().done) {
          if (member.has('name')) {
            tasks$.push(this.teamService.createMember(member).pipe(take(1)));
          } else {
            (this.form.controls.members as FormArray).controls[index].markAllAsTouched();
            this.scrollToFirstInvalidControl();
          }
        }
      }

      return tasks$.length ? concat(...tasks$) : EMPTY;
    }),
  )
  .subscribe(() => {

    this.teamService.getMembers().subscribe();

  });
}

What should I use to make only necessary requests?

Body:
You are not using any value from sendTeam, you're only waiting for the completion so you can subscribe to the response an then process your data.

makeRequest(value) {
  const team = toFormData(this.form.controls.profile.value);
  new Observable(subscription => {
    this.teamService
    .sendTeam(team)
    .subscribe(() => {
      const tasks$ = [];
        for (const [index, m] of this.form.controls.members.value.entries()) {
          const member = toFormData(m);

          if (m.id) {
            tasks$.push(this.teamService.updateMember(member, m.id).pipe(take(1)));
          } else if (!member.entries().next().done) {
            if (member.has('name')) {
              tasks$.push(this.teamService.createMember(member).pipe(take(1)));
            } else {
              (this.form.controls.members as FormArray).controls[index].markAllAsTouched();
              this.scrollToFirstInvalidControl();
            }
          }
        }

        subscription.next(tasks$.length ? concat(...tasks$) : EMPTY);
    });
  }).subscribe(() => {

    this.teamService.getMembers().subscribe();

  });
}


问:
Replacing a button
I tried to search my problem's solution but i couldnt't find it because of my bad english so i apologize if my question have an answer already.

I want place my button to there that i showed you in image. If possibly i want to do this with 'flex'. But doesn't matter.

Here is the code (i wrote just this section)

    *{
        padding:0;
        margin:0;
        box-sizing: border-box;
    }

    body{
        background-image: url('img/bg.png');
        font-family: 'Roboto', 'sans-serif';
    }

    a{
        text-decoration: none;
    }

    ul{
        list-style: none;
    }

    .container{
        padding-left:2rem;
        padding-right:2rem;
    }

    .container-deep{
        padding-left:8rem;
        padding-right:8rem;
    }

    /*about-me start*/

    .about-me .card{
        background:white;
        box-shadow:2px 2px 15px rgba(0,0,0,0.4);
        padding:4rem;
        display:flex;
        border-radius:10px;
    }

    .about-me .card-info{
        margin-left:5rem;
        display:flex;
        flex-direction: column;
    }

    .about-me .card .card-info h3{
        margin-top:.3rem;
        margin-bottom:1rem;
        font-size:.8rem;
        font-weight: bold;
    }

    .about-me .card .card-info p{
        opacity:.8;
        margin-bottom:1rem;
    }

    .about-me .card .card-info a{
        background:black;
        border: 1px solid black;
        color:white;
        padding: .7rem 1.5rem .7rem 1.5rem;
        align-self: flex-end;
        justify-self: center;
    }

    .about-me .card .card-info a:hover{
        background:white;
        color:black;
        border: 1px solid black;
    }

    .about-me .card .card-image img{
      width:125vh;
    }

    /*about-me end*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Emir">
        <meta name="keywords" content="full, stack, web, development">
        <meta name="description" content="Full Stack Web Development">
        <title>Full-Stack Web Site</title>
        <link rel="stylesheet" href="style.css">
        <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
    </head>
    <body>
        <section>
            <div class="about-me container">
                <div class="card">
                    <div class="card-image">
                        <img src="https://images.pexels.com/photos/2941570/pexels-photo-2941570.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260">
                    </div>
                    <div class="card-info">
                        <h1>About Me</h1>
                        <h3>Full-Stack Web Developer</h3>
                        <p>
                            Merhaba, ben Emir.
                            Kendimi web alanında geliştirebilmek adına sürekli araştırmalar yaparak full-stack developer olmayı hedefliyorum.
                            Yaptığım çalışmaları ve sahip olduğum referansları sunabilmek adına bu siteyi yazdım.
                        </p>
                        <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Natus illo deleniti nostrum praesentium dignissimos pariatur magnam ipsum perferendis aut ab. Voluptatum, ut sapiente. Fuga dolor corporis quis temporibus quos qui.</p>

                        Visit My Blog
                    </div>
                </div>
            </div>
        </section>

    </body>
    </html></code>```

答:
Using flex, you have to go for a column logic and space-between the child containers like so:

#container {
    display: flex;
    flex-direction: column;
    height: 45vh;
    width: 40vw;
    justify-content: space-between;
    border-style: solid;
    border-width: 2px;
    border-color: blue;
}

#button {
    border-style: solid;
    border-width: 2px;
    border-color: red;
    width: 10vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>

    <div id="container">

      <div id="text">This is the about me text</div>
      <div id="button">this is the button</div>

    </div>
  </body>
</html></code>```

Title: Replacing a button

Body:
I tried to search my problem's solution but i couldnt't find it because of my bad english so i apologize if my question have an answer already.

I want place my button to there that i showed you in image. If possibly i want to do this with 'flex'. But doesn't matter.

Here is the code (i wrote just this section)

    *{
        padding:0;
        margin:0;
        box-sizing: border-box;
    }

    body{
        background-image: url('img/bg.png');
        font-family: 'Roboto', 'sans-serif';
    }

    a{
        text-decoration: none;
    }

    ul{
        list-style: none;
    }

    .container{
        padding-left:2rem;
        padding-right:2rem;
    }

    .container-deep{
        padding-left:8rem;
        padding-right:8rem;
    }

    /*about-me start*/

    .about-me .card{
        background:white;
        box-shadow:2px 2px 15px rgba(0,0,0,0.4);
        padding:4rem;
        display:flex;
        border-radius:10px;
    }

    .about-me .card-info{
        margin-left:5rem;
        display:flex;
        flex-direction: column;
    }

    .about-me .card .card-info h3{
        margin-top:.3rem;
        margin-bottom:1rem;
        font-size:.8rem;
        font-weight: bold;
    }

    .about-me .card .card-info p{
        opacity:.8;
        margin-bottom:1rem;
    }

    .about-me .card .card-info a{
        background:black;
        border: 1px solid black;
        color:white;
        padding: .7rem 1.5rem .7rem 1.5rem;
        align-self: flex-end;
        justify-self: center;
    }

    .about-me .card .card-info a:hover{
        background:white;
        color:black;
        border: 1px solid black;
    }

    .about-me .card .card-image img{
      width:125vh;
    }

    /*about-me end*/

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="author" content="Emir">
        <meta name="keywords" content="full, stack, web, development">
        <meta name="description" content="Full Stack Web Development">
        <title>Full-Stack Web Site</title>
        <link rel="stylesheet" href="style.css">
        <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

About Me

Full-Stack Web Developer

                            Merhaba, ben Emir.
                            Kendimi web alanında geliştirebilmek adına sürekli araştırmalar yaparak full-stack developer olmayı hedefliyorum.
                            Yaptığım çalışmaları ve sahip olduğum referansları sunabilmek adına bu siteyi yazdım.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Natus illo deleniti nostrum praesentium dignissimos pariatur magnam ipsum perferendis aut ab. Voluptatum, ut sapiente. Fuga dolor corporis quis temporibus quos qui.

                        Visit My Blog

Body:
Using flex, you have to go for a column logic and space-between the child containers like so:

#container {
    display: flex;
    flex-direction: column;
    height: 45vh;
    width: 40vw;
    justify-content: space-between;
    border-style: solid;
    border-width: 2px;
    border-color: blue;
}

#button {
    border-style: solid;
    border-width: 2px;
    border-color: red;
    width: 10vw;
}

<html>
  <body>

    <div id="container">

      <div id="text">This is the about me text</div>
      <div id="button">this is the button</div>

    </div>
  </body>
</html>


问:
System.FormatException: input string was not in correct Format
Here's the code:

using System;
using manjan_in_csharp.Classes;

namespace manjan_in_csharp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("What Do You Want ? \nPress");
            Console.WriteLine("'s' to use sort");
            var wish =(char)Console.Read();        //explicitly converting to char (char)
           // Console.WriteLine(wish.GetType());
            switch (wish)
            {
                case 's':
                    Console.WriteLine("Enter the size of unsort list");
                    Sort sort = new Sort();
                    var size = int.Parse(Console.ReadLine());
                    sort.CallingSort(size);
                    break;
                default:
                    Console.WriteLine("Invalid Operation");
                    break;
            }
        }
    }
}
```

<p>Now, I only enter s when the line appears "Press s to use sort" and I get this error:</p>

<p><img src="https://i.stack.imgur.com/dprt4.png" alt="enter image description here"></p>

<p>I have no idea what's causing the problem. I mean, I enter s and then it doesn't let me do anything and the program crashes and I get that error. </p>

<p>Btw, here's the Sort class</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading;

namespace manjan_in_csharp.Classes
{
    public class Sort
    {
        public void CallingSort(int size)
        {
            var datetimenow = DateTime.Now;
            Console.WriteLine("|| Sorting Progra ||\t\t\t DATE/TIME: " + datetimenow.ToString("dd-mm-yyyy hh-mm"));
            Console.WriteLine("Now Which Sort Method you want to apply");
            Console.WriteLine("'b' for BubbleSort");
            var method = (char)Console.Read();
            switch (method)
            {
                case 'b':
                    Bubblesort(ListInitilizer(size));
                    break;
                default:
                    Console.WriteLine("There is no sort related to that");
                    break;
            }
        }
        public List<int> ListInitilizer(int size)
        {
            List<int> unsortlist = new List<int>();
            Random random = new Random();
            for (int i = 0; i < size; i++)
            {
                unsortlist.Insert(i, random.Next(0, size));
            }
            Console.WriteLine("Now the unsort list is :");
            for (int i = 0; i < size; i++)
            {
                Console.Write(unsortlist[i] + "  ");
            }
            Console.WriteLine();
            return unsortlist;
        }

        public void Bubblesort(List<int> unsortlist)
        {
            var start = DateTime.Now;
            for (int i = 0; i < unsortlist.Count; i++)
            {
                for (int j = i; j < unsortlist.Count; j++)
                {
                    if (unsortlist[j] < unsortlist[i])
                    {
                        int temp = unsortlist[i];
                        unsortlist[i] = unsortlist[j];
                        unsortlist[j] = temp;
                    }
                }
            }
            Console.WriteLine("Applying Bubblesort");
            Console.WriteLine("Items in Sorted List : "+unsortlist.Count);
            for (int i = 0; i < unsortlist.Count; i++)
            {
                Console.Write(unsortlist[i] + "  ");
            }
            var end = DateTime.Now;
            Console.WriteLine("\nTotal Duration is : " + (end - start) + " Seconds");
        }
    }
}
</code>```

答:
The problem is with the combination of these two lines of code:

```<code>var wish =(char)Console.Read();
...
var size = int.Parse(Console.ReadLine());
</code>```

The Console.Read() takes only single character from the input stream so for your input 's' followed by carriage-return. The carriage-return is discarded which will then be passed to next read i.e. Console.ReadLine().
You can either use ReadLine() for the first input as well or use ReadKey(). Modify your Main() as such

```<code>static void Main()
        {
            Console.WriteLine("What Do You Want ? \nPress");
            Console.WriteLine("'s' to use sort");
            var wish = Console.ReadKey().Key;        //explicitly converting to char (char)
                                                    // Console.WriteLine(wish.GetType());
            switch (wish)
            {
                case ConsoleKey.S:
                    Console.WriteLine("Enter the size of unsort list");
                    Sort sort = new Sort();
                    var size = int.Parse(Console.ReadLine());
                    sort.CallingSort(size);
                    break;
                default:
                    Console.WriteLine("Invalid Operation");
                    break;
            }
        }
</code>```

Body:
Here's the code:

using System;
using manjan_in_csharp.Classes;

namespace manjan_in_csharp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("What Do You Want ? \nPress");
            Console.WriteLine("'s' to use sort");
            var wish =(char)Console.Read();        //explicitly converting to char (char)
           // Console.WriteLine(wish.GetType());
            switch (wish)
            {
                case 's':
                    Console.WriteLine("Enter the size of unsort list");
                    Sort sort = new Sort();
                    var size = int.Parse(Console.ReadLine());
                    sort.CallingSort(size);
                    break;
                default:
                    Console.WriteLine("Invalid Operation");
                    break;
            }
        }
    }
}

Now, I only enter s when the line appears "Press s to use sort" and I get this error:

I have no idea what's causing the problem. I mean, I enter s and then it doesn't let me do anything and the program crashes and I get that error.

Btw, here's the Sort class

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading;

namespace manjan_in_csharp.Classes
{
    public class Sort
    {
        public void CallingSort(int size)
        {
            var datetimenow = DateTime.Now;
            Console.WriteLine("|| Sorting Progra ||\t\t\t DATE/TIME: " + datetimenow.ToString("dd-mm-yyyy hh-mm"));
            Console.WriteLine("Now Which Sort Method you want to apply");
            Console.WriteLine("'b' for BubbleSort");
            var method = (char)Console.Read();
            switch (method)
            {
                case 'b':
                    Bubblesort(ListInitilizer(size));
                    break;
                default:
                    Console.WriteLine("There is no sort related to that");
                    break;
            }
        }
        public List<int> ListInitilizer(int size)
        {
            List<int> unsortlist = new List<int>();
            Random random = new Random();
            for (int i = 0; i < size; i++)
            {
                unsortlist.Insert(i, random.Next(0, size));
            }
            Console.WriteLine("Now the unsort list is :");
            for (int i = 0; i < size; i++)
            {
                Console.Write(unsortlist[i] + "  ");
            }
            Console.WriteLine();
            return unsortlist;
        }

        public void Bubblesort(List<int> unsortlist)
        {
            var start = DateTime.Now;
            for (int i = 0; i < unsortlist.Count; i++)
            {
                for (int j = i; j < unsortlist.Count; j++)
                {
                    if (unsortlist[j] < unsortlist[i])
                    {
                        int temp = unsortlist[i];
                        unsortlist[i] = unsortlist[j];
                        unsortlist[j] = temp;
                    }
                }
            }
            Console.WriteLine("Applying Bubblesort");
            Console.WriteLine("Items in Sorted List : "+unsortlist.Count);
            for (int i = 0; i < unsortlist.Count; i++)
            {
                Console.Write(unsortlist[i] + "  ");
            }
            var end = DateTime.Now;
            Console.WriteLine("\nTotal Duration is : " + (end - start) + " Seconds");
        }
    }
}

Body:
The problem is with the combination of these two lines of code:

var wish =(char)Console.Read();
...
var size = int.Parse(Console.ReadLine());

The Console.Read() takes only single character from the input stream so for your input 's' followed by carriage-return. The carriage-return is discarded which will then be passed to next read i.e. Console.ReadLine().
You can either use ReadLine() for the first input as well or use ReadKey(). Modify your Main() as such

static void Main()
        {
            Console.WriteLine("What Do You Want ? \nPress");
            Console.WriteLine("'s' to use sort");
            var wish = Console.ReadKey().Key;        //explicitly converting to char (char)
                                                    // Console.WriteLine(wish.GetType());
            switch (wish)
            {
                case ConsoleKey.S:
                    Console.WriteLine("Enter the size of unsort list");
                    Sort sort = new Sort();
                    var size = int.Parse(Console.ReadLine());
                    sort.CallingSort(size);
                    break;
                default:
                    Console.WriteLine("Invalid Operation");
                    break;
            }
        }


答:
First sort by Active then DSC of number when the Active values are same.

const arr = [
  { number: 13.23, Active: false },
  { number: 2.21, Active: false },
  { number: 2.3, Active: true },
];

arr.sort((a, b) => {
  if (a.Active === b.Active) {
    return b.number - a.number;
  } else if (a.Active || !b.Active) {
    return -1;
  } else if (b.Active || !a.Active) {
    return 1;
  }
  return 0;
});

console.log(arr);```

Title: How to sort javascript array where first record should be specific and then follow by descending order


问:
(Why) can we assign non-static class members to static variables in initialization?
In a larger code base I have encountered code like this (see on godbolt):

```<code>struct Foo {};

struct Base {
    Foo* a;
};

struct Bar : public Base {
    static Foo* Bar::*mybar[];
};

Foo* Bar::Bar::*mybar[] = {
    &Base::a
};
</code>```

To be honest, I'm baffled. This looks like it's initializing a static array of Foo pointers in Bar with a non-static member variable of Base. How is that even possible without an object?

(Disclaimer: This is found in production code that actually works - hopefully not relying on UB?)

Also, is there any problem if I remove the qualified name lookup like here? I'd like to refactor the code and make it more readable. All these Bar::s seem quite superfluous, but since I'm not feeling so comfortable with the code I'd rather understand the implications first.

答:
To start with, Bar::mybar is an array of pointers to members. Those aren't actual pointers. They are more like an abstraction over an offset into the object. They allow accessing members indirectly. Given a Base object (or one derived from it), we can invoke them, as follows

```<code>aBar.*mybar[0] // This resolve to a Foo* inside aBar
</code>```

The other thing of note, is that in your example the object in namespace scope is not the definition of Bar::mybar. It's an unrelated array. The correct definition would be

```<code>Foo* Bar::* Bar::mybar[] = {
    &Base::a
};
</code>```

It is because your definition was wrong that removing some of the qualified name had no effect. When you removed it, you were left with

```<code>static Foo *mybar[];

Foo Bar::*mybar[] = {
    &Base::a
};
</code>```

The types of the declaration and "definition" mismatch. But you got no error because those are in fact different objects.

In the correct definition, every Bar:: qualifier is required and serves a different purpose. One serves to create the correct type (pointer to member of Bar), the other designates the static member of Bar that is being defined, and is required in every static class member definition.

Body:
In a larger code base I have encountered code like this (see on godbolt):

struct Foo {};

struct Base {
    Foo* a;
};

struct Bar : public Base {
    static Foo* Bar::*mybar[];
};

Foo* Bar::Bar::*mybar[] = {
    &Base::a
};

To be honest, I'm baffled. This looks like it's initializing a static array of Foo pointers in Bar with a non-static member variable of Base. How is that even possible without an object?

(Disclaimer: This is found in production code that actually works - hopefully not relying on UB?)

Also, is there any problem if I remove the qualified name lookup like here? I'd like to refactor the code and make it more readable. All these Bar::s seem quite superfluous, but since I'm not feeling so comfortable with the code I'd rather understand the implications first.

Body:
To start with, Bar::mybar is an array of pointers to members. Those aren't actual pointers. They are more like an abstraction over an offset into the object. They allow accessing members indirectly. Given a Base object (or one derived from it), we can invoke them, as follows

aBar.*mybar[0] // This resolve to a Foo* inside aBar

The other thing of note, is that in your example the object in namespace scope is not the definition of Bar::mybar. It's an unrelated array. The correct definition would be

Foo* Bar::* Bar::mybar[] = {
    &Base::a
};

It is because your definition was wrong that removing some of the qualified name had no effect. When you removed it, you were left with

static Foo *mybar[];

Foo Bar::*mybar[] = {
    &Base::a
};

The types of the declaration and "definition" mismatch. But you got no error because those are in fact different objects.

In the correct definition, every Bar:: qualifier is required and serves a different purpose. One serves to create the correct type (pointer to member of Bar), the other designates the static member of Bar that is being defined, and is required in every static class member definition.


问:
Remove last n lines (sentences) in a String in Java
I am looking for an efficient way to remove last n lines from a String. Efficient as in- fast performing as well as something that does not create too may objects. Therefore would like to stay away from split(). Especially because, at times, my strings could be a few hundred or even thousand lines.

For instance, I am getting a string as such:

```<code>This is a sample code line 1.
This is a sample code line 2.

Warm Regards,
SomeUser.
</code>```

The last 3 lines (an empty line, "Warm Regards,", and "SomeUser.") is what I am trying to get rid of. Note that the content (including the last 3 lines) isn't fixed.

I am thinking of counting the lines first using this solution here: https://stackoverflow.com/a/18816371/1353174 and then again, use another similar loop to reach to a position that is lines - n and do a substring till that position.

However, just posting this problem here to know if there are any other and perhaps more efficient ways to achieve this. External library-based solutions (like Apache Commons StringUtils) are also welcome.

答:
```<code>  @scala.annotation.tailrec
  def rmLines(in: String, nlines: Int): String =
    if (nlines == 0) {
      in
    } else {
      val lastBreakIndex = in.lastIndexOf('\n')
      if (lastBreakIndex == -1) {
        in
      } else {
        rmLines(in.substring(0, lastBreakIndex), nlines - 1)
      }
    }

</code>```

Body:
I am looking for an efficient way to remove last n lines from a String. Efficient as in- fast performing as well as something that does not create too may objects. Therefore would like to stay away from split(). Especially because, at times, my strings could be a few hundred or even thousand lines.

For instance, I am getting a string as such:

This is a sample code line 1.
This is a sample code line 2.

Warm Regards,
SomeUser.

The last 3 lines (an empty line, "Warm Regards,", and "SomeUser.") is what I am trying to get rid of. Note that the content (including the last 3 lines) isn't fixed.

I am thinking of counting the lines first using this solution here: https://stackoverflow.com/a/18816371/1353174 and then again, use another similar loop to reach to a position that is lines - n and do a substring till that position.

However, just posting this problem here to know if there are any other and perhaps more efficient ways to achieve this. External library-based solutions (like Apache Commons StringUtils) are also welcome.


问:
index out of range when trying to load image url from json data
I'm trying to load data from NYTime Articles search API to an UITableView. I can load the text(headline, abstract) just fine but I have been having some trouble to load the image url, basically need to access nested json.

Here's the JSON Data using "pelosi" keyword and here's the API doc

Here's the models I have set up

```<code>class Response: Mappable {
    var docs = [Docs]()
    ...
}
class Docs: Mappable {
    ...
    var multimedia = [Multimedia]()
    var headline : Headline?
    ...
}
class Multimedia: Mappable {
    ...
    var url: String?
    ...
}
</code>```

I pass the data to:

```<code>var docResult: [Docs] = []
</code>```

here's my numberOfRows :

```<code> return docResult.count
</code>```

Tried to load the image into each cell using kingfisher but got Index out of range error :

```<code>var cellResponse: Docs!
let imgUrl = URL(string: "https://static01.nyt.com/\(cellResponse.multimedia[0].url)!")
docImg.kf.setImage(with: imgUrl)
</code>```

The thing I'm trying to do is retrieve a single item (url of the first in the multimedia array). Can someone provide a solution for this ? Thanks !

EDIT:
here's my cellForRowAt

```<code>cell.cellResponse = docResult[indexPath.row]
</code>```

答:
If you get this crash in this line then multimedia is empty. You have to check that

```<code>if let multimediaURL = cellResponse.multimedia.first?.url,
   let imgUrl = URL(string: "https://static01.nyt.com/\(multimediaURL)") {
       docImg.kf.setImage(with: imgUrl)
}
</code>```

Body:
I'm trying to load data from NYTime Articles search API to an UITableView. I can load the text(headline, abstract) just fine but I have been having some trouble to load the image url, basically need to access nested json.

Here's the JSON Data using "pelosi" keyword and here's the API doc

Here's the models I have set up

class Response: Mappable {
    var docs = [Docs]()
    ...
}
class Docs: Mappable {
    ...
    var multimedia = [Multimedia]()
    var headline : Headline?
    ...
}
class Multimedia: Mappable {
    ...
    var url: String?
    ...
}

I pass the data to:

var docResult: [Docs] = []

here's my numberOfRows :

 return docResult.count

Tried to load the image into each cell using kingfisher but got Index out of range error :

var cellResponse: Docs!
let imgUrl = URL(string: "https://static01.nyt.com/\(cellResponse.multimedia[0].url)!")
docImg.kf.setImage(with: imgUrl)

The thing I'm trying to do is retrieve a single item (url of the first in the multimedia array). Can someone provide a solution for this ? Thanks !

EDIT:
here's my cellForRowAt

cell.cellResponse = docResult[indexPath.row]

Body:
If you get this crash in this line then multimedia is empty. You have to check that

if let multimediaURL = cellResponse.multimedia.first?.url,
   let imgUrl = URL(string: "https://static01.nyt.com/\(multimediaURL)") {
       docImg.kf.setImage(with: imgUrl)
}


问:
How to access dataset in current scope generated by a call to a stored procedure in TSQL?

Problem Background

Generating and accessing data of a fixed column layout is easy.  You can create local temp tables up-front, and populate them by calling stored procedures.

On the other hand, if you want to generate data with a dynamic column layout, you must generally build an SQL statement dynamically and execute it with "exec sp_executesql".  Since the data layout is unknown at run-time, you cannot create a temp-table up-front, and once inside the "exec sp_executesql" statement, any temporary tables created there are bound to that scope and vanish when the call returns, so it's much more difficult to access the data (i.e. your options are more limited).

My Specific Situation

I have a query that needs to access data in a dynamically generated table.

The table is generated by a stored procedure, which dynamically builds a query, stores it in a variable "@sql nvarchar(max)", and runs it by calling  "exec sp_executesql @statement = @sql".

The @sql statement was something like "select * into #temptable from...", but #temptable was destroyed by the time "exec sp_executesql" returned.  A quick fix for this was to just use "##temptable" instead (i.e. a global temp table), because it survives when the stored procedure returns AND I can easily access it in the calling scope (because it has a known/static name).

I don't like this solution because global temp tables aren't thread-safe (name collistion-wise), and I don't want to have to mess with dynamically-generated unique names, because I'll just end up having to use more dynamic SQL to access them... which puts me right back at square one, leaving the data inaccessible outside the SP.

I don't think returning table variables (through output parameters) is an option (new to SQL Server 2008 too), unless it can be done without having to define a static table type.  The tables my stored procedure generates are dynamic, and depend on the input parameter(s) passed.

Inline table-valued functions are not an option, because I'm running code loops to build the @sql query and calling "exec sp_executesql".

Multi-statement table-valued functions (instead of the stored procedure), is also not an option, because such a function must have a well-defined table format, whereas I'm running dyanmic SQL to return a table with a variable number of columns and column names depending on the input parameter values.

All I really want to do is select the result set of the dynamic query into a new table, but I'm finding it difficult, as none of the above works; particularly irritating is how local temporary tables aren't local to the session, but local to the stored procedure so that they vanish upon returning.  The only solution I've seen insists that using OPENROWSET is the only way, but I don't want to mess with connection strings inside my stored procedure, for the same reason I don't want to include unique-name-management code... it's just way more complicated than it ought to be.

In summary, I just want to execute dynamic SQL that generates a dataset of an unknown format, and be able to easily access it from the calling scope.

答:
Create the temp table before the sp_executesql: it will still be in scope for "inner" scopes like the sp_executesql

Change the SQL to do an INSERT rather than SELECT..INTO...

Edit:

Make the table wide enough to cover all options.

Frankly, SQL is designed to work with fixed table definitions: variable output signatures (tables) leads to the problem you have...


答:
```<code>const arr = [
    { number: 13.23, Active: false },
    { number: 2.21, Active: false },
    { number: 2.3, Active: true }
]
customSortActiveShouldBeFirst = function (array) {
    let key = 'number';
    if (array && array.length > 0) {
        return array.sort(function (a, b) {
            var x = a[key];
            var y = b[key];
            if (a.Active && b.Active) {
                return y - x;
            }
            if (a.Active) {
                return -1
            }
            if (b.Active) {
                return 1;
            }
            return y - x;
        });
    }
    return array;
};
console.log(customSortActiveShouldBeFirst(arr))

</code>```

Body:
input array as list object like,  [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

Expected sorted descending order output as, "active" object should be first and all other descending sorted by numbers after "active" record.
Tried with below approach but it does not give me active as first entry. this sort the descending by number but active not coming first.

const arr = [{ number: 13.23 , Active: false },{ number: 2.21 , Active: false },{ number: 2.3 , Active: true }];

const customSortActiveShouldBeFirst = function(array) {
  let key = 'number';
  if (array && array.length > 0) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return (x['Active'] === true ? 1 : (y - x));
    });
  }
  return array;
};
console.log(customSortActiveShouldBeFirst(arr))

Expected output:
Active object to be first in result array and then all entries descending by numbers. like, [{ number: 2.3 , Active: true },{ number: 13.23 , Active: false },{ number: 2.21 , Active: false }]


问:
Programatically Install Microsoft Access Add-In Using VBA
Finding information on Add-In development for Microsoft Access is like getting all of your teeth pulled! Yes I've found the couple Managed Add-In Articles written... but could find next to nothing for Un-Managed Add-Ins. I did find one great article which is very old in creating basically an unmanaged .mda project... which I've followed and created a add-in. Now I would like an automated way to deploy this add-in.

I've seen it done from VBA with such tools as Rick Fisher's Find and Replace add-in tool... but can not find a way to do this programatically in Access. I have found lot's and lot's of articles on Excel Add-In's and even Excel Add-In Installation. One such method uses VBA like so:

```<code>Sub InstallAddIn()
    Dim AI As Excel.AddIn
    Set AI = Application.AddIns.Add(Filename:="C:\MyAddIn.xla")
    AI.Installed = True
End Sub
</code>```

Unfortunately Access does not use the same method. If anyone could point me in the right direction I would greatly appreciate it. AND if anyone knows of any books or references that goes more in-depth to developing Add-Ins for Microsoft Access that would be greatly appreciated as well as most of the picking seem slim.

答:
If you target the main registry hive there is logic that will put the key in the correct location for you. For example, you never hard code Wow6432Node because that location is automatically managed by 64-bit windows when a 32-bit application tries to use the registry. Likewise, in modern C2R versions of office the registry location is in a really strange place. You don't have to worry about it. If you target the main key from Access, the key will end up in the correct location magically.

If you want to install per user I recommend using the following locations.

Put the file here:

```<code>Private Function GetAddinFileName() As String
    GetAddinFileName = Environ$("AppData") & "\Microsoft\AddIns\" & CodeProject.Name
End Function
</code>```

Use this registry location:

```<code>Private Function GetAddinRegPath() As String
    GetAddinRegPath = "HKCU\SOFTWARE\Microsoft\Office\" & _
        Application.Version & "\Access\Menu Add-Ins\"
End Function
</code>```

Body:
Finding information on Add-In development for Microsoft Access is like getting all of your teeth pulled! Yes I've found the couple Managed Add-In Articles written... but could find next to nothing for Un-Managed Add-Ins. I did find one great article which is very old in creating basically an unmanaged .mda project... which I've followed and created a add-in. Now I would like an automated way to deploy this add-in.

I've seen it done from VBA with such tools as Rick Fisher's Find and Replace add-in tool... but can not find a way to do this programatically in Access. I have found lot's and lot's of articles on Excel Add-In's and even Excel Add-In Installation. One such method uses VBA like so:

Sub InstallAddIn()
    Dim AI As Excel.AddIn
    Set AI = Application.AddIns.Add(Filename:="C:\MyAddIn.xla")
    AI.Installed = True
End Sub

Unfortunately Access does not use the same method. If anyone could point me in the right direction I would greatly appreciate it. AND if anyone knows of any books or references that goes more in-depth to developing Add-Ins for Microsoft Access that would be greatly appreciated as well as most of the picking seem slim.

Body:
If you target the main registry hive there is logic that will put the key in the correct location for you. For example, you never hard code Wow6432Node because that location is automatically managed by 64-bit windows when a 32-bit application tries to use the registry. Likewise, in modern C2R versions of office the registry location is in a really strange place. You don't have to worry about it. If you target the main key from Access, the key will end up in the correct location magically.

If you want to install per user I recommend using the following locations.

Put the file here:

Private Function GetAddinFileName() As String
    GetAddinFileName = Environ$("AppData") & "\Microsoft\AddIns\" & CodeProject.Name
End Function

Use this registry location:

Private Function GetAddinRegPath() As String
    GetAddinRegPath = "HKCU\SOFTWARE\Microsoft\Office\" & _
        Application.Version & "\Access\Menu Add-Ins\"
End Function


问:
Get the path of first file in each directory or sub-directory
I have a directory structure as following: The Root directory contains some sub-directories in which many.txt files are placed or some  sub-directories again  that contains different files with the same extension.

```<code>├───Root
│   ├───SubDir1
        └───file1.txt
│   ├───SubDir2
│   ├───SubDir3
│       └───SubSubDir1
            └───file1.txt
            └───file2.txt
│   └───SubDir4
│       └───SubSubDir1
        └───SubSubDir2
            └───file1.txt
</code>```

I want to save all the first file-paths in each directoriy in a QStringList. E.g.:

```<code>/Root/SubDir1/file1.txt
/Root/SubDir3/SubSubDir1/file1.txt
/Root/SubDir4/SubSubDir2/file1.txt
</code>```

The following code gives me all the file-paths in a directory or sub-directories but not the path of the first file in each.

```<code>QDir rootFolder("/root");
QStringList list;
QDirIterator dirIter(rootFolder.absolutePath(), QDir::AllEntries | QDir::NoSymLinks |
QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

while(dirIter.hasNext())
{
    dirIter.next();
    if(QFileInfo(dirIter.filePath()).isFile())
    {
        if(QFileInfo(dirIter.filePath()).suffix() == "txt")
        {
            qDebug()<<"File Path: " <<dirIter.filePath();

            list.append(dirIter.next());
            qDebug()<<"List: " <<list;
        }
    }
}
</code>```

答:
please consider iterating recursively on root using as filter the file1.txt

example#:

```<code>QDirIterator it("/home/root", QStringList() << "file1.txt", QDir::NoFilter, QDirIterator::Subdirectories);
while (it.hasNext())
{
    qDebug() << it.next();
}
</code>```

that will print directly a DEbug message like

```<code>/Root/SubDir1/file1.txt
/Root/SubDir3/SubSubDir1/file1.txt
/Root/SubDir4/SubSubDir2/file1.txt
</code>```

read the doc for more info:

https://doc.qt.io/qt-5/qdiriterator.html

Body:
I have a directory structure as following: The Root directory contains some sub-directories in which many.txt files are placed or some  sub-directories again  that contains different files with the same extension.

├───Root
│   ├───SubDir1
        └───file1.txt
│   ├───SubDir2
│   ├───SubDir3
│       └───SubSubDir1
            └───file1.txt
            └───file2.txt
│   └───SubDir4
│       └───SubSubDir1
        └───SubSubDir2
            └───file1.txt

I want to save all the first file-paths in each directoriy in a QStringList. E.g.:

/Root/SubDir1/file1.txt
/Root/SubDir3/SubSubDir1/file1.txt
/Root/SubDir4/SubSubDir2/file1.txt

The following code gives me all the file-paths in a directory or sub-directories but not the path of the first file in each.

QDir rootFolder("/root");
QStringList list;
QDirIterator dirIter(rootFolder.absolutePath(), QDir::AllEntries | QDir::NoSymLinks |
QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

while(dirIter.hasNext())
{
    dirIter.next();
    if(QFileInfo(dirIter.filePath()).isFile())
    {
        if(QFileInfo(dirIter.filePath()).suffix() == "txt")
        {
            qDebug()<<"File Path: " <<dirIter.filePath();

            list.append(dirIter.next());
            qDebug()<<"List: " <<list;
        }
    }
}

Body:
please consider iterating recursively on root using as filter the file1.txt

example#:

QDirIterator it("/home/root", QStringList() << "file1.txt", QDir::NoFilter, QDirIterator::Subdirectories);
while (it.hasNext())
{
    qDebug() << it.next();
}

that will print directly a DEbug message like

/Root/SubDir1/file1.txt
/Root/SubDir3/SubSubDir1/file1.txt
/Root/SubDir4/SubSubDir2/file1.txt

read the doc for more info:

https://doc.qt.io/qt-5/qdiriterator.html


问:
How to force IntelliJ IDEA to convert all java files from spaces to tabs?
I have an existing project, where some of the java files have tabs, some have spaces for indentation.
I want to make ALL java files based on tabs, but there are hundreds of them, the action of "to tabs" is not realistic I am not going to go manually over multiple modules, hundreds of files!

Is there any other way to do it smartly without going through individual files?

答:
Here are the steps to follow.

Settings > Editor > Code Style > Java

Tabs and Indents > Click [Use tab character]

Go to tree structure/Project window (the main side tab of project hierarchy display)

Right click the folder(or project) you want to convert and select Reformat code & Run