问:
Filter array using multiple keys
I'm trying to render grid with multiple toggling filters. I'm Using react hooks.

This is data array:

```<code>const items = [
    {
        name: 'hotel1',
        type: 'hotel'
    },
    {
        name: 'bar1',
        type: 'bar'
    },{
        name: 'entertainment1',
         type: 'entertainment'
    },{
        name: 'equipment1',
        type: 'equipment'
    },
    {
        name: 'shop1',
        type: 'shop'
    }
]

    const initialFilters = [
        {
            id: 1,
            active: false,
            type: 'bar'
        },
        {
            id: 2,
            active: false,
            type: 'shop'
        },
        {
            id: 3,
            active: false,
            type: 'hotel'
        },
        {
            id: 4,
            active: false,
            type: 'entertainment'
        },
        {
            id: 5,
            active: false,
            type: 'equipment'
        },
    ];

const [data, setData] = useState(items);
const [filterItems, setFilteredItems] = useState(initialFilters);

</code>```

currently I'm filtering with single key that is passed

```<code>const mainFilter = (key) => {
 setData(items.filter(x => x.type === key));
}
</code>```

and filter buttons with grid item names are rendered:

```<code>return (
    <div>
        <ul>
            {filterItems.map(x =>
                <li key={x.type}><a
                    className={x.active == true ? 'active' : ''}
                    onClick={() => mainFilter(x.type)}>
                    {x.type}
                </a></li>
            )}
        </ul>
     <div>{data.map(item => <div>{item.name}</div>}</div>
    </div>
)
</code>```

I need to get the functionality where when pressed for example shop filter, it should only leave items with type shop. if you press bar filter, it should only leave items with bar an shop and it should work all the way to all 5 filters.
if none are selected, it should show full array.

I've tried converting logic from this:

https://gist.github.com/jherax/f11d669ba286f21b7a2dcff69621eb72#file-filterplainarray-js

but no luck yet

答:
You can use the function every for checking if all flags have value false

This code snippet, have an initialFilter with all the flags equal to false

const items = [{name: 'hotel1',type: 'hotel'},{name: 'bar1',type: 'bar'}, {name: 'entertainment1',type: 'entertainment'}, {name: 'equipment1',type: 'equipment'},{name: 'shop1',type: 'shop'}];
const initialFilters = [{id: 1,active: false,type: 'bar'},{id: 2,active: false,type: 'shop'},{id: 3,active: false,type: 'hotel'},{id: 4,active: false,type: 'entertainment'},{id: 5,active: false,type: 'equipment'}];

let allFalse = initialFilters.every(({active}) => !active);
if (allFalse) console.log(items);```
</div>
</div>
</p>

<p>Otherwise, you can use the function <code>filter</code> along with the function <code>some</code>:</p>

<p><em>This code snippet has as active <code>shop</code> and <code>entertainment</code></em></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const items = [{name: 'hotel1',type: 'hotel'},{name: 'bar1',type: 'bar'}, {name: 'entertainment1',type: 'entertainment'}, {name: 'equipment1',type: 'equipment'},{name: 'shop1',type: 'shop'}];
const initialFilters = [{id: 1,active: false,type: 'bar'},{id: 2,active: true,type: 'shop'},{id: 3,active: false,type: 'hotel'},{id: 4,active: true,type: 'entertainment'},{id: 5,active: false,type: 'equipment'}];

let fltered = items.filter(({type}) => initialFilters.some(({type: t, active}) => t === type && active));
console.log(fltered);</code>```

Title: Filter array using multiple keys

Body:
I'm trying to render grid with multiple toggling filters. I'm Using react hooks.

This is data array:

const items = [
    {
        name: 'hotel1',
        type: 'hotel'
    },
    {
        name: 'bar1',
        type: 'bar'
    },{
        name: 'entertainment1',
         type: 'entertainment'
    },{
        name: 'equipment1',
        type: 'equipment'
    },
    {
        name: 'shop1',
        type: 'shop'
    }
]

    const initialFilters = [
        {
            id: 1,
            active: false,
            type: 'bar'
        },
        {
            id: 2,
            active: false,
            type: 'shop'
        },
        {
            id: 3,
            active: false,
            type: 'hotel'
        },
        {
            id: 4,
            active: false,
            type: 'entertainment'
        },
        {
            id: 5,
            active: false,
            type: 'equipment'
        },
    ];

const [data, setData] = useState(items);
const [filterItems, setFilteredItems] = useState(initialFilters);

currently I'm filtering with single key that is passed

const mainFilter = (key) => {
 setData(items.filter(x => x.type === key));
}

and filter buttons with grid item names are rendered:

return (

            {filterItems.map(x =>

 mainFilter(x.type)}>
                    {x.type}

            )}

{data.map(item =>
{item.name}
}

)

I need to get the functionality where when pressed for example shop filter, it should only leave items with type shop. if you press bar filter, it should only leave items with bar an shop and it should work all the way to all 5 filters.
if none are selected, it should show full array.

I've tried converting logic from this:

https://gist.github.com/jherax/f11d669ba286f21b7a2dcff69621eb72#file-filterplainarray-js

but no luck yet

Body:
You can use the function every for checking if all flags have value false

This code snippet, have an initialFilter with all the flags equal to false

const items = [{name: 'hotel1',type: 'hotel'},{name: 'bar1',type: 'bar'}, {name: 'entertainment1',type: 'entertainment'}, {name: 'equipment1',type: 'equipment'},{name: 'shop1',type: 'shop'}];
const initialFilters = [{id: 1,active: false,type: 'bar'},{id: 2,active: false,type: 'shop'},{id: 3,active: false,type: 'hotel'},{id: 4,active: false,type: 'entertainment'},{id: 5,active: false,type: 'equipment'}];

let allFalse = initialFilters.every(({active}) => !active);
if (allFalse) console.log(items);

Otherwise, you can use the function filter along with the function some:

This code snippet has as active shop and entertainment

const items = [{name: 'hotel1',type: 'hotel'},{name: 'bar1',type: 'bar'}, {name: 'entertainment1',type: 'entertainment'}, {name: 'equipment1',type: 'equipment'},{name: 'shop1',type: 'shop'}];
const initialFilters = [{id: 1,active: false,type: 'bar'},{id: 2,active: true,type: 'shop'},{id: 3,active: false,type: 'hotel'},{id: 4,active: true,type: 'entertainment'},{id: 5,active: false,type: 'equipment'}];

let fltered = items.filter(({type}) => initialFilters.some(({type: t, active}) => t === type && active));
console.log(fltered);


来源: stackexchange

问:
Issue with script to delete the files with particular extension
I have written the following script to delete the files with a particular extension.However, this script delete the file with the extension '.log' or '.txt' or '.css'.

What if the file extension is '.log000123' or '.log1234', so here extension is constant but random numbers are added after the extension. What can be done to delete such files as well through this script?

Any modification in the script or link to any website where such example is covered will be appreciated.

```<code>import os, time, sys

folder_path = "C:\SampleFolder"
file_ends_with = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path
</code>```

答:
This should work:</p>

