问:
MSBuild Target not running in NET Core Project
I am using Visual Studio 2019, .NET Core 3.1

I create a new Project and use template Class Library (.NET Core)

I right-click on the project in the solution explorer and click Edit Project File

and add the following target:

```<code>  <Target Name="Test" AfterTargets="Build">
    <Message Text="This is a test" Importance="high" />
  </Target>
</code>```

When I publish... it hits this target a few times and in the Output pane i see "This is a test" a few times.

I would like this target to execute after the Publish instead of the build.

This works in a .NET Core Web API solution where before the Publish event i am executing an ng build on an angular project that's included in the published result.

But in a Class Library its like the Publish msbuild target never gets executed even though I am doing an actual Publish.

So...

```<code>  <Target Name="Test" AfterTargets="Publish">
    <Message Text="This is a test" Importance="high" />
  </Target>
</code>```

This message never displays in my Output pane.

This class library is going to be published to a private NuGet server and I'd like to execute a nuget push after the Publish action has completed. I can easily execute a command to push to the NuGet server once i get the msbuild target to actually run at the right time.

Am I missing something here? How can I execute a target after the Publish action finishes on a .NET Core Library solution?

EDIT:
That raises another question. When i publish, i get this output:

```<code>1>------ Build started: Project: ClassLibrary1, Configuration: Release Any CPU ------
1>ClassLibrary1 -> C:\Users\11016409\Documents\source\Libraries\NET Core\ClassLibrary1\ClassLibrary1\bin\Release\netcoreapp3.1\ClassLibrary1.dll
1>This is a test
2>------ Publish started: Project: ClassLibrary1, Configuration: Release Any CPU ------
2>ClassLibrary1 -> C:\Users\11016409\Documents\source\Libraries\NET Core\ClassLibrary1\ClassLibrary1\bin\Release\netcoreapp3.1\ClassLibrary1.dll
2>This is a test
2>Successfully created package 'C:\Users\11016409\Documents\source\Libraries\NET Core\ClassLibrary1\ClassLibrary1\bin\Release\netcoreapp3.1\publish\ClassLibrary1.1.0.0.nupkg'.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========
</code>```

why Does it run the build phase twice?

答:
There are certain built in targets that never get hit like Publish for a .NET Core Class Library project. I even set the publishable property to true to no avail. I was never able to figure that one out. But I did find that it was executing a built-in target "Pack" that I could hook into.

```<code>  <Target Name="nuget push" AfterTargets="Pack">
    <Exec WorkingDirectory="$(PackageOutputPath)" Command="nuget push $(PackageId).$(PackageVersion).nupkg -source http://DevServices/NuGet" />
  </Target>
</code>```

Pack is where it generates the actual .nupkg file. Once the Pack target is finished, i can push to my local NuGet server.

Make sure you have the checkbox unchecked on the project properties for generating the Nuget Package on each build because the Pack target will execute each time you build.

This way it will only do a Pack when you do a Publish of the project. You can publish to any location and it will run the nuget push on the generated .nupkg regardless of the location you published to.

If you really need to generate a .nupkg on each build but want to only do a nuget push when you use publish, then use this target instead and have it only push the nuget package to your nuget server if the output path matches your publish folder location:

```<code>  <Target Name="nuget push" AfterTargets="Pack" Condition="$(PackageOutputPath.EndsWith('\publish\'))">
    <Exec WorkingDirectory="$(PackageOutputPath)" Command="nuget push $(PackageId).$(PackageVersion).nupkg -source http://DevServices/NuGet" />
  </Target>
</code>```

Note: With this nuget push method, its very handy if your nuget server is set up to not allow you to overwrite existing package versions (which is how it should be) then it requires those pushing packages to update the version number before it will work. Otherwise it will get an error on publish that it cannot overwrite an existing package version.  Everything right in the GUI like this makes it easy to jump in and update the version of the library and try the publish again. Super quick. Super easy.

Edit:
This no longer works after Visual Studio 17.3.6
It appears that it does not automatically do a Pack to the nuget package unless you want it to do it on every build via the project properties. You can right click the project in the solution explorer and select Pack and the above

AfterTargets="Pack"

will execute your code.

Body:
I am using Visual Studio 2019, .NET Core 3.1

I create a new Project and use template Class Library (.NET Core)

I right-click on the project in the solution explorer and click Edit Project File

and add the following target:

  <Target Name="Test" AfterTargets="Build">
    <Message Text="This is a test" Importance="high" />
  </Target>

When I publish... it hits this target a few times and in the Output pane i see "This is a test" a few times.

I would like this target to execute after the Publish instead of the build.

This works in a .NET Core Web API solution where before the Publish event i am executing an ng build on an angular project that's included in the published result.

But in a Class Library its like the Publish msbuild target never gets executed even though I am doing an actual Publish.

So...

  <Target Name="Test" AfterTargets="Publish">
    <Message Text="This is a test" Importance="high" />
  </Target>

This message never displays in my Output pane.

This class library is going to be published to a private NuGet server and I'd like to execute a nuget push after the Publish action has completed. I can easily execute a command to push to the NuGet server once i get the msbuild target to actually run at the right time.

Am I missing something here? How can I execute a target after the Publish action finishes on a .NET Core Library solution?

EDIT:
That raises another question. When i publish, i get this output:

1>------ Build started: Project: ClassLibrary1, Configuration: Release Any CPU ------
1>ClassLibrary1 -> C:\Users\11016409\Documents\source\Libraries\NET Core\ClassLibrary1\ClassLibrary1\bin\Release\netcoreapp3.1\ClassLibrary1.dll
1>This is a test
2>------ Publish started: Project: ClassLibrary1, Configuration: Release Any CPU ------
2>ClassLibrary1 -> C:\Users\11016409\Documents\source\Libraries\NET Core\ClassLibrary1\ClassLibrary1\bin\Release\netcoreapp3.1\ClassLibrary1.dll
2>This is a test
2>Successfully created package 'C:\Users\11016409\Documents\source\Libraries\NET Core\ClassLibrary1\ClassLibrary1\bin\Release\netcoreapp3.1\publish\ClassLibrary1.1.0.0.nupkg'.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========

why Does it run the build phase twice?

Body:
There are certain built in targets that never get hit like Publish for a .NET Core Class Library project. I even set the publishable property to true to no avail. I was never able to figure that one out. But I did find that it was executing a built-in target "Pack" that I could hook into.

  <Target Name="nuget push" AfterTargets="Pack">
    <Exec WorkingDirectory="$(PackageOutputPath)" Command="nuget push $(PackageId).$(PackageVersion).nupkg -source http://DevServices/NuGet" />
  </Target>

Pack is where it generates the actual .nupkg file. Once the Pack target is finished, i can push to my local NuGet server.

Make sure you have the checkbox unchecked on the project properties for generating the Nuget Package on each build because the Pack target will execute each time you build.

This way it will only do a Pack when you do a Publish of the project. You can publish to any location and it will run the nuget push on the generated .nupkg regardless of the location you published to.

If you really need to generate a .nupkg on each build but want to only do a nuget push when you use publish, then use this target instead and have it only push the nuget package to your nuget server if the output path matches your publish folder location:

  <Target Name="nuget push" AfterTargets="Pack" Condition="$(PackageOutputPath.EndsWith('\publish\'))">
    <Exec WorkingDirectory="$(PackageOutputPath)" Command="nuget push $(PackageId).$(PackageVersion).nupkg -source http://DevServices/NuGet" />
  </Target>

Note: With this nuget push method, its very handy if your nuget server is set up to not allow you to overwrite existing package versions (which is how it should be) then it requires those pushing packages to update the version number before it will work. Otherwise it will get an error on publish that it cannot overwrite an existing package version.  Everything right in the GUI like this makes it easy to jump in and update the version of the library and try the publish again. Super quick. Super easy.

Edit:
This no longer works after Visual Studio 17.3.6
It appears that it does not automatically do a Pack to the nuget package unless you want it to do it on every build via the project properties. You can right click the project in the solution explorer and select Pack and the above

AfterTargets="Pack"

will execute your code.


来源: stackexchange

问:
C# Console App - Streamwriter overwriting CSV file every time it writes new "Page" from API call, only leaving last API call results
So, I KNOW this is a simple thing but I typically work with ASP.NET web apps and SQL, so I'm having a problem with this console app.

I have a console app that pulls a "page" of data from a webclient API call. This pulls the data into a string (s) and writes that data to a CSV file. The method then loops, incrementing the "pagenum" by +1  until the API returns the string "No records found".

My problem is, instead of appending each new "page" of data to the existing CSV file, it overwrites the file with the previous "page" of data. So, I write page 1, then get page 2, and all the data in the CSV is replaced with Page 2 data, rinse and repeat.

My question: do I need to create a new "string" for each page of data (maybe incrementing the string variable name by 1 (s1, s2, s3) based on page number or do I simply need to change my loops to use some sort of other part of Streamwriter (like is there an add line command I need to call at the end of the loop?) If so, any ideas on how to do this based on my sample code below? (NOTE: I have some Console.WriteLines for debugging purposes so I can see the data while testing.)

```<code>while (!s.Contains("No records found")) //When API returns "No Records Found" we know we've reached the last page of data we need to get.
        {
            rpcURL = "https://api.WEBSITEcom/urlrpc?method=getPlacementReport&username=" + userName + "&password=" + passWord + "&class_code=" + classCode + "&from_date=" + startDate + "&to_date=" + endDate + "&page_num=" + page;
            Console.WriteLine(rpcURL);
            client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            using (var stream = client.OpenRead(rpcURL))
            using (var sr = new StreamReader(stream))
            {
                s = sr.ReadToEnd();

                Console.WriteLine(s);
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string docPath = path + "\\" + "AleksReport.csv";

                if (!s.Contains("No records found"))
                {
                    using (StreamWriter writer = new StreamWriter(docPath))
                    {
                        writer.WriteLine(s);
                    }
                }
                else
                {
                    Console.WriteLine("End of records");
                }
            }
            page++;

        }
</code>```

答:
You can pass a second argument to StreamWriter, which indicates whether or not you want to append to the file. Here, obviously you want true:

```<code>using (StreamWriter writer = new StreamWriter(docPath, true))
</code>```

Documentation

However, I think a better way is to not create a stream writer every iteration of the loop. Create one stream writer and reuse it:

```<code>string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string docPath = path + "\\" + "AleksReport.csv";
using (StreamWriter writer = new StreamWriter(docPath)) {
    while (!s.Contains("No records found")) //When API returns "No Records Found" we know we've reached the last page of data we need to get.
    {
        rpcURL = "https://api.WEBSITEcom/urlrpc?method=getPlacementReport&username=" + userName + "&password=" + passWord + "&class_code=" + classCode + "&from_date=" + startDate + "&to_date=" + endDate + "&page_num=" + page;
        Console.WriteLine(rpcURL);
        client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
        using (var stream = client.OpenRead(rpcURL))
        using (var sr = new StreamReader(stream))
        {
            s = sr.ReadToEnd();

            Console.WriteLine(s);

            if (!s.Contains("No records found"))
            {
                writer.WriteLine(s);
            }
            else
            {
                Console.WriteLine("End of records");
            }
        }
        page++;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So, I KNOW this is a simple thing but I typically work with ASP.NET web apps and SQL, so I'm having a problem with this console app.

I have a console app that pulls a "page" of data from a webclient API call. This pulls the data into a string (s) and writes that data to a CSV file. The method then loops, incrementing the "pagenum" by +1  until the API returns the string "No records found".

My problem is, instead of appending each new "page" of data to the existing CSV file, it overwrites the file with the previous "page" of data. So, I write page 1, then get page 2, and all the data in the CSV is replaced with Page 2 data, rinse and repeat.

My question: do I need to create a new "string" for each page of data (maybe incrementing the string variable name by 1 (s1, s2, s3) based on page number or do I simply need to change my loops to use some sort of other part of Streamwriter (like is there an add line command I need to call at the end of the loop?) If so, any ideas on how to do this based on my sample code below? (NOTE: I have some Console.WriteLines for debugging purposes so I can see the data while testing.)

while (!s.Contains("No records found")) //When API returns "No Records Found" we know we've reached the last page of data we need to get.
        {
            rpcURL = "https://api.WEBSITEcom/urlrpc?method=getPlacementReport&username=" + userName + "&password=" + passWord + "&class_code=" + classCode + "&from_date=" + startDate + "&to_date=" + endDate + "&page_num=" + page;
            Console.WriteLine(rpcURL);
            client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            using (var stream = client.OpenRead(rpcURL))
            using (var sr = new StreamReader(stream))
            {
                s = sr.ReadToEnd();

                Console.WriteLine(s);
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string docPath = path + "\\" + "AleksReport.csv";

                if (!s.Contains("No records found"))
                {
                    using (StreamWriter writer = new StreamWriter(docPath))
                    {
                        writer.WriteLine(s);
                    }
                }
                else
                {
                    Console.WriteLine("End of records");
                }
            }
            page++;

        }

Body:
You can pass a second argument to StreamWriter, which indicates whether or not you want to append to the file. Here, obviously you want true:

using (StreamWriter writer = new StreamWriter(docPath, true))

Documentation

However, I think a better way is to not create a stream writer every iteration of the loop. Create one stream writer and reuse it:

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string docPath = path + "\\" + "AleksReport.csv";
using (StreamWriter writer = new StreamWriter(docPath)) {
    while (!s.Contains("No records found")) //When API returns "No Records Found" we know we've reached the last page of data we need to get.
    {
        rpcURL = "https://api.WEBSITEcom/urlrpc?method=getPlacementReport&username=" + userName + "&password=" + passWord + "&class_code=" + classCode + "&from_date=" + startDate + "&to_date=" + endDate + "&page_num=" + page;
        Console.WriteLine(rpcURL);
        client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
        using (var stream = client.OpenRead(rpcURL))
        using (var sr = new StreamReader(stream))
        {
            s = sr.ReadToEnd();

            Console.WriteLine(s);

            if (!s.Contains("No records found"))
            {
                writer.WriteLine(s);
            }
            else
            {
                Console.WriteLine("End of records");
            }
        }
        page++;
    }
}


问:
ReferenceError: Item Is Not Defined In NodeJs Route
I define my API routes in Nodejs but when I run it, it gives this error message.

Error Message

ReferenceError: Item is not defined

```<code>at D:\shoppinglist\serverside\route\routes.js:7:5
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at Function.handle (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:174:3)
at router (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:317:13)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at jsonParser (D:\shoppinglist\serverside\node_modules\body-parser\lib\types\json.js:110:7)
</code>```

My Route.js code is

```<code>var express = require('express');

var router = express.Router();

router.get('/items', (req, res, next)=>{
    Item.find(function(err, items){
        if(err){
            res.json(err);
        }
        else{
            res.json(items);
        }
    });
});
router.post('/item', (req, res, next)=>{
    let newShoppingItem = new Item({
        itemName: req.body.itemName,
        itemQuantity: req.body.itemQuantity,
        itemBought: req.body.itemBought
    });
    newShoppingItem.save((err, item)=>{
        if(err){
            res.json(err)
        }
        else{
            res.json({msg: 'Item has been added to db'});
        }
    });
});
router.put('/put_test', (req, res, next)=>{
  // do later
});

router.delete('/delete_test', (req, res, next)=>{
  // do later
});

module.exports = router;
</code>```

Here is my shoopingitem.js code

shoppingitem.js

```<code>const mongoose = require('mongoose');

const shoppingItemSchema = mongoose.Schema({

    itemName:{
        type: String,
        require:true
    },

    itemQuantity:{
        type: Number,
        require:true
    },

    itemBought:{
        type: Boolean,
        require:true
    },

});
const Item = module.exports = mongoose.model('Item', shoppingItemSchema);
</code>```

Please suggest me the solution. I'm new in nodejs. So please help

Thanks in advance

答:
You'll need to require the Item model into the routes file in order to use it. This can be done in 2 ways:

```<code>const Item = require('../path/to/item/shoppingItem.js')
</code>```

or

```<code>const mongoose = require('mongoose')
const Item = mongoose.model('Item');
</code>```

Body:
I define my API routes in Nodejs but when I run it, it gives this error message.

Error Message

ReferenceError: Item is not defined

at D:\shoppinglist\serverside\route\routes.js:7:5
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\shoppinglist\serverside\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at Function.handle (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:174:3)
at router (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (D:\shoppinglist\serverside\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:317:13)
at D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:335:12)
at next (D:\shoppinglist\serverside\node_modules\express\lib\router\index.js:275:10)
at jsonParser (D:\shoppinglist\serverside\node_modules\body-parser\lib\types\json.js:110:7)

My Route.js code is

var express = require('express');

var router = express.Router();

router.get('/items', (req, res, next)=>{
    Item.find(function(err, items){
        if(err){
            res.json(err);
        }
        else{
            res.json(items);
        }
    });
});
router.post('/item', (req, res, next)=>{
    let newShoppingItem = new Item({
        itemName: req.body.itemName,
        itemQuantity: req.body.itemQuantity,
        itemBought: req.body.itemBought
    });
    newShoppingItem.save((err, item)=>{
        if(err){
            res.json(err)
        }
        else{
            res.json({msg: 'Item has been added to db'});
        }
    });
});
router.put('/put_test', (req, res, next)=>{
  // do later
});

router.delete('/delete_test', (req, res, next)=>{
  // do later
});

module.exports = router;

Here is my shoopingitem.js code

shoppingitem.js

const mongoose = require('mongoose');

const shoppingItemSchema = mongoose.Schema({

    itemName:{
        type: String,
        require:true
    },

    itemQuantity:{
        type: Number,
        require:true
    },

    itemBought:{
        type: Boolean,
        require:true
    },

});
const Item = module.exports = mongoose.model('Item', shoppingItemSchema);

Please suggest me the solution. I'm new in nodejs. So please help

Thanks in advance

Body:
You'll need to require the Item model into the routes file in order to use it. This can be done in 2 ways:

const Item = require('../path/to/item/shoppingItem.js')

or

const mongoose = require('mongoose')
const Item = mongoose.model('Item');


问:
Convert discord username to member object
I have the following script,

```<code>async def kick(ctx, u: discord.User):
    await client.kick(u)
</code>```

It does have pass_context=True but that is in the primary function.

This script works but the problem is that it is passing a string with the author id (example: johnwayne#345) that has been pulled from a database while the kick command is expecting a member object.

How can I use this to look up a member object?

答:
Are you sure u is just a string? I just checked and for me it's passing a User object.

However, where I think the problem lies is that you're not calling kick correctly. You want to call Guild.kick or Member.kick. I'm assuming client is your actual botclient and that does not have a kick command.

EDIT:

So assuming the kick command receives the id of a member as a string every time you call it, you can use the following. You won't actually have to pass u: discord.User since it's only passing a string.

```<code>@client.command()
async def kick(ctx, id):
    await ctx.guild.kick(ctx.guild.get_member(int(id)))
</code>```

Since you mentioned in your question that you save their id in a database but then gave the example of their name I'll include the following in case you're saving their names and not the actual User.id.

```<code>@botclient.command()
async def kick(ctx, name):
    await ctx.guild.kick(ctx.guild.get_member_named(name))
</code>```

Body:
I have the following script,

async def kick(ctx, u: discord.User):
    await client.kick(u)

It does have pass_context=True but that is in the primary function.

This script works but the problem is that it is passing a string with the author id (example: johnwayne#345) that has been pulled from a database while the kick command is expecting a member object.

How can I use this to look up a member object?

Body:
Are you sure u is just a string? I just checked and for me it's passing a User object.

However, where I think the problem lies is that you're not calling kick correctly. You want to call Guild.kick or Member.kick. I'm assuming client is your actual botclient and that does not have a kick command.

EDIT:

So assuming the kick command receives the id of a member as a string every time you call it, you can use the following. You won't actually have to pass u: discord.User since it's only passing a string.

@client.command()
async def kick(ctx, id):
    await ctx.guild.kick(ctx.guild.get_member(int(id)))

Since you mentioned in your question that you save their id in a database but then gave the example of their name I'll include the following in case you're saving their names and not the actual User.id.

@botclient.command()
async def kick(ctx, name):
    await ctx.guild.kick(ctx.guild.get_member_named(name))


问:
Office 2016 add-in communicating to http://localhost
I'd like to build a Microsoft Office 2016 Add-in that could be used off-line (at least after being used online once).

I understand that we could cache HTML, js, etc. like a normal browser and I had thought of using a local HTTP server (not distributed with the Add-in) so the plugin could communicate with it. But doing things like:

```<code>var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://localhost:8080", true);
xmlHttp.onreadystatechange = function(aEvt) {
  if (xmlHttp.status == 200) {
    console.log(xmlHttp.responseText);
  } else {
    console.log("Status:" + xmlHttp.statusText);
  }
};
xmlHttp.send();
</code>```

This fails with:

JavaScript runtime error: Access is denied.

If I used an HTTPS URL (to a proper server) it works.

I think that the Add-ins only allow HTTPS and not HTTP requests?

What would be the best way to communicate, not via HTTPS external on the Internet, an Office 2016 add-in with another process in the machine?

Is it possible to relax the security on the manifest (I haven't found how) and allow HTTP requests to localhost?

答: What worked for me was to click the click the solution and go to the properties tab and change SSL Enabled from True to False, and whenever you intend to produce a prod build turn SSL flag to True.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to build a Microsoft Office 2016 Add-in that could be used off-line (at least after being used online once).

I understand that we could cache HTML, js, etc. like a normal browser and I had thought of using a local HTTP server (not distributed with the Add-in) so the plugin could communicate with it. But doing things like:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://localhost:8080", true);
xmlHttp.onreadystatechange = function(aEvt) {
  if (xmlHttp.status == 200) {
    console.log(xmlHttp.responseText);
  } else {
    console.log("Status:" + xmlHttp.statusText);
  }
};
xmlHttp.send();

This fails with:

JavaScript runtime error: Access is denied.

If I used an HTTPS URL (to a proper server) it works.

I think that the Add-ins only allow HTTPS and not HTTP requests?

What would be the best way to communicate, not via HTTPS external on the Internet, an Office 2016 add-in with another process in the machine?

Is it possible to relax the security on the manifest (I haven't found how) and allow HTTP requests to localhost?


问:
Multiple instances of Prolog clauses with identical ground head. Any uses besides for this besides (dubious) control of computation?
In SWI Prolog:

Exact clause duplicates are allowed:

```<code>a(1).
a(1).
</code>```

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```

or even:

```<code>c :- format("Hello from first c!").
c :- format("Hello from second c!").
</code>```

```<code>Hello from first c!
true ;
Hello from second c!
true.
</code>```

More generally, so are clauses with identical fully ground heads but differing bodies:

```<code>b(1) :- format("Hello from first b!").
b(1) :- format("Hello from second b!").
</code>```

```<code>?- b(1).
Hello from first b!
true ;
Hello from second b!
true.
</code>```

Clauses with identical non-ground head feel somewhat more reasonable:

```<code>p(X) :- format("Yup, this is p(~w)",X).
p(X) :- format("Yup, this is also p(~w)",X).
p(X) :- format("You think you can get rid of good old p(~w) just like that?",X).
</code>```

```<code>?- p('homer simpson').
Yup, this is p(homer simpson)
true ;
Yup, this is also p(homer simpson)
true ;
You think you can get rid of good old p(homer simpson) just like that?
true.
</code>```

```<code>?- p(X).
Yup, this is p(_4782)
true ;
Yup, this is also p(_4782)
true ;
You think you can get rid of good old p(_4782) just like that?
true.
</code>```

This covers the reasonable case of clauses with a guarded body:

```<code>p(X) :- X < 0,   format("It's less than 0: ~w", X).
p(X) :- X =:= 0, format("It's exactly 0: ~w", X).
p(X) :- X > 0,   format("It's larger than 0: ~w", X).
</code>```

On second thoughts ... we already encounter the ultimate case in the built-in repeat:

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```0

Or can construct an intermediate case easily:

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```1

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```2

Somehow textbooks gloss over the fact that predicates have additional semantics: they can not only be false or true for any given ground arguments, but they can actually be true(n) - "true n times, n ≥ 0" .

From a theory standpoint, this is dubious, at least for vanilla classical logic.

On the other hand, it is useful from a computational standpoint for:

Side-effects (rather for output than for input, and rather marginally).

Control of the computation (i.e. repeat).

Are there any other uses?

I really feel the compiler should flag variable-less cases like a/1, c/0, b/1 above as errors (easy to detect), and even repeat/0 should probably have a value: repeat(Count). Anything which redoes successfully should NOT redo successfully in the same context on exactly the same ground arguments. It has the same squishy feeling of irrelevancy as a(X) :- b(Y). b(Z). Brrr!.

答:
@false mentions in his answer using duplicated clauses to "answer the question how often the clause contributes to solutions." He also mentions "that a tracer cannot tell you this as easily".

A better solution to this use case is to use a ports profiler tool as found in e.g. ECLiPSe and Logtalk. No need to duplicate clauses to gather that information.

As an example, consider the following pure program, saved in a pure.pl file:

```<code>a :- b, c.

b.
b :- d.

c.

d.
</code>```

Let's include this code in an object. We can define it in a source file:

```<code>:- object(pure).

    :- set_logtalk_flag(debug, on).

    :- public(a/0).
    :- include('pure.pl').

:- end_object.
</code>```

Alternatively, we can create pure as a dynamic object:

```<code>?- create_object(pure, [],  [set_logtalk_flag(debug,on), public(a/0), include('pure.pl')], []).
true.
</code>```

Either way, after loading or creating the pure object and loading the ports_profiler tool, we can e.g. query all solutions for the a/0 predicate and then print the profiling data:

```<code>?- {ports_profiler(loader)}.
...
% (0 warnings)
true.

?- pure::a.
true ;
true.

?- ports_profiler::data.
-------------------------------------------------------------------
Entity  Predicate    Fact  Rule  Call  Exit *Exit  Fail  Redo Error
-------------------------------------------------------------------
pure    a/0             0     1     1     1     1     0     1     0
pure    b/0             1     1     1     1     1     0     1     0
pure    c/0             2     0     2     2     0     0     0     0
pure    d/0             1     0     1     1     0     0     0     0
-------------------------------------------------------------------
true.
</code>```

The table displays port crossing information for all predicates used in the query to the a/0 predicate. For example, that the predicate c/0 as called twice (for the two solutions to a/0) and exited deterministically. On the other hand, the predicate b/0 was called once by succeeded twice (on of them non-deterministically) due to backtracking.

For details on the portable port_profiler tool and a discussion on the insights that it can provide, see:

https://logtalk.org/manuals/devtools/ports_profiler.html

Body:
In SWI Prolog:

Exact clause duplicates are allowed:

a(1).
a(1).

?- a(X).
X = 1 ;
X = 1.

or even:

c :- format("Hello from first c!").
c :- format("Hello from second c!").

Hello from first c!
true ;
Hello from second c!
true.

More generally, so are clauses with identical fully ground heads but differing bodies:

b(1) :- format("Hello from first b!").
b(1) :- format("Hello from second b!").

?- b(1).
Hello from first b!
true ;
Hello from second b!
true.

Clauses with identical non-ground head feel somewhat more reasonable:

p(X) :- format("Yup, this is p(~w)",X).
p(X) :- format("Yup, this is also p(~w)",X).
p(X) :- format("You think you can get rid of good old p(~w) just like that?",X).

?- p('homer simpson').
Yup, this is p(homer simpson)
true ;
Yup, this is also p(homer simpson)
true ;
You think you can get rid of good old p(homer simpson) just like that?
true.

?- p(X).
Yup, this is p(_4782)
true ;
Yup, this is also p(_4782)
true ;
You think you can get rid of good old p(_4782) just like that?
true.

This covers the reasonable case of clauses with a guarded body:

p(X) :- X < 0,   format("It's less than 0: ~w", X).
p(X) :- X =:= 0, format("It's exactly 0: ~w", X).
p(X) :- X > 0,   format("It's larger than 0: ~w", X).

On second thoughts ... we already encounter the ultimate case in the built-in repeat:

?- repeat.
true ;
true ;
true ;
true ;
…

Or can construct an intermediate case easily:

h :- member(_,[1,2,3]).

?- h.
true ;
true ;
true.

Somehow textbooks gloss over the fact that predicates have additional semantics: they can not only be false or true for any given ground arguments, but they can actually be true(n) - "true n times, n ≥ 0" .

From a theory standpoint, this is dubious, at least for vanilla classical logic.

On the other hand, it is useful from a computational standpoint for:

Side-effects (rather for output than for input, and rather marginally).

Control of the computation (i.e. repeat).

Are there any other uses?

I really feel the compiler should flag variable-less cases like a/1, c/0, b/1 above as errors (easy to detect), and even repeat/0 should probably have a value: repeat(Count). Anything which redoes successfully should NOT redo successfully in the same context on exactly the same ground arguments. It has the same squishy feeling of irrelevancy as a(X) :- b(Y). b(Z). Brrr!.

Body:
@false mentions in his answer using duplicated clauses to "answer the question how often the clause contributes to solutions." He also mentions "that a tracer cannot tell you this as easily".

A better solution to this use case is to use a ports profiler tool as found in e.g. ECLiPSe and Logtalk. No need to duplicate clauses to gather that information.

As an example, consider the following pure program, saved in a pure.pl file:

a :- b, c.

b.
b :- d.

c.

d.

Let's include this code in an object. We can define it in a source file:

:- object(pure).

    :- set_logtalk_flag(debug, on).

    :- public(a/0).
    :- include('pure.pl').

:- end_object.

Alternatively, we can create pure as a dynamic object:

?- create_object(pure, [],  [set_logtalk_flag(debug,on), public(a/0), include('pure.pl')], []).
true.

Either way, after loading or creating the pure object and loading the ports_profiler tool, we can e.g. query all solutions for the a/0 predicate and then print the profiling data:

?- {ports_profiler(loader)}.
...
% (0 warnings)
true.

?- pure::a.
true ;
true.

?- ports_profiler::data.
-------------------------------------------------------------------
Entity  Predicate    Fact  Rule  Call  Exit *Exit  Fail  Redo Error
-------------------------------------------------------------------
pure    a/0             0     1     1     1     1     0     1     0
pure    b/0             1     1     1     1     1     0     1     0
pure    c/0             2     0     2     2     0     0     0     0
pure    d/0             1     0     1     1     0     0     0     0
-------------------------------------------------------------------
true.

The table displays port crossing information for all predicates used in the query to the a/0 predicate. For example, that the predicate c/0 as called twice (for the two solutions to a/0) and exited deterministically. On the other hand, the predicate b/0 was called once by succeeded twice (on of them non-deterministically) due to backtracking.

For details on the portable port_profiler tool and a discussion on the insights that it can provide, see:

https://logtalk.org/manuals/devtools/ports_profiler.html


问:
React axios api call: How can I return multiple parameters in a url?
Wasn't sure how to ask this..

How can I return, say, people/0-15? I don't want just people/0, I'd like to access people 0-15, etc

I want to return multiple people. What should I be doing here?

```<code>function getData() {
    return axios.get("https://www.blablahtest.com/api/orders");
  }

function getPerson() {
    return axios.get(`https://www.blablahtest.com/api/people/0`); <----
  }

  useEffect(() => {
    axios.all([getData(), getPerson()]).then(
      axios.spread(function(item, person) {
        setData(item.data);
        setPersonData(person.data);
      })
    );
  }, []);
</code>```

答:
Don't use axios.spread (it will be removed in future versions https://github.com/axios/axios/issues/1042)

You can try below:

```<code>function getData() {
  return axios.get("https://www.blablahtest.com/api/orders");
}

function getPerson() {
  return axios.get("https://www.blablahtest.com/api/people/0");
}

useEffect(() => {
  Promise.all([getData(), getPerson()]).then((item, person) => {
    setData(item.data);
    setPersonData(person.data);
  })
}, []);
</code>```

I hope it helps.

Body:
Wasn't sure how to ask this..

How can I return, say, people/0-15? I don't want just people/0, I'd like to access people 0-15, etc

I want to return multiple people. What should I be doing here?

function getData() {
    return axios.get("https://www.blablahtest.com/api/orders");
  }

function getPerson() {
    return axios.get(`https://www.blablahtest.com/api/people/0`); <----
  }

  useEffect(() => {
    axios.all([getData(), getPerson()]).then(
      axios.spread(function(item, person) {
        setData(item.data);
        setPersonData(person.data);
      })
    );
  }, []);