```<code>import os, time, sys

folder_path = "C:\SampleFolder"
file_contains = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file_contains in file_full_path:
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written the following script to delete the files with a particular extension.However, this script delete the file with the extension '.log' or '.txt' or '.css'.

What if the file extension is '.log000123' or '.log1234', so here extension is constant but random numbers are added after the extension. What can be done to delete such files as well through this script?

Any modification in the script or link to any website where such example is covered will be appreciated.

import os, time, sys

folder_path = "C:\SampleFolder"
file_ends_with = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path

Body:
This should work:

import os, time, sys

folder_path = "C:\SampleFolder"
file_contains = ".log"
how_many_days_old_logs_to_remove = 7

now = time.time()
only_files = []

for file in os.listdir(folder_path):
    file_full_path = os.path.join(folder_path,file)
    if os.path.isfile(file_full_path) and file_contains in file_full_path:
        #Delete files older than x days
        if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
             os.remove(file_full_path)
             print "\n File Removed : " , file_full_path


问:
The entity type <type> is not part of the model for the current context
I am getting into the Entity Framework, but I am unsure if I am missing a critical point in the code-first approach.

I am using a generic repository pattern based on the code from https://genericunitofworkandrepositories.codeplex.com/ and have created my entities.

But when I try to access or modify the entity I run into the following:

System.InvalidOperationException: The entity type Estate is not part
  of the model for the current context.

It happens when I am trying to access it from my repository:

```<code>public virtual void Insert(TEntity entity)
{
    ((IObjectState)entity).ObjectState = ObjectState.Added;
    _dbSet.Attach(entity); // <-- The error occurs here
    _context.SyncObjectState(entity);
}
</code>```

The database (./SQLEXPRESS) is created just fine, but the entities (tables) is just not created on startup.

I am wondering if I need to explicit set the mapping of the entities? Is EF not able to this by its own?

My Entity is:

```<code>public class Estate : EntityBase
{
    public int EstateId { get; set; }
    public string Name { get; set; }
}
</code>```

My context is as so:

```<code>public partial class DimensionWebDbContext : DbContextBase // DbContextBase inherits DbContext
{
    public DimensionWebDbContext() :
        base("DimensionWebContext")
    {
        Database.SetInitializer<DimensionWebDbContext>(new CreateDatabaseIfNotExists<DimensionWebDbContext>());
        Configuration.ProxyCreationEnabled = false;
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

}
</code>```

Is there any specific reason why this error occurs? I have tried enable migrations and enable automatic migrations without any help either.

答:
I was facing the same issue with EntityFrameworkCore trying to update a range of values.

This approach did not work

```<code>  _dbSet.AttachRange(entity);
  _context.Entry(entity).State = EntityState.Modified;
   await _context.SaveChangesAsync().ConfigureAwait(false);
</code>```

After adding UpdateRange method and removing attach and entry everything work

```<code>  _dbSet.UpdateRange(entity);
  await _context.SaveChangesAsync().ConfigureAwait(false);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting into the Entity Framework, but I am unsure if I am missing a critical point in the code-first approach.

I am using a generic repository pattern based on the code from https://genericunitofworkandrepositories.codeplex.com/ and have created my entities.

But when I try to access or modify the entity I run into the following:

System.InvalidOperationException: The entity type Estate is not part
  of the model for the current context.

It happens when I am trying to access it from my repository:

public virtual void Insert(TEntity entity)
{
    ((IObjectState)entity).ObjectState = ObjectState.Added;
    _dbSet.Attach(entity); // <-- The error occurs here
    _context.SyncObjectState(entity);
}

The database (./SQLEXPRESS) is created just fine, but the entities (tables) is just not created on startup.

I am wondering if I need to explicit set the mapping of the entities? Is EF not able to this by its own?

My Entity is:

public class Estate : EntityBase
{
    public int EstateId { get; set; }
    public string Name { get; set; }
}

My context is as so:

public partial class DimensionWebDbContext : DbContextBase // DbContextBase inherits DbContext
{
    public DimensionWebDbContext() :
        base("DimensionWebContext")
    {
        Database.SetInitializer<DimensionWebDbContext>(new CreateDatabaseIfNotExists<DimensionWebDbContext>());
        Configuration.ProxyCreationEnabled = false;
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

}

Is there any specific reason why this error occurs? I have tried enable migrations and enable automatic migrations without any help either.

Body:
I was facing the same issue with EntityFrameworkCore trying to update a range of values.

This approach did not work

  _dbSet.AttachRange(entity);
  _context.Entry(entity).State = EntityState.Modified;
   await _context.SaveChangesAsync().ConfigureAwait(false);

After adding UpdateRange method and removing attach and entry everything work

  _dbSet.UpdateRange(entity);
  await _context.SaveChangesAsync().ConfigureAwait(false);


问:
How to setup a lot of domain names in one row?
I am working on a blog factory and we let the final user to use a fully customized domain name like www.myawsomeblog.com. There is a lot of people using this feature, so we cannot do a per case treatments.

How we can tag our pages in a way that we can track traffic for each domains without pain? Even if, the traffic statistics is a little mess is not a big deal as soon as there is a way to see which domain have which traffic.

Thanks !

答:
Ideally you would want a profile for each site, but you would have to manually set each new one up.  But it sounds like you want to avoid that...

The easiest but least flexible way to do it would be to pop your _trackPageview with the full URL so it shows the subdomain instead of just path, in pages reports.  But that puts all of your sites into a single profile, and there's no easy automated way to segment them (you can, but it's manual, esp since you have arbitrary domains popping up).

Alternatively if you don't wanna mess with having to change existing code, you can setup a domain prefix filter for your profile, to rewrite the page name to have domain prefix.. but that still gives you same problem as above. You can filter your reports to see
the different domains, but they won't be in aggregated buckets.  You will have to basically export to excel and do some manual grouping/filtering there, would be easiest.


问:
Azure App Service with ARR Reading Client IP from Web API
I have an ASP.Net Web API application hosted in Azure’s App Service scaled out using their auto scale/ARR. To read the client’s IP do I need to be looking at  X-FORWARDED-FOR or can it be read as though there was no load balancer, like here: https://stackoverflow.com/a/22532924

Can’t seem to find docs on how it works.

答:
I can just give you my test result.

I create a web app and manually set it to 2 instances.

My code:

```<code>public string GetIP()
{
    string HTTP_X_FORWARDED_FOR = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    string REMOTE_ADDR = Request.ServerVariables["REMOTE_ADDR"];
    string UserHostAddress = Request.UserHostAddress;
    string WEBSITE_INSTANCE_ID = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID");
    return Newtonsoft.Json.JsonConvert.SerializeObject(new { HTTP_X_FORWARDED_FOR = HTTP_X_FORWARDED_FOR, REMOTE_ADDR = REMOTE_ADDR, UserHostAddress = UserHostAddress, WEBSITE_INSTANCE_ID = WEBSITE_INSTANCE_ID });
}
</code>```

Result:

```<code>// First request from 13.70.19.163
{"HTTP_X_FORWARDED_FOR":"13.70.19.163:50331","REMOTE_ADDR":"13.70.19.163","UserHostAddress":"13.70.19.163","WEBSITE_INSTANCE_ID":"2b4ef85523c8628779b336b1ae7771fb0c5e289014ef47912d911dceb47ba032"}

// Second request from 65.52.178.194
{"HTTP_X_FORWARDED_FOR":"65.52.178.194:31190","REMOTE_ADDR":"65.52.178.194","UserHostAddress":"65.52.178.194","WEBSITE_INSTANCE_ID":"2b4ef85523c8628779b336b1ae7771fb0c5e289014ef47912d911dceb47ba032"}

// Another request from 223.67.26.144. This request is redirected to a different instance
{"HTTP_X_FORWARDED_FOR":"223.67.26.144:2732","REMOTE_ADDR":"223.67.26.144","UserHostAddress":"223.67.26.144","WEBSITE_INSTANCE_ID":"76deb6ae830639a9e41a93b4cc30ee9961483023510e33e97582dc1e2ac11a99"}

</code>```

Conclusion:

Request.ServerVariables["HTTP_X_FORWARDED_FOR"], REMOTE_ADDR and UserHostAddress all can get correct client IP.

Body:
I can just give you my test result.

I create a web app and manually set it to 2 instances.

My code:

public string GetIP()
{
    string HTTP_X_FORWARDED_FOR = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    string REMOTE_ADDR = Request.ServerVariables["REMOTE_ADDR"];
    string UserHostAddress = Request.UserHostAddress;
    string WEBSITE_INSTANCE_ID = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID");
    return Newtonsoft.Json.JsonConvert.SerializeObject(new { HTTP_X_FORWARDED_FOR = HTTP_X_FORWARDED_FOR, REMOTE_ADDR = REMOTE_ADDR, UserHostAddress = UserHostAddress, WEBSITE_INSTANCE_ID = WEBSITE_INSTANCE_ID });
}

Result:

// First request from 13.70.19.163
{"HTTP_X_FORWARDED_FOR":"13.70.19.163:50331","REMOTE_ADDR":"13.70.19.163","UserHostAddress":"13.70.19.163","WEBSITE_INSTANCE_ID":"2b4ef85523c8628779b336b1ae7771fb0c5e289014ef47912d911dceb47ba032"}

// Second request from 65.52.178.194
{"HTTP_X_FORWARDED_FOR":"65.52.178.194:31190","REMOTE_ADDR":"65.52.178.194","UserHostAddress":"65.52.178.194","WEBSITE_INSTANCE_ID":"2b4ef85523c8628779b336b1ae7771fb0c5e289014ef47912d911dceb47ba032"}

// Another request from 223.67.26.144. This request is redirected to a different instance
{"HTTP_X_FORWARDED_FOR":"223.67.26.144:2732","REMOTE_ADDR":"223.67.26.144","UserHostAddress":"223.67.26.144","WEBSITE_INSTANCE_ID":"76deb6ae830639a9e41a93b4cc30ee9961483023510e33e97582dc1e2ac11a99"}

Conclusion:

Request.ServerVariables["HTTP_X_FORWARDED_FOR"], REMOTE_ADDR and UserHostAddress all can get correct client IP.


问:
While Loop Function after a button is pressed and stop looping when another button is pressed C#
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

```<code>private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }
</code>```

While for my button2 code:

```<code>private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}
</code>```

Thank you!

答:
You can create a bool variable and make the loop while your variable is true.

So set the variable to true, when button1 is clicked.

Then your while would look like this:

```<code>while(myBoolVariable)
</code>```

And when button2 is clicked you can change the value to false and the while will stop.

Body:
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }

While for my button2 code:

private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}

Thank you!

Body:
You can create a bool variable and make the loop while your variable is true.

So set the variable to true, when button1 is clicked.

Then your while would look like this:

while(myBoolVariable)

And when button2 is clicked you can change the value to false and the while will stop.


问:
How can I tell if I'm running on x64?
I just got a bug report for an issue that only occurs when the program is running "on a 64-bit machine."  Now, Delphi doesn't produce 64-bit code, so theoretically that shouldn't matter, but apparently it does in this case.  I think I have a workaround, but it will break things on 32-bit Windows, so I need some way to tell:

If I'm running on a x64 or an x86 processor and

If I'm running under a 64-bit version of Windows under Win32 emulation or native Win32 on a 32-bit OS.

Does anyone know how I can get those answers from within my app?

答:
At the beginning of the first function you need to add</p>

```<code>if SizeOf(Pointer)=8 then
  Exit(True); // Current app is 64 bit
</code>```

ContentLicense: CC BY-SA 2.5

Title: How can I tell if I'm running on x64?

Body:
At the beginning of the first function you need to add

if SizeOf(Pointer)=8 then
  Exit(True); // Current app is 64 bit


答:
You can just do,</p>

```<code>lapply(your_list, function(i) your_df[i])
</code>```

Title: Split a data frame by column using a list of vectors

Body:
I want to split this data frame df by column using a list of vectors ind as the column indices.

> df
    1  2  3  4  5  6  7  8  9  10
1   1 11 21 31 41 51 61 71 81  91
2   2 12 22 32 42 52 62 72 82  92
3   3 13 23 33 43 53 63 73 83  93
4   4 14 24 34 44 54 64 74 84  94
5   5 15 25 35 45 55 65 75 85  95
6   6 16 26 36 46 56 66 76 86  96
7   7 17 27 37 47 57 67 77 87  97
8   8 18 28 38 48 58 68 78 88  98
9   9 19 29 39 49 59 69 79 89  99
10 10 20 30 40 50 60 70 80 90 100

The combined length of the vectors are equal to the number of columns in the data frame.

> ind
[[1]]
[1] 1 4 9

[[2]]
[1] 2 5 10 7 3

[[3]]
[1]  8 6

The desired result should look like this:

$`1`
    1  4  9
1   1 31 81
2   2 32 82
3   3 33 83
4   4 34 84
5   5 35 85
6   6 36 86
7   7 37 87
8   8 38 88
9   9 39 89
10 10 40 90

$`2`
    2  5  10  7  3
1  11 41  91 61 21
2  12 42  92 62 22
3  13 43  93 63 23
4  14 44  94 64 24
5  15 45  95 65 25
6  16 46  96 66 26
7  17 47  97 67 27
8  18 48  98 68 28
9  19 49  99 69 29
10 20 50 100 70 30

$`3`
    8  6
1  71 51
2  72 52
3  73 53
4  74 54
5  75 55
6  76 56
7  77 57
8  78 58
9  79 59
10 80 60

Effectively the code generates sub matrices as data frames from the data frame df based on the vectors in the list ind

I have tried using split.defult without achieving the desired result.

split.default(V, rep(seq_along(ind), lengths(ind)))

Body:
You can just do,

lapply(your_list, function(i) your_df[i])


问:
How to combine column data in excel
I am trying to combine column B from a total of 24 sheets into a master column using formula NOT VBA. Each column B could have up to 500 part numbers.
So this will give me a master column on a new worksheet of up to 12000 numbers. </p>

<p>Can anyone please help. </p>

答: Does the mentioned column B refers to same sheet in all files ??</p>

Title: How to combine column data in excel

Body:
I am trying to combine column B from a total of 24 sheets into a master column using formula NOT VBA. Each column B could have up to 500 part numbers.
So this will give me a master column on a new worksheet of up to 12000 numbers.

Can anyone please help.


问:
typesafe akka + java fibres
Java fibres will help to avoid threads to go into blocking when a blocking code is called.
Will Typesafe Akka get benefitted from this feature, as akka uses Future based approach which results in a lot of context switching.</p>

答: You might enjoy reading Will Project Loom obliterate Java Futures? which discusses Loom in the context of Java and Scala Futures.</p>

Title: typesafe akka + java fibres


问:
List of multiple class to run same function name C++
I have multiple classes with same function as below

```<code>class A
{
  void display()
  {
    // display something
  }
};

class B
{
  void display()
  {
    // display something two
  }
};
</code>```

I want to store difference class at a list or a vector and loop to call the same function with same name

```<code>int main()
{
  A * a;

  B * b;

  //list or vector to store object

  std::vector < Something that can store different class > listofclass;

  listofclass.emplace_back(a);

  listofclass.emplace_back(b);

  for (int i = 0; i < listofclass.size(); i++)

  {

    listofclass[i].display();

  }
}
</code>```

Is that possible to do like this?
Because there is separate classes, having different purpose, and now i try to group them together
Or there is other alternative way to achieve something like this

答:
A way to solve this problem is by using polymorphism. You make a superclass, which contains a pure virtual version of this function and let both A and B inherit from this class. By doing this, you can dynamic_cast any pointer of type A or B to a superclass type, on which you have defined the display function.

This will get you something like this

class C {
public:
    virtual void display() = 0;

    virtual ~C() = default;
};

class A : public C {
public:
    void display() override {
        std::cout << "A" << std::endl;
    };

    ~A() override = default;
};

class B : public C {
public:
    void display(){
        std::cout << "B" << std::endl;
    };

     ~B() override = default;
};
```

<p>So you can do:</p>

```C* c = new A();
// You can put the types of C* in the same list, and iterate over this list and do on each element
c->display();
delete c;
```

Body:
I have multiple classes with same function as below

class A
{
  void display()
  {
    // display something
  }
};

class B
{
  void display()
  {
    // display something two
  }
};

I want to store difference class at a list or a vector and loop to call the same function with same name

int main()
{
  A * a;

  B * b;

  //list or vector to store object

  std::vector < Something that can store different class > listofclass;

  listofclass.emplace_back(a);

  listofclass.emplace_back(b);

  for (int i = 0; i < listofclass.size(); i++)

  {

    listofclass[i].display();

  }
}

Is that possible to do like this?
Because there is separate classes, having different purpose, and now i try to group them together
Or there is other alternative way to achieve something like this

Body:
A way to solve this problem is by using polymorphism. You make a superclass, which contains a pure virtual version of this function and let both A and B inherit from this class. By doing this, you can dynamic_cast any pointer of type A or B to a superclass type, on which you have defined the display function.

This will get you something like this

class C {
public:
    virtual void display() = 0;

    virtual ~C() = default;
};

class A : public C {
public:
    void display() override {
        std::cout << "A" << std::endl;
    };

    ~A() override = default;
};

class B : public C {
public:
    void display(){
        std::cout << "B" << std::endl;
    };

     ~B() override = default;
};

So you can do:

C* c = new A();
// You can put the types of C* in the same list, and iterate over this list and do on each element
c->display();
delete c;


问:
Why is it giving me error of "Expected 2D array, got 1D array instead"
I used regressor.fit([X_train], [Y_train]), it did worked but when I ran the below code ,it gave me the following error "ValueError: shapes (1,9) and (21,21) not aligned: 9 (dim 1) != 21 (dim 0)"

Please help

答:
The problem is in the index chosen and the dimension. Change x to

X = dataset.iloc[:, :-1].values

OwnerDisplayName: Vivek Mahajan


问:
AssertionError: negative sum of square deviations
As part of a larger project, I am writing a function that takes in a dict of dicts of ints and returns a dict with each "outer" key linked to a tuple of the mean and standard deviation of that sub dictionary (i.e.  (mean(dict[key1]), stdev(dict[key1])) ). I am operating on a large dataset (the source file is a 2.8 GB csv file) and am getting an Assertion Error while calculating the standard deviation of one of the sub dicts.

While I will (and currently am) tracking down the sub dict that caused the error below, I'm curious about what general situation could cause it so I can try to avoid it if it happens further into my dataset.

The error message I receive is:

AssertionError: negative sum of square deviations: -3734262324235.697754

from the code:

```<code>import statistics as stat

try: #Check for single value error
    std = stat.stdev(val)
except stat.StatisticsError:
    std = 0
</code>```

答:
I encountered the same problem with very small numbers. The accurate computation of sum(x²) gave a result of zero (Fraction(0,1)) but the accurate computation of sum(x) gave a very small, positive fraction representing the rounding errors and losses of accuracy in the substractions of the mean from the data.

The code in statistics.py indicates that total2 should be zero, but it can actually be any small number, positive or negative. The square of total2 is always a small positive fraction.

```<code>def _ss(data, c=None):
    """Return sum of square deviations of sequence data.

    If ``c`` is None, the mean is calculated in one pass, and the deviations
    from the mean are calculated in a second pass. Otherwise, deviations are
    calculated from ``c`` as given. Use the second case with care, as it can
    lead to garbage results.
    """
    if c is None:
        c = mean(data)
    T, total, count = _sum((x-c)**2 for x in data)
    # The following sum should mathematically equal zero, but due to rounding
    # error may not.
    U, total2, count2 = _sum((x-c) for x in data)
    assert T == U and count == count2
    total -=  total2**2/len(data)
    assert not total < 0, 'negative sum of square deviations: %f' % total
    return (T, total)