Body:
Don't use axios.spread (it will be removed in future versions https://github.com/axios/axios/issues/1042)

You can try below:

function getData() {
  return axios.get("https://www.blablahtest.com/api/orders");
}

function getPerson() {
  return axios.get("https://www.blablahtest.com/api/people/0");
}

useEffect(() => {
  Promise.all([getData(), getPerson()]).then((item, person) => {
    setData(item.data);
    setPersonData(person.data);
  })
}, []);

I hope it helps.


问:
in over multiple lists
I was recently confused by this

if 2 in ([1,2] or [3,4]) : print(True)
else: print(False)
#prints True
```

or is a boolean operator so how can it be applied to lists?

why does it work the same as if 2 in [1,2] or [3,4]?

答:
Use any()

```<code>print(any(2 in x for x in [[1, 2], [3, 4]]))
</code>```

or is operates on any types, not just booleans. It returns the leftmost operand that's truthy, or False if none of the operands are truthy. So ([1, 2] or [3, 4]) is equivalent to [1, 2] because any non-empty list is truthy.

In general, operators don't automatically distribute in programming languages like they do in English. x in (a or b) is not the same as x in a or x in b. Programming languages evaluate expressions recursively, so x in (a or b) is roughly equivalent to:

```<code>temp = a or b
x in temp
</code>```

Title: in over multiple lists

Body:
I was recently confused by this

if 2 in ([1,2] or [3,4]) : print(True)
else: print(False)
#prints True

or is a boolean operator so how can it be applied to lists?

why does it work the same as if 2 in [1,2] or [3,4]?

Body:
Use any()

print(any(2 in x for x in [[1, 2], [3, 4]]))

or is operates on any types, not just booleans. It returns the leftmost operand that's truthy, or False if none of the operands are truthy. So ([1, 2] or [3, 4]) is equivalent to [1, 2] because any non-empty list is truthy.

In general, operators don't automatically distribute in programming languages like they do in English. x in (a or b) is not the same as x in a or x in b. Programming languages evaluate expressions recursively, so x in (a or b) is roughly equivalent to:

temp = a or b
x in temp


问:
Split a dataframe based on a column and write out the multiple split .txt files with specific names
I'm dealing with my huge .txt data frames generated from microscopic data. Each single .txt output file from it is about 3 to 4 GB! And I have a couple hundreds of them....

For each of those monster file, it has a couple hundreds of features, some are categorical and some are numeric.

Here is an abstract example of the dataframe:

```<code>df <- read.csv("output.txt", sep="\t", skip = 9,header=TRUE, fill = T)
df