</code>```

Therefore total, the variance, can become a negative value just before the failing assert.

The root cause is the loss of accuracy which takes place when each value is squared  in the first _sum function call. The float or np.float64 values are squared in the list comprehension by a floating point operation.

One possible way to correct, would be to cast total2 to type T before squaring it. It changes the semantics because _ss returns a value of type T instead of an exact fraction. Another, more accurate way, would be to convert x-c to Fractions once and for all before calling _sum for the first time. In both cases, the calculation would also run faster.

The most appropriate correction is not trivial because _sum also aggregates the type from successive calls to _coerce. Converting data to fractions earlier also changes the type of the result to Fraction.

Body:
As part of a larger project, I am writing a function that takes in a dict of dicts of ints and returns a dict with each "outer" key linked to a tuple of the mean and standard deviation of that sub dictionary (i.e.  (mean(dict[key1]), stdev(dict[key1])) ). I am operating on a large dataset (the source file is a 2.8 GB csv file) and am getting an Assertion Error while calculating the standard deviation of one of the sub dicts.

While I will (and currently am) tracking down the sub dict that caused the error below, I'm curious about what general situation could cause it so I can try to avoid it if it happens further into my dataset.

The error message I receive is:

AssertionError: negative sum of square deviations: -3734262324235.697754

from the code:

import statistics as stat

try: #Check for single value error
    std = stat.stdev(val)
except stat.StatisticsError:
    std = 0

Body:
I encountered the same problem with very small numbers. The accurate computation of sum(x²) gave a result of zero (Fraction(0,1)) but the accurate computation of sum(x) gave a very small, positive fraction representing the rounding errors and losses of accuracy in the substractions of the mean from the data.

The code in statistics.py indicates that total2 should be zero, but it can actually be any small number, positive or negative. The square of total2 is always a small positive fraction.

def _ss(data, c=None):
    """Return sum of square deviations of sequence data.

    If ``c`` is None, the mean is calculated in one pass, and the deviations
    from the mean are calculated in a second pass. Otherwise, deviations are
    calculated from ``c`` as given. Use the second case with care, as it can
    lead to garbage results.
    """
    if c is None:
        c = mean(data)
    T, total, count = _sum((x-c)**2 for x in data)
    # The following sum should mathematically equal zero, but due to rounding
    # error may not.
    U, total2, count2 = _sum((x-c) for x in data)
    assert T == U and count == count2
    total -=  total2**2/len(data)
    assert not total < 0, 'negative sum of square deviations: %f' % total
    return (T, total)

Therefore total, the variance, can become a negative value just before the failing assert.

The root cause is the loss of accuracy which takes place when each value is squared  in the first _sum function call. The float or np.float64 values are squared in the list comprehension by a floating point operation.

One possible way to correct, would be to cast total2 to type T before squaring it. It changes the semantics because _ss returns a value of type T instead of an exact fraction. Another, more accurate way, would be to convert x-c to Fractions once and for all before calling _sum for the first time. In both cases, the calculation would also run faster.

The most appropriate correction is not trivial because _sum also aggregates the type from successive calls to _coerce. Converting data to fractions earlier also changes the type of the result to Fraction.


问:
SSRS Report automatic page navigation/looping
I have created a SSRS report that has 7 pages that I would like to have loop from beginning to end and then refresh every few minutes. Is this possible? I have been searching, but cannot find anything on how to do it. I have SQL Server 2008.
Thank you!</p>

答: In SQL Server Reporting Services, we can set the report to refresh automatically based on a specific time interval. However, it is not supported to set the report to jump to the next page in a loop at the same time. I recommend you submit your suggestion to the Microsoft Connect at http://connect.microsoft.com/. Your feedback is valuable for Microsoft to improve products and increase the level of service provide</p>


问:
Getting strange error when reloading section index?
I am using the iPhone SDK and Objective-C and
I get this error message:

Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit/UIKit-984.38/UITableView.m:774
  2010-01-08 13:24:16.842 MyAPP[628:20b] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1.  The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).

Here is my code to expand sections:

```<code>- (void)checkAction:(id)sender
{
    //The button is added as subview on a view and the view is section header custom view
    UIButton *Button = (UIButton*)sender;
    NSLog(@"Button Tag=%d",Button.tag);
    if([[self.MySectionIndexArray objectAtIndex:Button.tag] isEqualToString:@"UP"])
    {
        [self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:@"DOWN"];
        [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Up.png"] forState:UIControlStateNormal];
        [TableDashBoard reloadSections:[NSIndexSet indexSetWithIndex:Button.tag] withRowAnimation:UITableViewRowAnimationFade];
    }
    else
    {
        [self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:@"UP"];
        [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Down.png"] forState:UIControlStateNormal];
    }
    NSLog(@"self.MySectionIndexArray ka title = %@ at index Number=%d",self.MySectionIndexArray,Button.tag);
}
</code>```

答:
I had a similar problem. I was sure of being updating the dataSource.

But finally I realized that I was actually modifying 2 sections but updating the dataSource for only one.

Body:
I am using the iPhone SDK and Objective-C and
I get this error message:

Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit/UIKit-984.38/UITableView.m:774
  2010-01-08 13:24:16.842 MyAPP[628:20b] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1.  The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).

Here is my code to expand sections:

- (void)checkAction:(id)sender
{
    //The button is added as subview on a view and the view is section header custom view
    UIButton *Button = (UIButton*)sender;
    NSLog(@"Button Tag=%d",Button.tag);
    if([[self.MySectionIndexArray objectAtIndex:Button.tag] isEqualToString:@"UP"])
    {
        [self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:@"DOWN"];
        [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Up.png"] forState:UIControlStateNormal];
        [TableDashBoard reloadSections:[NSIndexSet indexSetWithIndex:Button.tag] withRowAnimation:UITableViewRowAnimationFade];
    }
    else
    {
        [self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:@"UP"];
        [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Down.png"] forState:UIControlStateNormal];
    }
    NSLog(@"self.MySectionIndexArray ka title = %@ at index Number=%d",self.MySectionIndexArray,Button.tag);
}


问:
Program type already present: com.google.zxing.ChecksumException
I try using zxing library to scan a qrcode, there's no error until I run the app like this:

```<code>Program type already present: com.google.zxing.ChecksumException

Message{kind=ERROR, text=Program type already present: com.google.zxing.ChecksumException, sources=[Unknown source file], tool name=Optional.of(D8)}
</code>```

here's my gradle:

```<code>android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.std.scanner"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}
</code>```

i think i should using "exclude" in my gradle dependecies, but I don't know how to write the code. please help, thanks in advance.

答:
solve by  add in build.gradle (app)</p>
```<code>configurations {
    implementation.exclude group: 'com.google.zxing'
}
</code>```

Body:
I try using zxing library to scan a qrcode, there's no error until I run the app like this:

Program type already present: com.google.zxing.ChecksumException

Message{kind=ERROR, text=Program type already present: com.google.zxing.ChecksumException, sources=[Unknown source file], tool name=Optional.of(D8)}

here's my gradle:

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.std.scanner"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}

i think i should using "exclude" in my gradle dependecies, but I don't know how to write the code. please help, thanks in advance.

Body:
solve by  add in build.gradle (app)

configurations {
    implementation.exclude group: 'com.google.zxing'
}


问:
What is hidden surface problem and why does z buffer precision even matter?
As beginner to OpenGL (and computer graphics in general) I'm quite curious regarding the following questions:

I know what is Z buffer, it is a depth buffer which stores value ranging from 0 to 1. But why does its precision matter?

What is hidden surface problem?

What is the problem in using a linear Z buffer?

Why do we care about Z buffer precision?

答:
Z buffer precision

In GL the depth buffer was developed so the precision is visually not decreasing with distance ... meaning that if you render infinite plane that crosses both znear and zfar planes and use the stored depth as color you would see the plane rendered as parallel bars with the same visual width. Something like this:

This provides more or less the same visual detail along the whole scene. However when you start looking at the geometrical accuracy its non linear and from numerical stats you will see that most of the <0,1> range is very close to znear.

Once our computers was able to handle bigger and more detailed scenes this behavior started to be a problem as suddenly we wanted to see details in more distant places where the depth value increment is usually bigger than the whole rendered object itself ...

To remedy this we can use linear dept buffer (for scenes with large dynamic depth range or very big objects).

lets have 16 bit depth buffer that means 2^16 values without sign as we have sign than its just 2^15 = 32768 possible values.

Now for linear depth that means that depth accuracy (minimal increment/change/delta) is

```<code>dz = (zfar-znear)/2^(bits-1)
</code>```

for example let znear=0.1 and zfar=1000 then:

```<code>dz = (1000-0.1)/32768 = 0.03
</code>```

across whole scene. Now when we get back to non linear depth the dz is much smaller near znear but hugely bigger near zfar and using it as detail criteria is useless. Instead of that its better to comply this:

```<code>zfar/znear < 2^(bits-1)
</code>```

hidden surface removal

its a workaround to Painters algorithm where objects more distant to camera are overpaintade by objects closer. The painter's algorithm in graphics is called Z-sorting and it requires to render stuff in order. Depth buffering is a workaround where you store the depth value of already rendered stuff and render only if you are closer to camera. This eliminates the need of rendering in order while still achieve the same result.

However if dept precision is too low the rendering can not reliably tell what is closet and what not see this:

On the left the precision is good on the right its bad. As you can see the same geometry renders differently with wrong depth precision.

linear depth problems

Linear depth buffer is not GL native so you need to workaround the GL implementation a bit. Luckily with GLSL its really easy and cheap now without precission loss nor performance hits. For more info see the link above. However having linear depth means we got the same geometrical accuracy along whole scene. So for the same details we need more bits for depth buffer in case of close to znear objects. That is why linear depth buffer is more suited for scenes with high dynamic depth range where non linear depth buffers behave poorly. So scenes with big objects going from znear to zfar like terrains, big space ships, towns etc ...

Why to care about depth precision?

to avoid rendering artifacts like depth fitting / depth tearing, wrong geometry intersections, wrong advanced effects etc ...

You need to take in mind that depth buffer bitwidth is fairly limited. The usuall values are 16/24/32 but for ages only 16/24 where available on majority of HW. Only in recent years we can have 32 and on some cards even 64 but IIRC that is no longer native depth buffer and needs additional code to enable it...

There are also other methods than linear depth buffer to achieve High dynamic depth range of the scene see:

Is it possible to make realistic n-body solar system simulation in matter of size and mass?

Body:
Z buffer precision

In GL the depth buffer was developed so the precision is visually not decreasing with distance ... meaning that if you render infinite plane that crosses both znear and zfar planes and use the stored depth as color you would see the plane rendered as parallel bars with the same visual width. Something like this:

This provides more or less the same visual detail along the whole scene. However when you start looking at the geometrical accuracy its non linear and from numerical stats you will see that most of the <0,1> range is very close to znear.

Once our computers was able to handle bigger and more detailed scenes this behavior started to be a problem as suddenly we wanted to see details in more distant places where the depth value increment is usually bigger than the whole rendered object itself ...

To remedy this we can use linear dept buffer (for scenes with large dynamic depth range or very big objects).

lets have 16 bit depth buffer that means 2^16 values without sign as we have sign than its just 2^15 = 32768 possible values.

Now for linear depth that means that depth accuracy (minimal increment/change/delta) is

dz = (zfar-znear)/2^(bits-1)

for example let znear=0.1 and zfar=1000 then:

dz = (1000-0.1)/32768 = 0.03

across whole scene. Now when we get back to non linear depth the dz is much smaller near znear but hugely bigger near zfar and using it as detail criteria is useless. Instead of that its better to comply this:

zfar/znear < 2^(bits-1)

hidden surface removal

its a workaround to Painters algorithm where objects more distant to camera are overpaintade by objects closer. The painter's algorithm in graphics is called Z-sorting and it requires to render stuff in order. Depth buffering is a workaround where you store the depth value of already rendered stuff and render only if you are closer to camera. This eliminates the need of rendering in order while still achieve the same result.

However if dept precision is too low the rendering can not reliably tell what is closet and what not see this:

On the left the precision is good on the right its bad. As you can see the same geometry renders differently with wrong depth precision.

linear depth problems

Linear depth buffer is not GL native so you need to workaround the GL implementation a bit. Luckily with GLSL its really easy and cheap now without precission loss nor performance hits. For more info see the link above. However having linear depth means we got the same geometrical accuracy along whole scene. So for the same details we need more bits for depth buffer in case of close to znear objects. That is why linear depth buffer is more suited for scenes with high dynamic depth range where non linear depth buffers behave poorly. So scenes with big objects going from znear to zfar like terrains, big space ships, towns etc ...

Why to care about depth precision?

to avoid rendering artifacts like depth fitting / depth tearing, wrong geometry intersections, wrong advanced effects etc ...

You need to take in mind that depth buffer bitwidth is fairly limited. The usuall values are 16/24/32 but for ages only 16/24 where available on majority of HW. Only in recent years we can have 32 and on some cards even 64 but IIRC that is no longer native depth buffer and needs additional code to enable it...

There are also other methods than linear depth buffer to achieve High dynamic depth range of the scene see:

Is it possible to make realistic n-body solar system simulation in matter of size and mass?


问:
Generic XQuery to recursively traverse the XML
I am trying to convert the XML input given below to the output format using generic Xquery without calling any parent/child elements. If the parent has two or more recurring child then that should be grouped as an array.

XML:

```<code><root>
<name>xxx</name>
<id>1</id>
<tasks>
    <job>
        <id>1</id>
        <val>2</val>
    </job>
    <job>
        <id>2</id>
        <val>12</val>
    </job>
    <job>
        <id>3</id>
        <val>22</val>
    </job>
</tasks>
</root>
</code>```

Expected result:

```<code><map>
<string key="name">xxx</string>
<string key="id">1</string>
<array key="tasks">
    <map key="job">
        <string key="id">1</string>
        <string key="val">2</string>
    </map>
    <map key="job">
        <string key="id">2</string>
        <string key="val">12</string>
    </map>
    <map key="job">
        <string key="id">3</string>
        <string key="val">22</string>
    </map>
</array>
</map>
</code>```

XQuery I tried:

```<code>declare default element namespace "http://www.w3.org/2005/xpath-functions";
for $a in /*[1]
let $retval :=
<map>
    {
    for $z in $a//*
    return if ($z/*/text()) then
    (
    <map>
        {
        for $zz in $z/child::*
        return if ($zz/text()) then
        (
        <string key="{lower-case(name($zz))}">{data($zz)}</string>
        )
        else ()
        }</map>
    )
    else ()
    }
</map>
return $retval
</code>```

答:
Hi Please test attached code:

```<code>declare function local:testChild($in)
{
    if($in/text())
    then <string key="{local-name($in)}">{$in/node()}</string>
    else if(not($in/*/text()))
        then
   <array key="{local-name($in)}">{for $in in $in/*
                return local:testChild($in)
                }</array>

    else <map key="{local-name($in)}">{for $in in $in/*
                return local:testChild($in)
                }</map>

};

let $markup:=<root>
<name>xxx</name>
<id>1</id>
<tasks>
    <job>
        <id>1</id>
        <val>2</val>
    </job>
    <job>
        <id>2</id>
        <val>12</val>
    </job>
    <job>
        <id>3</id>
        <val>22</val>
    </job>
</tasks>
</root>

let $first:=<map>{for $in in  $markup/*
    return local:testChild($in)
}</map>
return $first
</code>```

See transformation at https://xqueryfiddle.liberty-development.net/94hwphU

Body:
I am trying to convert the XML input given below to the output format using generic Xquery without calling any parent/child elements. If the parent has two or more recurring child then that should be grouped as an array.

XML:

<root>
<name>xxx</name>
<id>1</id>
<tasks>
    <job>
        <id>1</id>
        <val>2</val>
    </job>
    <job>
        <id>2</id>
        <val>12</val>
    </job>
    <job>
        <id>3</id>
        <val>22</val>
    </job>
</tasks>
</root>

Expected result:

<map>
<string key="name">xxx</string>
<string key="id">1</string>
<array key="tasks">
    <map key="job">
        <string key="id">1</string>
        <string key="val">2</string>
    </map>
    <map key="job">
        <string key="id">2</string>
        <string key="val">12</string>
    </map>
    <map key="job">
        <string key="id">3</string>
        <string key="val">22</string>
    </map>
</array>
</map>

XQuery I tried:

declare default element namespace "http://www.w3.org/2005/xpath-functions";
for $a in /*[1]
let $retval :=
<map>
    {
    for $z in $a//*
    return if ($z/*/text()) then
    (
    <map>
        {
        for $zz in $z/child::*
        return if ($zz/text()) then
        (
        <string key="{lower-case(name($zz))}">{data($zz)}</string>
        )
        else ()
        }</map>
    )
    else ()
    }
</map>
return $retval

Body:
Hi Please test attached code:

declare function local:testChild($in)
{
    if($in/text())
    then <string key="{local-name($in)}">{$in/node()}</string>
    else if(not($in/*/text()))
        then
   <array key="{local-name($in)}">{for $in in $in/*
                return local:testChild($in)
                }</array>

    else <map key="{local-name($in)}">{for $in in $in/*
                return local:testChild($in)
                }</map>

};

let $markup:=<root>
<name>xxx</name>
<id>1</id>
<tasks>
    <job>
        <id>1</id>
        <val>2</val>
    </job>
    <job>
        <id>2</id>
        <val>12</val>
    </job>
    <job>
        <id>3</id>
        <val>22</val>
    </job>
</tasks>
</root>

let $first:=<map>{for $in in  $markup/*
    return local:testChild($in)
}</map>
return $first

See transformation at https://xqueryfiddle.liberty-development.net/94hwphU


问:
Numpy: Elegant solution to calculating output matrix of function with indefinite number of variables
I have been searching all weekend for a more elegant (read: no manual for-loop programming) solution to the following problem:

Lets assume we have a custom function f() with an indefinite number of inputs. For simplicity, let us start with two:

```<code>def f(x,y):
    return x + y
</code>```

Now I pass an array with the correct number of variables to this function:

```<code>x = np.array([x0, x1, x2, ..., xn])
y = np.array([y0, y1, y2, ..., yn])
</code>```

The answer I look for is:

```<code>z = np.array([[x0 + y0, x0 + y1, x0 + y2, ..., x0 + yn],
              [x1 + y0, x1 + y1, x1 + y2, ..., x1 + yn],
              [x2 + y0, x2 + y1, x2 + y2, ..., x2 + yn],
              ...])
</code>```

So, in summary, I am looking for a function, that I can pass another custom function to, which then calculates all possible combinations, without me having to program a ridiculous number of for-loops.

Please help me, hive mind!

Edit 1: the custom function may be of arbitrary complexity. From my real world problem, this is one example:

```<code>def f(x, y):
    return 1 - (x/2)**y*binom(y, y/2)
</code>```

Edit 2: the accepted answer works as intended. The answer of Dishin H Goyani linking to stackoverflow.com/a/32742943/6075699 produces the same result using a different path.

Thanks everyone! Stackoverflow rules!

答:
Mesh grid can help you create all the pairs, than just sum them. As a bonus it's extensible to more dimensions:

```<code>>>> y = np.arange(1,5)
>>> x = np.arange(6,10)
>>> x
array([6, 7, 8, 9])
>>> y
array([1, 2, 3, 4])
>>> sum(np.meshgrid(x,y))
array([[ 7,  8,  9, 10],
       [ 8,  9, 10, 11],
       [ 9, 10, 11, 12],
       [10, 11, 12, 13]])
</code>```

To put this in a function taking an unknown number of arrays:

```<code>def meshSum(*arrays):
    return sum(np.meshgrid(*arrays))
</code>```

An example with another array:

```<code>>>> z = np.arange(11,15)
>>> def meshSum(*arrays):
...     return sum(np.meshgrid(*arrays))
...
>>> meshSum(x,y,z)
array([[[18, 19, 20, 21],
        [19, 20, 21, 22],
        [20, 21, 22, 23],
        [21, 22, 23, 24]],

       [[19, 20, 21, 22],
        [20, 21, 22, 23],
        [21, 22, 23, 24],
        [22, 23, 24, 25]],

       [[20, 21, 22, 23],
        [21, 22, 23, 24],
        [22, 23, 24, 25],
        [23, 24, 25, 26]],

       [[21, 22, 23, 24],
        [22, 23, 24, 25],
        [23, 24, 25, 26],
        [24, 25, 26, 27]]])
</code>```

Following your edit, for an arbitrary operation on the mesh

```<code>def meshOperation(f, *arrays):
    return f((*np.meshgrid(*arrays))
</code>```

where f must take either a *args argument or a number of arguments equal to len(arrays), so meshOperation(f, x, y) is valid in your final example.

Body:
I have been searching all weekend for a more elegant (read: no manual for-loop programming) solution to the following problem:

Lets assume we have a custom function f() with an indefinite number of inputs. For simplicity, let us start with two:

def f(x,y):
    return x + y

Now I pass an array with the correct number of variables to this function:

x = np.array([x0, x1, x2, ..., xn])
y = np.array([y0, y1, y2, ..., yn])

The answer I look for is:

z = np.array([[x0 + y0, x0 + y1, x0 + y2, ..., x0 + yn],
              [x1 + y0, x1 + y1, x1 + y2, ..., x1 + yn],
              [x2 + y0, x2 + y1, x2 + y2, ..., x2 + yn],
              ...])

So, in summary, I am looking for a function, that I can pass another custom function to, which then calculates all possible combinations, without me having to program a ridiculous number of for-loops.

Please help me, hive mind!

Edit 1: the custom function may be of arbitrary complexity. From my real world problem, this is one example:

def f(x, y):
    return 1 - (x/2)**y*binom(y, y/2)

Edit 2: the accepted answer works as intended. The answer of Dishin H Goyani linking to stackoverflow.com/a/32742943/6075699 produces the same result using a different path.

Thanks everyone! Stackoverflow rules!

Body:
Mesh grid can help you create all the pairs, than just sum them. As a bonus it's extensible to more dimensions:

>>> y = np.arange(1,5)
>>> x = np.arange(6,10)
>>> x
array([6, 7, 8, 9])
>>> y
array([1, 2, 3, 4])
>>> sum(np.meshgrid(x,y))
array([[ 7,  8,  9, 10],
       [ 8,  9, 10, 11],
       [ 9, 10, 11, 12],
       [10, 11, 12, 13]])

To put this in a function taking an unknown number of arrays:

def meshSum(*arrays):
    return sum(np.meshgrid(*arrays))

An example with another array:

>>> z = np.arange(11,15)
>>> def meshSum(*arrays):
...     return sum(np.meshgrid(*arrays))
...
>>> meshSum(x,y,z)
array([[[18, 19, 20, 21],
        [19, 20, 21, 22],
        [20, 21, 22, 23],
        [21, 22, 23, 24]],

       [[19, 20, 21, 22],
        [20, 21, 22, 23],
        [21, 22, 23, 24],
        [22, 23, 24, 25]],

       [[20, 21, 22, 23],
        [21, 22, 23, 24],
        [22, 23, 24, 25],
        [23, 24, 25, 26]],

       [[21, 22, 23, 24],
        [22, 23, 24, 25],
        [23, 24, 25, 26],
        [24, 25, 26, 27]]])

Following your edit, for an arbitrary operation on the mesh

def meshOperation(f, *arrays):
    return f((*np.meshgrid(*arrays))

where f must take either a *args argument or a number of arguments equal to len(arrays), so meshOperation(f, x, y) is valid in your final example.


问:
How can I set that the function using the variable does not alter its content in current function?
My function getUser() does a databse select of user info. In this function, I call a another function called calcPercentage() which takes the received values from the database stored in $result, then removes some values(indexes) and do a calculation. Once complete, the second function returns a value to the first function.

My issue is that the values removed in calcPercentage(), the second function, are effecting the original values received from the database.

See code

```<code>function getUser()
{
  $result = DB::select();
// say $result = name, surname, email, telephone

  $percentage = $this->calcPercentage($result);

var_dump($result)
// now $result = name, surname
}

function calcPercentage($data)
{
 $u_data = $data;
 unset($u_data->email);
 unset($u_data->telephone);
 // the above values are not needed for the calculations,
 // thus they are being removed.

 ... do calculation
 return $percentage
 //$percentage would be = 100 || >100;
}

</code>```

I would like to remove the values from the object with out affecting the original variable in function getUser();
Expected outcome.

```<code>function getUser()
{
  $result = DB::select();
// say $result = name, surname, email, telephone

  $percentage = $this->calcPercentage($result);

var_dump($result)
// now $result = name, surname, email, telephone
}

</code>```

Should I rather do a another query here to the database?

答:
Before calling calcPercentage() method, clone your result object.

```<code>function getUser(){
    $result = DB::select();
    // say $result = name, surname, email, telephone

    $result_copy = clone $result;
    $percentage = $this->calcPercentage(result_copy);

    var_dump($result)
    // now $result= name, surname, email, telephone
}
</code>```

Body:
My function getUser() does a databse select of user info. In this function, I call a another function called calcPercentage() which takes the received values from the database stored in $result, then removes some values(indexes) and do a calculation. Once complete, the second function returns a value to the first function.

My issue is that the values removed in calcPercentage(), the second function, are effecting the original values received from the database.

See code

function getUser()
{
  $result = DB::select();
// say $result = name, surname, email, telephone

  $percentage = $this->calcPercentage($result);

var_dump($result)
// now $result = name, surname
}

function calcPercentage($data)
{
 $u_data = $data;
 unset($u_data->email);
 unset($u_data->telephone);
 // the above values are not needed for the calculations,
 // thus they are being removed.

 ... do calculation
 return $percentage
 //$percentage would be = 100 || >100;
}

I would like to remove the values from the object with out affecting the original variable in function getUser();
Expected outcome.

function getUser()
{
  $result = DB::select();
// say $result = name, surname, email, telephone

  $percentage = $this->calcPercentage($result);

var_dump($result)
// now $result = name, surname, email, telephone
}

Should I rather do a another query here to the database?

Body:
Before calling calcPercentage() method, clone your result object.

function getUser(){
    $result = DB::select();
    // say $result = name, surname, email, telephone

    $result_copy = clone $result;
    $percentage = $this->calcPercentage(result_copy);

    var_dump($result)
    // now $result= name, surname, email, telephone
}


问:
Change default TextFormField's icon color from grey to anything but show primary color on selection
I want to change default colour of icon of TextFormField, which will also get changes on selection. There are few way to change colour but non of them works for me.

1. Set icon color

When changing icon colour directly as below the icon colour will not change when selected, below is the code of the same and screenshot which shows red colour when field is selected or not selected.

```<code>     TextFormField(
        maxLength: 15,
        decoration: InputDecoration(
          labelText: "USER NAME",
          prefixIcon: IconTheme(data: IconThemeData(
            color: Colors.redAccent
          ), child: Icon(Icons.email,))
        ),
        onSaved: (username) => _username = username,
      ),
</code>```

2. Leave it default

This will show grey colour when field is not selected and primary colour when field is selected. Below is the screenshot of the same. Here i want to change the colour of icon from grey to red and want to show primary colour on selection.

NOTE:- It will be good if we can do this using theme

答:
If you want to change icon color at the time textFormField is selected,

change it according to below.

```<code>...
            Theme(
              child: Column(
                children: <Widget>[
                  TextFormField(
                    maxLength: 15,
                    decoration: InputDecoration(
                        labelText: "USER NAME",
                        prefixIcon: Icon(Icons.email,)
                    ),
                    onSaved: (username) => _username = username,
                  ),
                  TextFormField(
                    maxLength: 15,
                    decoration: InputDecoration(
                        labelText: "EMAIL",
                        prefixIcon: Icon(Icons.email,)
                    ),
                    onSaved: (usermail) => _useremail = usermail,
                  ),
                ],
              ),
              data: Theme.of(context)
                  .copyWith(primaryColor: Colors.redAccent,),
            ),
...
</code>```

Conclusion:

Wrap all the textFormFields widgets with Theme widget and set data field as the color you want as a highlighter.

Body:
I want to change default colour of icon of TextFormField, which will also get changes on selection. There are few way to change colour but non of them works for me.

1. Set icon color

When changing icon colour directly as below the icon colour will not change when selected, below is the code of the same and screenshot which shows red colour when field is selected or not selected.

     TextFormField(
        maxLength: 15,
        decoration: InputDecoration(
          labelText: "USER NAME",
          prefixIcon: IconTheme(data: IconThemeData(
            color: Colors.redAccent
          ), child: Icon(Icons.email,))
        ),
        onSaved: (username) => _username = username,
      ),

2. Leave it default

This will show grey colour when field is not selected and primary colour when field is selected. Below is the screenshot of the same. Here i want to change the colour of icon from grey to red and want to show primary colour on selection.

NOTE:- It will be good if we can do this using theme

Body:
If you want to change icon color at the time textFormField is selected,

change it according to below.

...
            Theme(
              child: Column(
                children: <Widget>[
                  TextFormField(
                    maxLength: 15,
                    decoration: InputDecoration(
                        labelText: "USER NAME",
                        prefixIcon: Icon(Icons.email,)
                    ),
                    onSaved: (username) => _username = username,
                  ),
                  TextFormField(
                    maxLength: 15,
                    decoration: InputDecoration(
                        labelText: "EMAIL",
                        prefixIcon: Icon(Icons.email,)
                    ),
                    onSaved: (usermail) => _useremail = usermail,
                  ),
                ],
              ),
              data: Theme.of(context)
                  .copyWith(primaryColor: Colors.redAccent,),
            ),
...

Conclusion:

Wrap all the textFormFields widgets with Theme widget and set data field as the color you want as a highlighter.


问:
How to specify AddressFilterMode.Any declaratively
There are lots of answers stating that AddressFilterMode.Any needs to be added as a code attribute when you can create an extension behavior for WCF that does the same thing.

How can you specify AddressFilterMode.Any programmatically

答:
If you want to specify it in code while creating a service host:

host.Description.Behaviors.Find<ServiceBehaviorAttribute>().AddressFilterMode = AddressFilterMode.Any;
```

<p>or</p>

<pre class="lang-cs prettyprint-override"><code>host.Description.Behaviors.Add(new ServiceBehaviorAttribute { AddressFilterMode = AddressFilterMode.Any });
</code>```

Depending on whether your service already has a ServiceBehaviorAttribute or not.

Body:
If you want to specify it in code while creating a service host:

host.Description.Behaviors.Find<ServiceBehaviorAttribute>().AddressFilterMode = AddressFilterMode.Any;

or

host.Description.Behaviors.Add(new ServiceBehaviorAttribute { AddressFilterMode = AddressFilterMode.Any });

Depending on whether your service already has a ServiceBehaviorAttribute or not.


问:
Overloading a function using templates
I am trying to define a function using templates and I want the typename to be either int or anEnum (a specific enum I had defined). I have tried the following but I have failed:

```<code>template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}
</code>```

What I am trying to do is to use templates, instead of defining two overloaded functions.
I'd prefer the function to be called as the following, without the programmer having to consider the type

```<code>isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)
</code>```

Basically, I want this function to be templated for int and aNum types. I have searched for this, but could not find the answer. What may I be missing? Thank you,

答:
In addition to non-C++20 answer, if you are, by any chance, able to use C++20 and its concepts feature, I would suggest you the following implementation:

#include <iostream>
#include <concepts>

enum class MyEnum {
    A,
    B,
    C
};

template <typename T>
concept IntegralOrEnum = std::same_as<MyEnum, T> || std::integral<T>;

template <IntegralOrEnum T>
bool isFunction(T const& aVariable) {
    return true;
}

int main() {
    isFunction(MyEnum::A);
    isFunction(3);
    isFunction("my_string"); // error
    return 0;
}
```

<p>Demo</p>

<p><strong>UPDATE</strong></p>

<p>According to @RichardSmith's comment, here is a more scalable and reusable approach:</p>

<pre class="lang-cpp prettyprint-override"><code>template <typename T, typename ...U>
concept one_of = (std::is_same_v<T, U> || ...);

template <one_of<int, MyEnum> T>
bool isFunction(T const& aVariable) {
    return true;
}
</code>```

Title: Overloading a function using templates

Body:
I am trying to define a function using templates and I want the typename to be either int or anEnum (a specific enum I had defined). I have tried the following but I have failed:

template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}

What I am trying to do is to use templates, instead of defining two overloaded functions.
I'd prefer the function to be called as the following, without the programmer having to consider the type

isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)

Basically, I want this function to be templated for int and aNum types. I have searched for this, but could not find the answer. What may I be missing? Thank you,

Body:
In addition to non-C++20 answer, if you are, by any chance, able to use C++20 and its concepts feature, I would suggest you the following implementation:

#include <iostream>
#include <concepts>

enum class MyEnum {
    A,
    B,
    C
};

template <typename T>
concept IntegralOrEnum = std::same_as<MyEnum, T> || std::integral<T>;

template <IntegralOrEnum T>
bool isFunction(T const& aVariable) {
    return true;
}

int main() {
    isFunction(MyEnum::A);
    isFunction(3);
    isFunction("my_string"); // error
    return 0;
}

<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:23,positionColumn:1,positionLineNumber:1,selectionStartColumn:2,selectionStartLineNumber:23,startColumn:1,startLineNumber:1),source:'%23include+%3Ciostream%3E%0A%23include+%3Cconcepts%3E%0A%0Aenum+class+MyEnum+%7B%0A++++A,%0A++++B,%0A++++C%0A%7D%3B%0A%0Atemplate+%3Ctypename+T%3E%0Aconcept+IntegralOrEnum+%3D+std::same_as%3CMyEnum,+T%3E+%7C%7C+std::integral%3CT%3E%3B%0A%0Atemplate+%3CIntegralOrEnum+T%3E%0Abool+isFunction(T+const%26+aVariable)+%7B%0A++++return+true%3B%0A%7D%0A%0Aint+main()+%7B%0A++++isFunction(MyEnum::A)%3B%0A++++isFunction(3)%3B%0A++++isFunction(%22my_string%22)%3B+//+error%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:49.85494633014216,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:gsnapshot,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:2,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B2a',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+(trunk)+(Editor+%231,+Compiler+%232)+C%2B%2B',t:'0')),k:50.145053669857845,l:'4',m:50,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:2,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%232+with+x86-64+gcc+(trunk)',t:'0')),header:(),l:'4',m:50,n:'0',o:'',s:0,t:'0')),k:50.145053669857845,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="noreferrer">Demo

UPDATE

According to @RichardSmith's comment, here is a more scalable and reusable approach:

template <typename T, typename ...U>
concept one_of = (std::is_same_v<T, U> || ...);

template <one_of<int, MyEnum> T>
bool isFunction(T const& aVariable) {
    return true;
}


问:
Using FetchRequest in swiftUI view model
I'm trying to follow the MVVM pattern in swiftUI and I’m running into a problem with core data and fetch request. All of the videos I've seen and articles I have read on it, have a @FetchRequest in the view, that accesses and modifies the core data. How would I put this in the SettingsVCModel? I can't seem to figure it out and as such I have kept the fetch request inside the view struct(SettingsVC) and used it there. However this has so far been with buttons, where you are able to perform an action. Now I need to do it with a toggle, that only has a binding variable associated with it and no action like buttons have. I tried the  didSet approach on the @Published bio inside SettingsVCModel, but they you don't have access to the fetch request. Any help would be greatly appreciated. The code I’m working with is below.   </p>

```<code>struct SettingsVC: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: UserSettings.getUserSettings()) var userSettings : FetchedResults<UserSettings>
    @ObservedObject var model = SettingsVCModel()

    var body: some View {
        NavigationView {
            Form{
                Section(header: Text("Application")){
                    Toggle(isOn: $model.bio, label: {Text(model.determineBiometricType())})
                    Picker(selection: $model.unitSelection, label: Text("Units")) {
                        Text("Imperial").tag(0)
                        Text("Metric").tag(1)
                    }
                    SettingsButton(toggleButton: $model.openSettings, title: "System Authorizations")
                }
                Section(header: Text("Feedback")){
                    NavigationLink(destination: ContactVC()){
                        Text("Contact Me")
                    }
                    SettingsButton(toggleButton: $model.rateApp, title: "Please Rate Body Insights")
                    SettingsButton(toggleButton: $model.tellAFriend, title: "Tell a Friend")
                }
                Section(header: Text("General")){
                    NavigationLink(destination: AboutVC()){
                        Text("About")
                    }
                    SettingsButton(toggleButton: $model.openPrivacyPolicy, title: "Privacy Policy", openPrivacyPolicy: true)
                }
            }
            .onAppear{
                self.model.bio = self.userSettings.first!.useBiometricUnlock
                self.model.unitSelection = self.userSettings.first!.usesMetric ? 1 : 0
            }
            .navigationBarTitle("Settings")
            .sheet(isPresented: $model.tellAFriend, content: {
                ShareSheetView(activityItems: ["Hey, check out this cool app! https://apps.apple.com/uy/app/body-insights/id1397531585"])
            })

        }
    }
}

final class SettingsVCModel : ObservableObject{
    @Published var unitSelection = 0
    @Published var tellAFriend = false
    @Published var openPrivacyPolicy = false
    @Published var bio = false
    @Published var openSettings = false {
        didSet{
            if openSettings{
                openAppSettingsApp()
                openSettings = false
            }
        }
    }
    @Published var rateApp = false {
        didSet{
            if rateApp{
                openRateApp()
                rateApp = false
            }
        }
    }

    func openRateApp() {
        let appID = "1397531585"
        let urlString = "https://itunes.apple.com/us/app/appName/id\(appID)?mt=8&action=write-review"
        let url = URL(string: urlString)!
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }

    func openAppSettingsApp() {
        guard
            let settingsURL = URL(string: UIApplication.openSettingsURLString),
            UIApplication.shared.canOpenURL(settingsURL)
            else {
                return
        }

        UIApplication.shared.open(settingsURL)
        return
    }

    func determineBiometricType() -> String {
        let authContext = LAContext()
        let _ = authContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
        switch(authContext.biometryType) {
        case .none:
            return "Not Avaliable"
        case .touchID:
            return "TouchID"
        case .faceID:
            return "FaceID"
        @unknown default:
            return "Not Avaliable"
        }
    }
}

public class UserSettings : NSManagedObject, Identifiable {
    @NSManaged public var useBiometricUnlock : Bool
    @NSManaged public var usesMetric : Bool
    @NSManaged public var name : String
    @NSManaged public var birthday : Date
    @NSManaged public var age : Int

    static func getUserSettings() -> NSFetchRequest<UserSettings> {
        let request : NSFetchRequest<UserSettings> = UserSettings.fetchRequest() as! NSFetchRequest<UserSettings>
        request.sortDescriptors = []
        return request
    }

    static func save(){
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        do {
            try context.save()
        } catch{
            print(error)
        }
    }

    static func preloadData(){
        let preloadKey: String  = "preloadKey"
        let isPreloaded = UserDefaults.standard.bool(forKey: preloadKey)

        if !isPreloaded {
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            let defaultSettings = UserSettings(context: context)
            let deviceName = UIDevice.current.name
            let firstName = deviceName.components(separatedBy: " ").first
            let isMetric = NSLocale.current.usesMetricSystem

            defaultSettings.name = firstName ?? ""
            defaultSettings.useBiometricUnlock = false
            defaultSettings.usesMetric = isMetric
            defaultSettings.age = 0
            defaultSettings.birthday = Date()

            UserDefaults.standard.set(true, forKey: preloadKey)
            UserSettings.save()
        }
    }
}
</code>```

答:
It appears you can only use SwiftUI's FetchRequest inside a view.
If you check its definition, FetchRequest conforms to DynamicProperty, and if you read the documentation around both they imply it is designed to be used in a SwiftUI view.

FetchRequest:

```<code>/// Property wrapper to help Core Data clients drive views from the results of
/// a fetch request. The managed object context used by the fetch request and
/// its results is provided by @Environment(\.managedObjectContext).
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct FetchRequest<Result> : DynamicProperty where Result : NSFetchRequestResult {
</code>```

DynamicProperty:

```<code>/// Represents a stored variable in a `View` type that is dynamically
/// updated from some external property of the view. These variables
/// will be given valid values immediately before `body()` is called.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicProperty {

    /// Called immediately before the view's body() function is
    /// executed, after updating the values of any dynamic properties
    /// stored in `self`.
    mutating func update()
}
</code>```

Body:
I'm trying to follow the MVVM pattern in swiftUI and I’m running into a problem with core data and fetch request. All of the videos I've seen and articles I have read on it, have a @FetchRequest in the view, that accesses and modifies the core data. How would I put this in the SettingsVCModel? I can't seem to figure it out and as such I have kept the fetch request inside the view struct(SettingsVC) and used it there. However this has so far been with buttons, where you are able to perform an action. Now I need to do it with a toggle, that only has a binding variable associated with it and no action like buttons have. I tried the  didSet approach on the @Published bio inside SettingsVCModel, but they you don't have access to the fetch request. Any help would be greatly appreciated. The code I’m working with is below.

struct SettingsVC: View {
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: UserSettings.getUserSettings()) var userSettings : FetchedResults<UserSettings>
    @ObservedObject var model = SettingsVCModel()

    var body: some View {
        NavigationView {
            Form{
                Section(header: Text("Application")){
                    Toggle(isOn: $model.bio, label: {Text(model.determineBiometricType())})
                    Picker(selection: $model.unitSelection, label: Text("Units")) {
                        Text("Imperial").tag(0)
                        Text("Metric").tag(1)
                    }
                    SettingsButton(toggleButton: $model.openSettings, title: "System Authorizations")
                }
                Section(header: Text("Feedback")){
                    NavigationLink(destination: ContactVC()){
                        Text("Contact Me")
                    }
                    SettingsButton(toggleButton: $model.rateApp, title: "Please Rate Body Insights")
                    SettingsButton(toggleButton: $model.tellAFriend, title: "Tell a Friend")
                }
                Section(header: Text("General")){
                    NavigationLink(destination: AboutVC()){
                        Text("About")
                    }
                    SettingsButton(toggleButton: $model.openPrivacyPolicy, title: "Privacy Policy", openPrivacyPolicy: true)
                }
            }
            .onAppear{
                self.model.bio = self.userSettings.first!.useBiometricUnlock
                self.model.unitSelection = self.userSettings.first!.usesMetric ? 1 : 0
            }
            .navigationBarTitle("Settings")
            .sheet(isPresented: $model.tellAFriend, content: {
                ShareSheetView(activityItems: ["Hey, check out this cool app! https://apps.apple.com/uy/app/body-insights/id1397531585"])
            })

        }
    }
}

final class SettingsVCModel : ObservableObject{
    @Published var unitSelection = 0
    @Published var tellAFriend = false
    @Published var openPrivacyPolicy = false
    @Published var bio = false
    @Published var openSettings = false {
        didSet{
            if openSettings{
                openAppSettingsApp()
                openSettings = false
            }
        }
    }
    @Published var rateApp = false {
        didSet{
            if rateApp{
                openRateApp()
                rateApp = false
            }
        }
    }

    func openRateApp() {
        let appID = "1397531585"
        let urlString = "https://itunes.apple.com/us/app/appName/id\(appID)?mt=8&action=write-review"
        let url = URL(string: urlString)!
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }

    func openAppSettingsApp() {
        guard
            let settingsURL = URL(string: UIApplication.openSettingsURLString),
            UIApplication.shared.canOpenURL(settingsURL)
            else {
                return
        }

        UIApplication.shared.open(settingsURL)
        return
    }

    func determineBiometricType() -> String {
        let authContext = LAContext()
        let _ = authContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
        switch(authContext.biometryType) {
        case .none:
            return "Not Avaliable"
        case .touchID:
            return "TouchID"
        case .faceID:
            return "FaceID"
        @unknown default:
            return "Not Avaliable"
        }
    }
}

public class UserSettings : NSManagedObject, Identifiable {
    @NSManaged public var useBiometricUnlock : Bool
    @NSManaged public var usesMetric : Bool
    @NSManaged public var name : String
    @NSManaged public var birthday : Date
    @NSManaged public var age : Int

    static func getUserSettings() -> NSFetchRequest<UserSettings> {
        let request : NSFetchRequest<UserSettings> = UserSettings.fetchRequest() as! NSFetchRequest<UserSettings>
        request.sortDescriptors = []
        return request
    }

    static func save(){
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        do {
            try context.save()
        } catch{
            print(error)
        }
    }

    static func preloadData(){
        let preloadKey: String  = "preloadKey"
        let isPreloaded = UserDefaults.standard.bool(forKey: preloadKey)

        if !isPreloaded {
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
            let defaultSettings = UserSettings(context: context)
            let deviceName = UIDevice.current.name
            let firstName = deviceName.components(separatedBy: " ").first
            let isMetric = NSLocale.current.usesMetricSystem

            defaultSettings.name = firstName ?? ""
            defaultSettings.useBiometricUnlock = false
            defaultSettings.usesMetric = isMetric
            defaultSettings.age = 0
            defaultSettings.birthday = Date()

            UserDefaults.standard.set(true, forKey: preloadKey)
            UserSettings.save()
        }
    }
}

Body:
It appears you can only use SwiftUI's FetchRequest inside a view.
If you check its definition, FetchRequest conforms to DynamicProperty, and if you read the documentation around both they imply it is designed to be used in a SwiftUI view.

FetchRequest:

/// Property wrapper to help Core Data clients drive views from the results of
/// a fetch request. The managed object context used by the fetch request and
/// its results is provided by @Environment(\.managedObjectContext).
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
@propertyWrapper public struct FetchRequest<Result> : DynamicProperty where Result : NSFetchRequestResult {

DynamicProperty:

/// Represents a stored variable in a `View` type that is dynamically
/// updated from some external property of the view. These variables
/// will be given valid values immediately before `body()` is called.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol DynamicProperty {

    /// Called immediately before the view's body() function is
    /// executed, after updating the values of any dynamic properties
    /// stored in `self`.
    mutating func update()
}


问:
Reading large table by chunks
I have a table generated on a server and I connect to it using a presto client as follows:

```<code>conn = presto.connect('hostname',port)
db = "some_large_table"
</code>```

What I would like to do is  to read in 1 chunk at a time then do my processing and append that chunk to an existing df. Ie:

```<code>sql = "select column1, .. column20 limit 100"
chunk_count = 0
dfs = []

for chunk in pd.read_sql_query(sql, conn, chunksize=10) :
    chunk_count +=1
    dfs.append(chunk)

print(dfs[['column1', 'column2']])
</code>```

The print dfs only shows 10 rows. Which Means its not appending.

答:
In my query I limited the number of rows to 10. For some reason df_full.append() does not work, I changed it to df_full = df_full.append() and it works fine.

```<code>sql = "select*...limit 10"
df_source = pd.read_sql_query(sql, conn, chunksize=2)
chunk_count = 0

df_list = []
df_full = pd.DataFrame(columns = col_names)

for chunk in df_source:
    df_list.append(chunk)

for df_item in df_list:
    df_full = df_full.append(df_item, ignore_index = True)

print(df_full)
</code>```

Result:

```<code>[10 rows x 38 columns]
</code>```

Title: Reading large table by chunks

Body:
I have a table generated on a server and I connect to it using a presto client as follows:

conn = presto.connect('hostname',port)
db = "some_large_table"

What I would like to do is  to read in 1 chunk at a time then do my processing and append that chunk to an existing df. Ie:

sql = "select column1, .. column20 limit 100"
chunk_count = 0
dfs = []

for chunk in pd.read_sql_query(sql, conn, chunksize=10) :
    chunk_count +=1
    dfs.append(chunk)

print(dfs[['column1', 'column2']])

The print dfs only shows 10 rows. Which Means its not appending.

Body:
In my query I limited the number of rows to 10. For some reason df_full.append() does not work, I changed it to df_full = df_full.append() and it works fine.

sql = "select*...limit 10"
df_source = pd.read_sql_query(sql, conn, chunksize=2)
chunk_count = 0

df_list = []
df_full = pd.DataFrame(columns = col_names)

for chunk in df_source:
    df_list.append(chunk)

for df_item in df_list:
    df_full = df_full.append(df_item, ignore_index = True)

print(df_full)

Result:

[10 rows x 38 columns]


问:
Connect to existing tables in database using SQLAlchemy
I am quite new to python. I am using flask to develope microservices using python. In order to connect to database  , I am using Sqlalchemy . Is there any standard approach like creating models , and connecting them to existing tables in db? And like Spring boot services , do we have repository classes for querying or what is the standard procedure. Any code snippet appreciated.</p>

答:
You do not need to create models at all by using the database's Metadata.

I used the following approach:

create engine

```<code>engine = sqlalchemy.create_engine('urlpwportetc...')
</code>```

load the metadata using the engine as the bind parameter

```<code>metadata = sqlalchemy.Metadata(bind=engine)
</code>```

make a reference to the table

```<code>my_table = sqlalchemy.Table('exact_table_name', metadata, autoload = True)
</code>```

you can then start constructing your db queries using (for example)

```<code>query = my_table.insert()
query.values({'column': value1, 'column2': value2})
</code>```

this is then executed with

```<code>my_session = Session(engine)
my_session.execute(query)
my_session.close()
</code>```

Body:
You do not need to create models at all by using the database's Metadata.

I used the following approach:

create engine

engine = sqlalchemy.create_engine('urlpwportetc...')

load the metadata using the engine as the bind parameter

metadata = sqlalchemy.Metadata(bind=engine)

make a reference to the table

my_table = sqlalchemy.Table('exact_table_name', metadata, autoload = True)

you can then start constructing your db queries using (for example)

query = my_table.insert()
query.values({'column': value1, 'column2': value2})

this is then executed with

my_session = Session(engine)
my_session.execute(query)
my_session.close()


问:
How to send a XML file to RabbitMQ using Python?
I am  having an xml file called Test.xml  which I am trying to send RabbitMQ using python.

I know below deatails regarding the Rabbit MQ

```<code>Hostname: xxx.xxxx.xxx

AMQP Port (SSL)  :4589

ESB Portal (Message Search): http://xxx.xxx.xxx:8585

RabbitMQ Web UI (https) :https://xxx.xxx.xxxx:15672
</code>```

How can this be done from python?

答:
This can be done using pika, you can read the file content and send it as a big string to RabbitMQ. And on the other side you can parse the content using ElementTree.fromstring.

Connection details:

```<code>credentials = pika.PlainCredentials('username', 'password')
conn = pika.BlockingConnection(pika.ConnectionParameters('host', port, 'vhost', credentials))
channel = conn.channel()
</code>```

Publisher:

```<code>with open('filename.xml', 'r') as fp:
    lines = fp.readlines()
channel.basic_publish('exchange', 'queue', ''.join(lines))
</code>```

Consumer:

```<code>def on_message(unused_channel, unused_method_frame, unused_header_frame, body):
    lines = body.decode()
    doc = ElementTree.fromstring(lines)
    tags = doc.findall("tag")

    ## DO YOUR STUFF HERE

channel.basic_consume('queue', on_message)
channel.start_consuming()
</code>```

Hope this helps!

RabbitMQ flow:

Reference: RabbitMQ docs

Body:
I am  having an xml file called Test.xml  which I am trying to send RabbitMQ using python.

I know below deatails regarding the Rabbit MQ

Hostname: xxx.xxxx.xxx

AMQP Port (SSL)  :4589

ESB Portal (Message Search): http://xxx.xxx.xxx:8585

RabbitMQ Web UI (https) :https://xxx.xxx.xxxx:15672

How can this be done from python?

Body:
This can be done using pika, you can read the file content and send it as a big string to RabbitMQ. And on the other side you can parse the content using ElementTree.fromstring.

Connection details:

credentials = pika.PlainCredentials('username', 'password')
conn = pika.BlockingConnection(pika.ConnectionParameters('host', port, 'vhost', credentials))
channel = conn.channel()

Publisher:

with open('filename.xml', 'r') as fp:
    lines = fp.readlines()
channel.basic_publish('exchange', 'queue', ''.join(lines))

Consumer:

def on_message(unused_channel, unused_method_frame, unused_header_frame, body):
    lines = body.decode()
    doc = ElementTree.fromstring(lines)
    tags = doc.findall("tag")

    ## DO YOUR STUFF HERE

channel.basic_consume('queue', on_message)
channel.start_consuming()

Hope this helps!

RabbitMQ flow:

Reference: RabbitMQ docs