Row  Column stimulation Compound Concentration treatmentsum Pid_treatmentsum  var1 var2  var3  ...
1    1      uns         Drug1    3             uns_Drug1_3  Jack_uns_Drug1_3  15.0 20.2  3.568 ...
1    1      uns         Drug1    3             uns_Drug1_3  Jack_uns_Drug1_3  55.0 0.20  9.068
1    1      uns         Drug2    5             uns_Drug2_5  Jack_uns_Drug2_5  100  50.2  3.568
1    1      uns         Drug2    5             uns_Drug2_5  Jack_uns_Drug2_5  75.0 60.2  13.68
1    1      3S          Drug1    3             3s_Drug3_3   Jack_3s_Drug1_3   65.0 30.8  6.58
1    1      4S          Drug1    3             4s_Drug3_3   Jack_4s_Drug1_3   35.0 69.3  2.98
.....
</code>```

And I would like to split the data frame based on common value in a categorical column, the treatmentsum.
So I can have all cells treated with the same drug and same dosage together, aka all "uns_Drug1_3" goes to one output.txt.

I have seen similar post so I used     split()

```<code>sptdf <- split(df, df$treatmentsum)
</code>```

it worked, as now sptdf gave me lists of data frames. Now I want to write them out as tables, ideally I want to use the "Pid_treatmentsum" element as the name of each splited file's name, as they should have the exact same "Pid_treatmentsum" after splitting. I don't quite know how to do that, so thus far I can at least manual input patient ID and join them by paste

```<code>lapply(names(sptdf), function(x){write.table(sptdf[[x]], file = paste("Jack", x, sep = "_"))})
</code>```

This works isn a sense that it writes out all the individual files with correct titles, but they are not .txt and if I open them in excel, I get warning messages that they are corrupted. Meanwhile in R, I get warning messages

    Error in file(file, ifelse(append, "a", "w")) :
      cannot open the connection

Where did I got this wrong?

Given the sheer size of each output file by the microscope  (3-4GB), is this the best way to do this?

And if I can push this further, can I dump all hundreds of those huge files in a folder, and could I write a loop to autopmate the process instead of splitting one file a time? the only problem I foresee is the microscope  outfiles always have the same name, titled "output".

Thank you in advance, and sorry for the long post.

Cheers,
ML

答:
I don't believe this is very different from the OP's code but here it goes.

First, a test data set. I will use a copy of the built-in data set iris

```<code>df <- iris
names(df)[5] <- "Pid_treatmentsum"
</code>```

Now the file writing code.

```<code>sptdf <- split(df, df$Pid_treatmentsum)
lapply(sptdf, function(DF){
  outfile <- as.character(unique(DF[["Pid_treatmentsum"]]))
  outfile <- paste0(outfile, ".txt")
  write.table(DF,
              file = outfile,
              row.names = FALSE,
              quote = FALSE)
})
</code>```

If Excel complains that the file is corrupt maybe write.csv (and file extension "csv") will solve the problem.

Edit.

To automate the code above to processing many files, the split/lapply could be rewritten as a function. Then the function would be called passing the filenames as an argument.

Something along the lines of (untested)

```<code>splitFun <- function(file, col = "Pid_treatmentsum", ...){
  X <- read.table(file, header = TRUE, ...)
  sptdf <- split(X, X[[col]])
  lapply(sptdf, function(DF){
    outfile <- as.character(unique(DF[[col]]))
    outfile <- paste0(outfile, ".txt")
    write.table(DF,
                file = outfile,
                row.names = FALSE,
                quote = FALSE)
  })
}

filenames <- list.files(pattern = "<a regular expression>")
lapply(filenames, splitFun)
</code>```

Body:
I'm dealing with my huge .txt data frames generated from microscopic data. Each single .txt output file from it is about 3 to 4 GB! And I have a couple hundreds of them....

For each of those monster file, it has a couple hundreds of features, some are categorical and some are numeric.

Here is an abstract example of the dataframe:

df <- read.csv("output.txt", sep="\t", skip = 9,header=TRUE, fill = T)
df

Row  Column stimulation Compound Concentration treatmentsum Pid_treatmentsum  var1 var2  var3  ...
1    1      uns         Drug1    3             uns_Drug1_3  Jack_uns_Drug1_3  15.0 20.2  3.568 ...
1    1      uns         Drug1    3             uns_Drug1_3  Jack_uns_Drug1_3  55.0 0.20  9.068
1    1      uns         Drug2    5             uns_Drug2_5  Jack_uns_Drug2_5  100  50.2  3.568
1    1      uns         Drug2    5             uns_Drug2_5  Jack_uns_Drug2_5  75.0 60.2  13.68
1    1      3S          Drug1    3             3s_Drug3_3   Jack_3s_Drug1_3   65.0 30.8  6.58
1    1      4S          Drug1    3             4s_Drug3_3   Jack_4s_Drug1_3   35.0 69.3  2.98
.....

And I would like to split the data frame based on common value in a categorical column, the treatmentsum.
So I can have all cells treated with the same drug and same dosage together, aka all "uns_Drug1_3" goes to one output.txt.

I have seen similar post so I used     split()

sptdf <- split(df, df$treatmentsum)

it worked, as now sptdf gave me lists of data frames. Now I want to write them out as tables, ideally I want to use the "Pid_treatmentsum" element as the name of each splited file's name, as they should have the exact same "Pid_treatmentsum" after splitting. I don't quite know how to do that, so thus far I can at least manual input patient ID and join them by paste

lapply(names(sptdf), function(x){write.table(sptdf[[x]], file = paste("Jack", x, sep = "_"))})

This works isn a sense that it writes out all the individual files with correct titles, but they are not .txt and if I open them in excel, I get warning messages that they are corrupted. Meanwhile in R, I get warning messages

    Error in file(file, ifelse(append, "a", "w")) :
      cannot open the connection

Where did I got this wrong?

Given the sheer size of each output file by the microscope  (3-4GB), is this the best way to do this?

And if I can push this further, can I dump all hundreds of those huge files in a folder, and could I write a loop to autopmate the process instead of splitting one file a time? the only problem I foresee is the microscope  outfiles always have the same name, titled "output".

Thank you in advance, and sorry for the long post.

Cheers,
ML

Body:
I don't believe this is very different from the OP's code but here it goes.

First, a test data set. I will use a copy of the built-in data set iris

df <- iris
names(df)[5] <- "Pid_treatmentsum"

Now the file writing code.

sptdf <- split(df, df$Pid_treatmentsum)
lapply(sptdf, function(DF){
  outfile <- as.character(unique(DF[["Pid_treatmentsum"]]))
  outfile <- paste0(outfile, ".txt")
  write.table(DF,
              file = outfile,
              row.names = FALSE,
              quote = FALSE)
})

If Excel complains that the file is corrupt maybe write.csv (and file extension "csv") will solve the problem.

Edit.

To automate the code above to processing many files, the split/lapply could be rewritten as a function. Then the function would be called passing the filenames as an argument.

Something along the lines of (untested)

splitFun <- function(file, col = "Pid_treatmentsum", ...){
  X <- read.table(file, header = TRUE, ...)
  sptdf <- split(X, X[[col]])
  lapply(sptdf, function(DF){
    outfile <- as.character(unique(DF[[col]]))
    outfile <- paste0(outfile, ".txt")
    write.table(DF,
                file = outfile,
                row.names = FALSE,
                quote = FALSE)
  })
}

filenames <- list.files(pattern = "<a regular expression>")
lapply(filenames, splitFun)


问:
Spring Data JPA to return List of Dates with a specified range (Start Date && End Date)
Currently, I am trying to return a list of Objects with a Date that falls into a range that is given by parameters... However, when I run my rest api call, nothing is returned. I am not sure if I am doing this Spring JPA request correctly and decided to get some feedback whether or not something I did is incorrect.

Here's some brief pseudocode:

Object Model

```<code>public class mResult{
/* other variables */
LocalDate runDate;
}
</code>```

Repo

```<code>public interface mResultRepository extends CrudRepository<mResult,String> {
    List<mResult> findAllByRunDateBetween(LocalDate startDate,LocalDate endDate);
}
</code>```

Service

```<code>mResultRepository mRepository;

public List<mResult> getAllBetweenDates(LocalDate startDate, LocalDate endDate){
     return mRepository.findAllByRunDateBetween(startDate,endDate);
 }

</code>```

My repo contains JSON objects for example:

```<code>{"runDate": "2019-02-05"}
{"runDate": "2019-02-06"}
{"runDate": "2019-02-10}
</code>```

If my range is 2019-02-01 to 2019-02-09, then it should only return those in this range. However, when I run my API request, nothing is returned. Is my Spring JPA request correct? TIA

答: I added an @DateTimeFormat annotation to my controller. Turns out the Spring JPA Request was correct, but it wasn't taking in my "yyyy-MM-dd" format.</p>

Body:
Currently, I am trying to return a list of Objects with a Date that falls into a range that is given by parameters... However, when I run my rest api call, nothing is returned. I am not sure if I am doing this Spring JPA request correctly and decided to get some feedback whether or not something I did is incorrect.

Here's some brief pseudocode:

Object Model

public class mResult{
/* other variables */
LocalDate runDate;
}

Repo

public interface mResultRepository extends CrudRepository<mResult,String> {
    List<mResult> findAllByRunDateBetween(LocalDate startDate,LocalDate endDate);
}

Service

mResultRepository mRepository;

public List<mResult> getAllBetweenDates(LocalDate startDate, LocalDate endDate){
     return mRepository.findAllByRunDateBetween(startDate,endDate);
 }

My repo contains JSON objects for example:

{"runDate": "2019-02-05"}
{"runDate": "2019-02-06"}
{"runDate": "2019-02-10}

If my range is 2019-02-01 to 2019-02-09, then it should only return those in this range. However, when I run my API request, nothing is returned. Is my Spring JPA request correct? TIA


问:
Says it cannot be used as constant
Visual studio 2019

```<code>const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];
</code>```

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.

答:
it says on w[how] that it must be "const" expression(but is is??)

It probably doesn't say that (in future, avoid paraphrasing error messages). I assume that it actually says that it must be a constant expression. The distinction may seem subtle, but is significant.

"Constant expression" is a specific term defined by the C++ language. There are many rules that specify whether an expression is constant, but a concise way to describe it is: Expression whose value is determined at translation time.

As confusing as it may be, an id-expression that names a const variable is not necessarily a constant expression. Constness of a type by itself merely implies that the variable is constant at runtime. And in this case, how specifically is not a constant expression.

The reason why how is not a constant expression is because its initialiser inputs * layerN + pow(layerN,layers) + output * layerN is not a constant expression. And that is because it contains a call to a non-constexpr function pow:

Here is a simple implementation of a constexpr pow function for int:

```<code>constexpr int
constant_pow(int base, int exp)
{

    return exp ? (base * constant_pow(base, exp-1))
               : 1;
}
</code>```

Title: Says it cannot be used as constant

Body:
Visual studio 2019

const int inputs = 1, layers = 2, layerN = 3, output = 1;
const int how = inputs * layerN + pow(layerN,layers) + output * layerN;
float w[how];

it says on w[how] that it must be "const" expression(but is is??)

I cannot run the program with this error.

hielp.

Body:
it says on w[how] that it must be "const" expression(but is is??)

It probably doesn't say that (in future, avoid paraphrasing error messages). I assume that it actually says that it must be a constant expression. The distinction may seem subtle, but is significant.

"Constant expression" is a specific term defined by the C++ language. There are many rules that specify whether an expression is constant, but a concise way to describe it is: Expression whose value is determined at translation time.

As confusing as it may be, an id-expression that names a const variable is not necessarily a constant expression. Constness of a type by itself merely implies that the variable is constant at runtime. And in this case, how specifically is not a constant expression.

The reason why how is not a constant expression is because its initialiser inputs * layerN + pow(layerN,layers) + output * layerN is not a constant expression. And that is because it contains a call to a non-constexpr function pow:

Here is a simple implementation of a constexpr pow function for int:

constexpr int
constant_pow(int base, int exp)
{

    return exp ? (base * constant_pow(base, exp-1))
               : 1;
}


问:
socket.on function is not being called for the first time when react component mounted
I am trying to create a simple real time chat app to practise with socket-io. I am using React to create UI and i am using NodeJS with Express web server. I have ChatPage React component to show messages.

I am emitting an event newMessage when a user joined to a room and i am sending a welcome message as data from server to client. At that time i am routing to ChatPage component and i am subscribing to updateUserList event in componentWillMount but this event is not coming up to that callback i defined. After some trials i realized a weird thing about this event. I subscribed this event from another .js file and i could see data that i sent from server.

```<code>// server.js
socket.on('joinRoom', (data, callback) => {
    const { username, roomName } = data
    if (username === '' || roomName === '') {
        if (callback) {
            return callback({ error: 'Username and password required!' })
        }
        return
    }

    socket.join(roomName, (err) => {
        if (err && callback) {
            return callback({ error: 'Could not connect to room.' })
        }

        socket.emit('newMessage', generateMessage('Admin', 'Welcome to chat app'))
        if (callback) {
            callback()
        }
    })
})

// ChatPage.js
componentWillMount() {
    const socket = io('http://localhost:3400')
    socket.on('newMessage', (message) => {
        console.log('newMessage', message)
    })
}

// event is coming to here instead!
import socketIOClient from "socket.io-client";

export const getSocketIOClient = () => {
    const endpoint = "http://localhost:3400"
    const socket = socketIOClient(endpoint)
    socket.on('newMessage', (er) => {
        console.log('newMessage', message)
    })
    return socket;
}
</code>```

答:
I faced similar porblem in my project. There I noticed few things which are missing in your code.

You need to call back join room in client code as well in componentWillMount() method.

You need to initialize socket in state variable. I don't know exactly why it doesn't work when we initialize in const variable but it works when we use state variable instead. I verified this code, it works fine even in the first time react component mount.

Here, is sample code:

```<code>import React from 'react'
import io from 'socket.io-client';

class SocketExample extends React.Component {

    state = {
        chatMessage: '',
        chatMessages: [],
        socket: io.connect(`http://localhost:3001`),
    }

    submitChatMessage = (e) => {
        e.preventDefault()
        if (this.state.chatMessage.length > 0) {
            this.state.socket.emit('newMessage', {
                username: this.props.currentUser.username,
                message: this.state.chatMessage,
            });
            this.setState({
                chatMessage: '',
            })
        }
    }

    componentDidMount(){
        this.state.socket.on('connect', () => {
            this.state.socket.emit('join', { uniqueValue: chatRoomName });
        });
        this.state.socket.on("newMessage", data => {
            this.setState({
                chatMessages: [...this.state.chatMessages, data],
            });
        });
    }

    render() {
        return (
            <div>{this.state.chatMessages.map(chat => {
                return <p>{chat.username + ': ' + chat.message}</p>
            })}</div>
        )
    }
}

export default SocketExample
</code>```

Body:
I am trying to create a simple real time chat app to practise with socket-io. I am using React to create UI and i am using NodeJS with Express web server. I have ChatPage React component to show messages.

I am emitting an event newMessage when a user joined to a room and i am sending a welcome message as data from server to client. At that time i am routing to ChatPage component and i am subscribing to updateUserList event in componentWillMount but this event is not coming up to that callback i defined. After some trials i realized a weird thing about this event. I subscribed this event from another .js file and i could see data that i sent from server.

// server.js
socket.on('joinRoom', (data, callback) => {
    const { username, roomName } = data
    if (username === '' || roomName === '') {
        if (callback) {
            return callback({ error: 'Username and password required!' })
        }
        return
    }

    socket.join(roomName, (err) => {
        if (err && callback) {
            return callback({ error: 'Could not connect to room.' })
        }

        socket.emit('newMessage', generateMessage('Admin', 'Welcome to chat app'))
        if (callback) {
            callback()
        }
    })
})

// ChatPage.js
componentWillMount() {
    const socket = io('http://localhost:3400')
    socket.on('newMessage', (message) => {
        console.log('newMessage', message)
    })
}

// event is coming to here instead!
import socketIOClient from "socket.io-client";

export const getSocketIOClient = () => {
    const endpoint = "http://localhost:3400"
    const socket = socketIOClient(endpoint)
    socket.on('newMessage', (er) => {
        console.log('newMessage', message)
    })
    return socket;
}

Body:
I faced similar porblem in my project. There I noticed few things which are missing in your code.

You need to call back join room in client code as well in componentWillMount() method.

You need to initialize socket in state variable. I don't know exactly why it doesn't work when we initialize in const variable but it works when we use state variable instead. I verified this code, it works fine even in the first time react component mount.

Here, is sample code:

import React from 'react'
import io from 'socket.io-client';

class SocketExample extends React.Component {

    state = {
        chatMessage: '',
        chatMessages: [],
        socket: io.connect(`http://localhost:3001`),
    }

    submitChatMessage = (e) => {
        e.preventDefault()
        if (this.state.chatMessage.length > 0) {
            this.state.socket.emit('newMessage', {
                username: this.props.currentUser.username,
                message: this.state.chatMessage,
            });
            this.setState({
                chatMessage: '',
            })
        }
    }

    componentDidMount(){
        this.state.socket.on('connect', () => {
            this.state.socket.emit('join', { uniqueValue: chatRoomName });
        });
        this.state.socket.on("newMessage", data => {
            this.setState({
                chatMessages: [...this.state.chatMessages, data],
            });
        });
    }

    render() {
        return (
            <div>{this.state.chatMessages.map(chat => {
                return <p>{chat.username + ': ' + chat.message}</p>
            })}</div>
        )
    }
}

export default SocketExample


答:
Both statement are different.

In first case python will first run 2 in [1,4] its False so now it will check for bool([1,3]) and its True so it prints 1.

But for second case what happening is first ([1,4] or [1,3]) is executing and this return first non-empty list. And so it will return [1,4] but 2 is not in list so nothing gets printed.

Its all about execution order.

Look at two more examples. Specially last example. ([1,4] or [2,4]) will return [1,4] and 2 is not in [1,4]. Now it will not check in second list [2,4]. If that's you want this is not the right way to do it. Use any

>>> if 2 in [1,4] or [1,3]: # True
...     print(1)
...
1
>>> if 2 in ([1,4] or [1,3]): # False
...     print(1)
...
>>> if 2 in [1,4] or []: # False
...     print(1)
...
>>> if 2 in ([1,4] or [2,4]): # False!!
...     print(1)
...
```

Title: in over multiple lists


问:
How do I exclude search results in Python
I am using the following library to extract google search urls:

```<code>from googlesearch import search
</code>```

This is the function that performs the google search:

```<code>search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0)
</code>```

My question is: How do I use this function to exclude certain domains in my search results?

答:
If you want use search interface to exclude a domain, add an argument

```<code> extra_params={'-site' : 'youtube.com'}
</code>```

e.g.

```<code>  search(query,
      tld='com',
      lang='en',
      num=10,
      start=0,
      stop=None,
      pause=2.0,
      extra_params={'-site' : 'youtube.com'}
  )
</code>```

Alternatively, you can just append -site:youtube.com or whatever needed into your query.

Body:
I am using the following library to extract google search urls:

from googlesearch import search

This is the function that performs the google search:

search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0)

My question is: How do I use this function to exclude certain domains in my search results?

Body:
If you want use search interface to exclude a domain, add an argument

 extra_params={'-site' : 'youtube.com'}

e.g.

  search(query,
      tld='com',
      lang='en',
      num=10,
      start=0,
      stop=None,
      pause=2.0,
      extra_params={'-site' : 'youtube.com'}
  )

Alternatively, you can just append -site:youtube.com or whatever needed into your query.


问:
Check image is loaded in Image.network widget in flutter
I am new to Flutter. I try to load network images using image.network widget. it's working fine but sometimes it takes time to load. I added tap listener to image.network during tap I need to check image is fully loaded or not based on the result I need to redirect the page. how to check image is loaded or not?

Code:

```<code>new Image.network('http://via.placeholder.com/350x150')
</code>```

Any help will be appreciated, thank you in advance

答:
thank you for your comment thats help to resolve the situation that how to know if the image is loaded or not hope that help

I use a StatefulWidget
need a editing depend on your AffichScreen

situation :

```<code> -i have an url that i enter
 -if url is correct affich the image if not affich an icon
 -if empty affich a Text()
 -precacheImage check if the url is correct if not give an error and change _loadingimage(bool) to false to affich the icon eror
 -i use a NetworkImage to check with precacheImage and before affich use a Image.network

   bool _loadingimage;
ImageProvider _image;
Image _imagescreen;

@override
  void initState() {
    _loadingimage = true;
    _imageUrlfocusNode.addListener(_updateImageUrl);
    super.initState();
  }

   @override
  void dispose() {
    _imageUrlfocusNode.removeListener(_updateImageUrl);
    _quantityfocusNode.dispose();
    _imageUrlConroller.dispose();
    _imageUrlfocusNode.dispose();
    super.dispose();
  }

  void _updateImageUrl() {
    setState(() {
      _image = NetworkImage(_imageUrlConroller.text);
    });
    if (!_imageUrlfocusNode.hasFocus) {
      if (_imageUrlConroller.text.isNotEmpty) {
        setState(() {
          loadimage();
        });
      }
    }
  }

  void loadimage() {
    _loadingimage = true;
    precacheImage(_image, context, onError: (e, stackTrace) {
      // log.fine('Image ${widget.url} failed to load with error $e.');
      print('error $e');
      setState(() {
        _loadingimage = false;
        print(_loadingimage);
      });
    });
    if (_loadingimage == true) {
      _imagescreen = Image.network(
        _imageUrlConroller.text,
        fit: BoxFit.fill,
      );
    }
  }

  Container(
                              width: 100,
                              height: 100,
                              margin: EdgeInsets.only(top: 13, right: 11),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  width: 1,
                                  color: Colors.grey,
                                ),
                              ),
                              child:_imageUrlConroller.text.isEmpty
                                      ? Text('enter an url')
                                      : !_loadingimage
                                          ? Container(
                                              child: Icon(Icons.add_a_photo),
                                            )
                                          : Container(
                                              child: _imagescreen,
                                            ),
                            ),
</code>```

Body:
I am new to Flutter. I try to load network images using image.network widget. it's working fine but sometimes it takes time to load. I added tap listener to image.network during tap I need to check image is fully loaded or not based on the result I need to redirect the page. how to check image is loaded or not?

Code:

new Image.network('http://via.placeholder.com/350x150')

Any help will be appreciated, thank you in advance

Body:
thank you for your comment thats help to resolve the situation that how to know if the image is loaded or not hope that help

I use a StatefulWidget
need a editing depend on your AffichScreen

situation :

 -i have an url that i enter
 -if url is correct affich the image if not affich an icon
 -if empty affich a Text()
 -precacheImage check if the url is correct if not give an error and change _loadingimage(bool) to false to affich the icon eror
 -i use a NetworkImage to check with precacheImage and before affich use a Image.network

   bool _loadingimage;
ImageProvider _image;
Image _imagescreen;

@override
  void initState() {
    _loadingimage = true;
    _imageUrlfocusNode.addListener(_updateImageUrl);
    super.initState();
  }

   @override
  void dispose() {
    _imageUrlfocusNode.removeListener(_updateImageUrl);
    _quantityfocusNode.dispose();
    _imageUrlConroller.dispose();
    _imageUrlfocusNode.dispose();
    super.dispose();
  }

  void _updateImageUrl() {
    setState(() {
      _image = NetworkImage(_imageUrlConroller.text);
    });
    if (!_imageUrlfocusNode.hasFocus) {
      if (_imageUrlConroller.text.isNotEmpty) {
        setState(() {
          loadimage();
        });
      }
    }
  }

  void loadimage() {
    _loadingimage = true;
    precacheImage(_image, context, onError: (e, stackTrace) {
      // log.fine('Image ${widget.url} failed to load with error $e.');
      print('error $e');
      setState(() {
        _loadingimage = false;
        print(_loadingimage);
      });
    });
    if (_loadingimage == true) {
      _imagescreen = Image.network(
        _imageUrlConroller.text,
        fit: BoxFit.fill,
      );
    }
  }

  Container(
                              width: 100,
                              height: 100,
                              margin: EdgeInsets.only(top: 13, right: 11),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  width: 1,
                                  color: Colors.grey,
                                ),
                              ),
                              child:_imageUrlConroller.text.isEmpty
                                      ? Text('enter an url')
                                      : !_loadingimage
                                          ? Container(
                                              child: Icon(Icons.add_a_photo),
                                            )
                                          : Container(
                                              child: _imagescreen,
                                            ),
                            ),


问:
Multiplatform crash reporting?
What would be the best way to implement crash reporting in a cross-platform app in c++ (windows, mac, linux)? Looked into google breakpad, but spent a few weeks trying to make socorro (UI) work to no avail.

edit: @Nim to clear up, I want to send a stack-trace to my server when some exception occurs.

答:
When we went crossplatform (from being previously Windows-only), we spent a lot of time researching the possible tools for exactly this. Google Breakpad really is the best crossplatform solution out there.

Your problem is Socorro, which is huge, obfuscated, and confusing. I can suggest two routes:

Drop the current version of Socorro, which is way too much in love with newfangled OSS toys like Hadoop, and roll back to Socorro 1.x. You'll need to do a bit more work to set up your processors, and your dumps will go into a Postgres table, but you'll have way fewer moving parts and crazy infrastructure to deal with.

Forget about Socorro altogether and write your own processors for the Breakpad dumps and a UI to view them with. Breakpad has already done the really hard work -- parsing the symbols and catching the exceptions -- so all you need to write is a collector that the dumps can get uploaded to, a farm to run the Breakpad processors on them, someplace to store the processed results, and something to view them.

Knowing what we do now, we would have probably gone with the second option rather than trying to integrate Socorro — the amount of time it's taken us to find a version of Socorro that works for us and adapt it to our workflow has already exceeded what it would have taken for us to just write a system that does exactly what we want.

Title: Multiplatform crash reporting?


问:
How to check if a url is valid (actually loads a page with content) efficiently?
QUESTION:

How to check if a url is valid and actually loads a page ?

With my current code, only the status code is checked, which means that a url like http://fsd.com/ will be considered as valid although it does not load anything.

How can I check that the url actually points to a website that can be loaded ?

CODE:

```<code>$.ajax({
                    url: link,
                    dataType: 'jsonp',
                    statusCode: {
                        200: function() {
                            console.log( "status code 200 returned");
                            validURL = true;
                        },
                        404: function() {
                            console.log( "status code 404 returned");
                            validURL = false;
                        }
                    },
                    error:function(){
                        console.log("Error");
                    }
                });
</code>```

EDIT: By valid, I mean that the page is at last partially loaded (as in at least the html & css are loaded) instead of loading forever or somehow failing without the status code being 404.

EDIT2: http://fsd.com actually returns a 404 now as it should...

EDIT3: Another example: https://dsd.com loads an empty page (status code 200) and http://dsd.com actually loads a page with content (status code 200). On my Node.js backend, the npm package "url-exists" indicates that https://dsd.com is invalid, while my frontend with the code shown in my question indicates it is a valid url. This is what the package code looks like: https://github.com/boblauer/url-exists/blob/master/index.js but I wanted to know what would be the best way according to SO users.

EDIT4:

Sadly, the request provided by Addis is apparently blocked by CORS which blocks the execution of the rest of my code while my original request did not.

```<code>$.ajax({
                    type: "HEAD",
                    url: link,
                    dataType: 'jsonp',
                }).done(function(message,text,response){
                    const size = response.getResponseHeader('Content-Length');
                    const status = response.status;
                    console.log("SIZE: "+size);
                    console.log("STATUS: "+status);
                    if(size > 0 && status == "200") {
                        $("#submitErrorMessage").css("display","none");
                        $('#directoryForm').submit();
                    }
                    else {
                        $("#submitErrorMessage").css("display","block");
                        $("#submitLoading").css("display","none");
                    }
                });
</code>```

EDIT 5:

To be more precise, both requests trigger a warning message in the browser console indicating that the response has been blocked because of CORS but my original code is actually executed in its entirety while the the other request doesn't get to the console.log().

EDIT 6:

```<code>$.ajax({
                    async: true,
                    url: link,
                    dataType: 'jsonp',
                    success: function( data, status, jqxhr ){
                        console.log( "Response data received: ", data );
                        console.log("Response data length: ", data.length);
                        console.log("Response status code: ", status);
                        if (status == "200" && data.length > 0) {
                            $("#submitErrorMessage").css("display","none");
                            $('#directoryForm').submit();
                        }
                        else {
                            $("#submitErrorMessage").css("display","block");
                            $("#submitLoading").css("display","none");
                        }

                    },
                    error:function(jqXHR, textStatus, errorThrown){
                        console.log("Error: ", errorThrown);
                    }
                });
</code>```

Error:

```<code>Error:  Error: jQuery34108117853955031047_1582059896271 was not called
    at Function.error (jquery.js:2)
    at e.converters.script json (jquery.js:2)
    at jquery.js:2
    at l (jquery.js:2)
    at HTMLScriptElement.i (jquery.js:2)
    at HTMLScriptElement.dispatch (jquery.js:2)
    at HTMLScriptElement.v.handle (jquery.js:2)
</code>```

答:
A successful response without content "should" return a 204: No Content but it doesn't mean that every developer implements the spec correctly. I guess it really depends on what you consider "valid" to mean for your business case.

Valid = 200 && body has some content?

If so you can the test this in the success callback.

```<code>$.ajax({
    url: link,
    dataType: 'jsonp',
    success: function (response) {
        // todo: test the response for "valid"
        // proper length? contains expected content?
    },
    statusCode: {
        200: function() {
            console.log( "status code 200 returned");
            validURL = true;
        },
        404: function() {
            console.log( "status code 404 returned");
            validURL = false;
        }
    },
    error:function(){
        console.log("Error");
    }
});
</code>```

Body:
QUESTION:

How to check if a url is valid and actually loads a page ?

With my current code, only the status code is checked, which means that a url like http://fsd.com/ will be considered as valid although it does not load anything.

How can I check that the url actually points to a website that can be loaded ?

CODE:

$.ajax({
                    url: link,
                    dataType: 'jsonp',
                    statusCode: {
                        200: function() {
                            console.log( "status code 200 returned");
                            validURL = true;
                        },
                        404: function() {
                            console.log( "status code 404 returned");
                            validURL = false;
                        }
                    },
                    error:function(){
                        console.log("Error");
                    }
                });

EDIT: By valid, I mean that the page is at last partially loaded (as in at least the html & css are loaded) instead of loading forever or somehow failing without the status code being 404.

EDIT2: http://fsd.com actually returns a 404 now as it should...

EDIT3: Another example: https://dsd.com loads an empty page (status code 200) and http://dsd.com actually loads a page with content (status code 200). On my Node.js backend, the npm package "url-exists" indicates that https://dsd.com is invalid, while my frontend with the code shown in my question indicates it is a valid url. This is what the package code looks like: https://github.com/boblauer/url-exists/blob/master/index.js but I wanted to know what would be the best way according to SO users.

EDIT4:

Sadly, the request provided by Addis is apparently blocked by CORS which blocks the execution of the rest of my code while my original request did not.

$.ajax({
                    type: "HEAD",
                    url: link,
                    dataType: 'jsonp',
                }).done(function(message,text,response){
                    const size = response.getResponseHeader('Content-Length');
                    const status = response.status;
                    console.log("SIZE: "+size);
                    console.log("STATUS: "+status);
                    if(size > 0 && status == "200") {
                        $("#submitErrorMessage").css("display","none");
                        $('#directoryForm').submit();
                    }
                    else {
                        $("#submitErrorMessage").css("display","block");
                        $("#submitLoading").css("display","none");
                    }
                });

EDIT 5:

To be more precise, both requests trigger a warning message in the browser console indicating that the response has been blocked because of CORS but my original code is actually executed in its entirety while the the other request doesn't get to the console.log().

EDIT 6:

$.ajax({
                    async: true,
                    url: link,
                    dataType: 'jsonp',
                    success: function( data, status, jqxhr ){
                        console.log( "Response data received: ", data );
                        console.log("Response data length: ", data.length);
                        console.log("Response status code: ", status);
                        if (status == "200" && data.length > 0) {
                            $("#submitErrorMessage").css("display","none");
                            $('#directoryForm').submit();
                        }
                        else {
                            $("#submitErrorMessage").css("display","block");
                            $("#submitLoading").css("display","none");
                        }

                    },
                    error:function(jqXHR, textStatus, errorThrown){
                        console.log("Error: ", errorThrown);
                    }
                });

Error:

Error:  Error: jQuery34108117853955031047_1582059896271 was not called
    at Function.error (jquery.js:2)
    at e.converters.script json (jquery.js:2)
    at jquery.js:2
    at l (jquery.js:2)
    at HTMLScriptElement.i (jquery.js:2)
    at HTMLScriptElement.dispatch (jquery.js:2)
    at HTMLScriptElement.v.handle (jquery.js:2)

Body:
A successful response without content "should" return a 204: No Content but it doesn't mean that every developer implements the spec correctly. I guess it really depends on what you consider "valid" to mean for your business case.

Valid = 200 && body has some content?

If so you can the test this in the success callback.

$.ajax({
    url: link,
    dataType: 'jsonp',
    success: function (response) {
        // todo: test the response for "valid"
        // proper length? contains expected content?
    },
    statusCode: {
        200: function() {
            console.log( "status code 200 returned");
            validURL = true;
        },
        404: function() {
            console.log( "status code 404 returned");
            validURL = false;
        }
    },
    error:function(){
        console.log("Error");
    }
});


问:
Is it possible to programmatically log in a user with Azure AD B2C?
I am contemplating switching to Azure AD B2C for Identity for our application. Currently we are just using ASP.NET Core local username/passwords.

My application has a simulation mode that is used for training purposes. During a simulation, we login a user as if they were logged in by themselves. The application allows the user to be logged in on more than one device. When the user is logged on a device during a simulation, they can observe in real time their activity while the simulation user works. We achieved this by having an alternate login mechanism that allowed the exchange of a secret and IP address filter to ensure that simulator logins are only allowed from simulator server machines on our network.

I'm trying to figure out how to do something similar with Azure AD B2C. I will never have the user credentials. I need an alternate means of granting user access to the system. Is this something possible?

答:
I believe you can create service principals instead of users for which you can grant permissions to access your application.

In your simulation, instead of performing the normal user login, you could perform a client credential flow and use that token for all authenticated requests.


问:
To Fetch Row data fully from FirebaseRealtime-database by checking the product id (child id) with android app scan result id
my app is with barcode scanner and i have created Firebase Realtime-database for the app. i entered some data to database. i want to fetch all the data(name,details,price) in a row by checking the scanresult to the id(in a specific row) in the database. found some tutorials similar to query but i couldn't set code as i wish. please, anyone help me to do this small correction for me ?

below i mentioned my present working code. but it is checking the scanresult with the row unique id and fetched as i want to do. but it is difficult to enter the data with same UID as same as scanresult. This code is working only when i dynamically add data directly to database in site.

The first pic is, of working present code:

the secong pic is to be fetch by checking its id :

```<code>@Override
public void handleResult(Result result) {
    final String scanResult = result.getText().toString();
    setContentView(R.layout.activity_second);

    databasefetch = FirebaseDatabase.getInstance().getReference().child("save").child(scanResult);
    databasefetch.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            TextView text = (TextView) findViewById(R.id.textView3);
            String name = dataSnapshot.child("name").getValue().toString();
            String details = dataSnapshot.child("details").getValue().toString();
            String price = dataSnapshot.child("price").getValue().toString();

            text.setText("\nProduct Name : "+name+"\nDetails : "+details+"\nPrice : "+price);

            //text to speech
            String  toSpeak=text.getText().toString();
            //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
            txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
</code>```

答:
To get the data from the second JSON snippet based on its id property, you need to run a query:

```<code>databasefetch = FirebaseDatabase.getInstance().getReference().child("save");
Query query = databasefetch.orderByChild("id").equalTo(8901058862836L);
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
      for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
        TextView text = (TextView) findViewById(R.id.textView3);
        String name = snapshot.child("name").getValue(String.class);
        String details = snapshot.child("details").getValue(String.class);
        String price = snapshot.child("price").getValue(String.class);

        ...
      }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); // never ignore errors
    }
})
</code>```

Body:
my app is with barcode scanner and i have created Firebase Realtime-database for the app. i entered some data to database. i want to fetch all the data(name,details,price) in a row by checking the scanresult to the id(in a specific row) in the database. found some tutorials similar to query but i couldn't set code as i wish. please, anyone help me to do this small correction for me ?

below i mentioned my present working code. but it is checking the scanresult with the row unique id and fetched as i want to do. but it is difficult to enter the data with same UID as same as scanresult. This code is working only when i dynamically add data directly to database in site.

The first pic is, of working present code:

the secong pic is to be fetch by checking its id :

@Override
public void handleResult(Result result) {
    final String scanResult = result.getText().toString();
    setContentView(R.layout.activity_second);

    databasefetch = FirebaseDatabase.getInstance().getReference().child("save").child(scanResult);
    databasefetch.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            TextView text = (TextView) findViewById(R.id.textView3);
            String name = dataSnapshot.child("name").getValue().toString();
            String details = dataSnapshot.child("details").getValue().toString();
            String price = dataSnapshot.child("price").getValue().toString();

            text.setText("\nProduct Name : "+name+"\nDetails : "+details+"\nPrice : "+price);

            //text to speech
            String  toSpeak=text.getText().toString();
            //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
            txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Body:
To get the data from the second JSON snippet based on its id property, you need to run a query:

databasefetch = FirebaseDatabase.getInstance().getReference().child("save");
Query query = databasefetch.orderByChild("id").equalTo(8901058862836L);
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
      for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
        TextView text = (TextView) findViewById(R.id.textView3);
        String name = snapshot.child("name").getValue(String.class);
        String details = snapshot.child("details").getValue(String.class);
        String price = snapshot.child("price").getValue(String.class);

        ...
      }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); // never ignore errors
    }
})


问:
Get all dates greater than current date in SSRS
I have two parameters in my Report - Begin and End Dates which are of Date/Time type. When I select the Begin Date from the Calendar, how do I automatically show dates equal to or greater than Begin Date for the End Date calendar? I would like the have the user the ability to select only End dates after Begin date.</p>

答:
This could be a potential workaround going off the comment I made to your question. You would need three datetime parameters:

-#1 StartDate

-#2 EndDate

-#3 EndDate2 - make this hidden

The StartDate and EndDate (#1 and #2) are for users to select. For the report, we will use  StartDate (#1) and EndDate2 (#3) to filter.

You can set the default for StartDate/EndDate however you would like. For EndDate2, if the user selects a date prior to the start date, default the end date that gets passed to the report. We set this by adjusting the default value for EndDate2 parameter with the IIF function to compare the user input dates.

Add this to default value for EndDate2 parameter:

```<code>=IIF(Parameters!EndDate.Value < Parameters!StartDate.Value, Parameters!StartDate.Value, Parameters!EndDate.Value )
</code>```

Body:
This could be a potential workaround going off the comment I made to your question. You would need three datetime parameters:

-#1 StartDate

-#2 EndDate

-#3 EndDate2 - make this hidden

The StartDate and EndDate (#1 and #2) are for users to select. For the report, we will use  StartDate (#1) and EndDate2 (#3) to filter.

You can set the default for StartDate/EndDate however you would like. For EndDate2, if the user selects a date prior to the start date, default the end date that gets passed to the report. We set this by adjusting the default value for EndDate2 parameter with the IIF function to compare the user input dates.

Add this to default value for EndDate2 parameter:

=IIF(Parameters!EndDate.Value < Parameters!StartDate.Value, Parameters!StartDate.Value, Parameters!EndDate.Value )


问:
VBA Excel save .xlsx file with the flexible name
I would like to save my file with the flexible name, which will change as the cell value changes.

The one answer is here:

Save a file with a name that corresponds to a cell value

however, I want also some fixed part of the name, which won't change unlike the part described in the query above.

Basing on this solution I tried to write something as follows:

```<code>Sub Save ()
Dim name As String, Custom_Name As String

name = Range("A2").Value
Custom_Name = "NBU" & name & "- Opportunity list.xlsx"
ActiveWorkbook.SaveAs Filename:=Custom_Name
</code>```

In the effect, I am getting an error:

This extension cannot be used with the selected file type. Change the file extension in the File name text box or select a different type file by changing the Save as type.

I would like to have this file in the .xlsx extension.

Excel VBA - save as with .xlsx extension

The answer above doesn't really match to my situation.
It will be vital to remove all form control buttons in the newly saved file, when possible.

Thanks & Regards,

```<code>End Sub
</code>```

答:
There is no action in the routine listed to save the file. It just simply takes the contents of a cell and creates a string with wrapped values.

I am not totally sure of what your goal is, but you need to add the action from the second link you provided. Workbook.SaveAs Method.

See the code below for a working example that I created to test.

```<code>Public Sub Save()
    Dim name As String, Custom_Name As String

    name = Range("A2").Value
    Custom_Name = ThisWorkbook.Path & "\" & "NBU" & name & " - Opportunity list.xlsx"

    'Disable alert when saving
    Application.DisplayAlerts = False

    'Save the workbook.
    ActiveWorkbook.SaveAs Filename:=Custom_Name, FileFormat:=51

End Sub
</code>```

You should note that after this code has executed, you will now be in the newly created file. This is not an export.

Test this and let me know if you have any questions. There are a few things that seem to be unnecessary in your code, but we can address those if you find this answers your first issue.

Edit:

I would also call out specifically then worksheet with the range as well.

name = Worksheets("Sheet1").Range("A2")

Body:
I would like to save my file with the flexible name, which will change as the cell value changes.

The one answer is here:

Save a file with a name that corresponds to a cell value

however, I want also some fixed part of the name, which won't change unlike the part described in the query above.

Basing on this solution I tried to write something as follows:

Sub Save ()
Dim name As String, Custom_Name As String

name = Range("A2").Value
Custom_Name = "NBU" & name & "- Opportunity list.xlsx"
ActiveWorkbook.SaveAs Filename:=Custom_Name

In the effect, I am getting an error:

This extension cannot be used with the selected file type. Change the file extension in the File name text box or select a different type file by changing the Save as type.

I would like to have this file in the .xlsx extension.

Excel VBA - save as with .xlsx extension

The answer above doesn't really match to my situation.
It will be vital to remove all form control buttons in the newly saved file, when possible.

Thanks & Regards,

End Sub

Body:
There is no action in the routine listed to save the file. It just simply takes the contents of a cell and creates a string with wrapped values.

I am not totally sure of what your goal is, but you need to add the action from the second link you provided. Workbook.SaveAs Method.

See the code below for a working example that I created to test.

Public Sub Save()
    Dim name As String, Custom_Name As String

    name = Range("A2").Value
    Custom_Name = ThisWorkbook.Path & "\" & "NBU" & name & " - Opportunity list.xlsx"

    'Disable alert when saving
    Application.DisplayAlerts = False

    'Save the workbook.
    ActiveWorkbook.SaveAs Filename:=Custom_Name, FileFormat:=51

End Sub

You should note that after this code has executed, you will now be in the newly created file. This is not an export.

Test this and let me know if you have any questions. There are a few things that seem to be unnecessary in your code, but we can address those if you find this answers your first issue.

Edit:

I would also call out specifically then worksheet with the range as well.

name = Worksheets("Sheet1").Range("A2")


问:
Capture Python's shell command within the own script
Launching a hypothetical Python script with several arguments (with argparse) from the shell, let's say, python my_script.py --foo 7.4 --bar whatever, I want to capture this shell command from the own script and put it in a string variable.

Of course, I could save those arguments just after doing args = parser.parse_args() by converting that object into a dictionary: args_dict = vars(args). But I don't want that. What I want is to get the whole shell command python my_script.py --foo 7.4 --bar whatever as a string.

Is that possible? If not, could I still get the shell command and put it as a part of the output when saving it in a file by doing python my_script.py --foo 7.4 --bar whatever >> my_output.txt?

答:
It's not perfectly accurate, but you can infer it like this:

import sys

print ("%s %s" % (sys.executable, " ".join(sys.argv) ) )
```

<pre class="lang-sh prettyprint-override"><code>❯ python3 test.py --foo 7.4 --bar=whatever
/usr/bin/python3 test.py --foo 7.4 --bar=whatever
</code>```

This will not catch pipes and the likes, only the command invoking python:

❯ python3 test.py | cat
/usr/bin/python3 test.py
```

Body:
It's not perfectly accurate, but you can infer it like this:

import sys

print ("%s %s" % (sys.executable, " ".join(sys.argv) ) )

❯ python3 test.py --foo 7.4 --bar=whatever
/usr/bin/python3 test.py --foo 7.4 --bar=whatever

This will not catch pipes and the likes, only the command invoking python:

❯ python3 test.py | cat
/usr/bin/python3 test.py