问:
VS Code + Python -> Erros in Pool.Apply_async are ignored?
Take a look at this code:

```<code>import multiprocessing as mp

def myFunc():
    nonExistingObject.DoSomething()

def collectFunc():
    pass

#uncomment me for desired behaviour
#myFunc()

pool = mp.Pool(2)
pool.apply_async(myFunc, args=(), callback=collectFunc)
</code>```

If you run it on VS Code, the code completes and no errors are reported, but of course there's an error going on. Not only nonExistingObject is not defined but DoSomething() also isn't.

If you uncomment the indicated code, you will get the expected error @ runtime. On VSCode I already checked the "Uncaught Exceptions" breakpoints

Is there a way to make the error get caught? is this a python thing or a VSCode thing?

答:
I think your code is quitting before the pool manages to run anything.

Try

```<code>with mp.Pool(2) as pool:
   pool.apply_async(myFunc, args=(), callback=collectFunc)
</code>```

Body:
Take a look at this code:

import multiprocessing as mp

def myFunc():
    nonExistingObject.DoSomething()

def collectFunc():
    pass

#uncomment me for desired behaviour
#myFunc()

pool = mp.Pool(2)
pool.apply_async(myFunc, args=(), callback=collectFunc)

If you run it on VS Code, the code completes and no errors are reported, but of course there's an error going on. Not only nonExistingObject is not defined but DoSomething() also isn't.

If you uncomment the indicated code, you will get the expected error @ runtime. On VSCode I already checked the "Uncaught Exceptions" breakpoints

Is there a way to make the error get caught? is this a python thing or a VSCode thing?

Body:
I think your code is quitting before the pool manages to run anything.

Try

with mp.Pool(2) as pool:
   pool.apply_async(myFunc, args=(), callback=collectFunc)


来源: stackexchange

问:
Removing an item from a session
I am storing an item in an asp.net session for example but I do not how to remove such an item can I just do the following. How would i also find the key to ensure it existed to be able to remove it in first place.

```<code>public void SetObjectValue(string name, object newValue) {
        Session["TestItem"] = newValue;
}
</code>```

Remove

```<code>public void RemoveObjectValue(string name, object newValue) {
        Session["TestItem"] = null;
}
</code>```

But the key would still be in the Session object how do I remove the test item from the session.

答:
There is a .Remove(string name) method for that. You can see the MSDN docs here

Basically, all you have to do is:

```<code>Session.Remove("TestItem");
</code>```

ContentLicense: CC BY-SA 4.0

Title: Removing an item from a session

Body:
I am storing an item in an asp.net session for example but I do not how to remove such an item can I just do the following. How would i also find the key to ensure it existed to be able to remove it in first place.

public void SetObjectValue(string name, object newValue) {
        Session["TestItem"] = newValue;
}

Remove

public void RemoveObjectValue(string name, object newValue) {
        Session["TestItem"] = null;
}

But the key would still be in the Session object how do I remove the test item from the session.

Body:
There is a .Remove(string name) method for that. You can see the MSDN docs here

Basically, all you have to do is:

Session.Remove("TestItem");


问:
difference in using sklearn.utils.resample with stratify and without stratify
What is difference in using sklearn.utils.resample with stratify and without stratify?

https://scikit-learn.org/stable/modules/generated/sklearn.utils.resample.html

```<code>import numpy
from sklearn.utils import resample

y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
res = resample(y, n_samples=5, replace=False, random_state=0)
print (res)
[1, 1, 0, 1, 1]

res = resample(y, n_samples=5, replace=False, stratify=y, random_state=0)
print (res)

[1, 1, 1, 0, 1]
</code>```

答:
stratification in general is an approach to maintain the original class proportion in resulting subsets.It is the technique to ensure training and test sets share approximately the same ratio of examples from each class, so that consistent predictive performance scores can be achieved in both the sets.

If the dataset has high class imbalance, in the worst-case scenario, the test set may not contain any instance of a minority class at all. Thus,
a recommended practice is to divide the dataset in a stratified fashion. Here, stratification simply means that we randomly split a dataset such that each class is correctly represented in the resulting subsets (the training and the test set)
It shall be noted that random subsampling in non-stratified fashion is usually not a big concern when working with relatively large and balanced datasets.

Body:
What is difference in using sklearn.utils.resample with stratify and without stratify?

https://scikit-learn.org/stable/modules/generated/sklearn.utils.resample.html

import numpy
from sklearn.utils import resample

y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
res = resample(y, n_samples=5, replace=False, random_state=0)
print (res)
[1, 1, 0, 1, 1]

res = resample(y, n_samples=5, replace=False, stratify=y, random_state=0)
print (res)

[1, 1, 1, 0, 1]


问:
Duplicate Function Implementation
I have one file, app.ts under my scripts folder, that gets copied to wwwroot/scripts by a gulp task. After the gulp task runs, I now also have a wwwroot/scripts/app.ts file, in which the sole function is red-underlined as duplicate. Is this normal, or is my gulp task, below, declared incorrectly?

```<code>var paths = {
    scripts: ["scripts/**/*.js", "scripts/**/*.ts", "scripts/**/*.map"]
};

gulp.task("default", function() {
    gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));
});
</code>```

I see the raw app.ts file, from the root scripts folder also gets built into *.js and *.js.map files. Could this have something to do with the 'false positive' duplicate function?

答:
1- When you call glup with 2 references to the same code the .ts and .js he is going to transpila .. the .ts in to .js soo that's why you have 2 files.

You can try this:

```<code>var paths = {
    scripts: ["scripts/**/*.js", "scripts/**/*.map"]
};

gulp.task("default", function() {
    gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));
});
</code>```

Title: Duplicate Function Implementation

Body:
I have one file, app.ts under my scripts folder, that gets copied to wwwroot/scripts by a gulp task. After the gulp task runs, I now also have a wwwroot/scripts/app.ts file, in which the sole function is red-underlined as duplicate. Is this normal, or is my gulp task, below, declared incorrectly?

var paths = {
    scripts: ["scripts/**/*.js", "scripts/**/*.ts", "scripts/**/*.map"]
};

gulp.task("default", function() {
    gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));
});

I see the raw app.ts file, from the root scripts folder also gets built into *.js and *.js.map files. Could this have something to do with the 'false positive' duplicate function?

Body:
1- When you call glup with 2 references to the same code the .ts and .js he is going to transpila .. the .ts in to .js soo that's why you have 2 files.

You can try this:

var paths = {
    scripts: ["scripts/**/*.js", "scripts/**/*.map"]
};

gulp.task("default", function() {
    gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));
});


问:
How to rotate pushpin image in bing map?
I am trying to rotate the pushpin image base on the degree for example "120" to show which direction it is going.</p>

```<code> var pushpin = new Microsoft.Maps.Pushpin(curlocation, {
                icon: '/images/Airplane_icon.png',
                anchor: new Microsoft.Maps.Point(20, 20),
                color: 'red'
            });
</code>```

答:
It is possible to rotate a pushpin in Bing Maps but requires a bit of code to achieve. There is a code sample here: https://bingmapsv8samples.azurewebsites.net/#Pushpin_RotatedImage This approach would work fine for a few pushpins, but if you have a lot of pushpins that all have difference rotations, or the rotation of a pushpin is updated frequently, this solution likely wouldn't be the best option.

Another consideration is to take a look at Azure Maps which is another Microsoft mapping platform which does support rotating icons on the map. Here is a sample: https://azuremapscodesamples.azurewebsites.net/index.html?sample=Symbol%20Layer%20Options (click on the icon options tab and move the rotation slider). Azure Maps can handle dynamic rotation values on large data sets easily. Here are a couple of related examples: https://azuremapscodesamples.azurewebsites.net/index.html?sample=Animate%20a%20Symbol%20along%20a%20Path

https://azuremapscodesamples.azurewebsites.net/index.html?sample=Add%20Arrow%20along%20a%20Path

Body:
I am trying to rotate the pushpin image base on the degree for example "120" to show which direction it is going.

 var pushpin = new Microsoft.Maps.Pushpin(curlocation, {
                icon: '/images/Airplane_icon.png',
                anchor: new Microsoft.Maps.Point(20, 20),
                color: 'red'
            });


问:
What should I return instead of null?
I've heard that it is bad practice to return null.

What are the alternatives to returning null in this case?

```<code>    public RollingStock getHeadPoint() {
        if (!train.isEmpty()) {
            return train.get(0);
        } else {
            return null;
        }
    }
</code>```

答:
You should differentiate "get" and "search/find" methods :

getHeadPoint : some train should exist. If not, it's against your business, throw an exception

findHeadPoint : non-existence of the train is coherent to your business, return null

Title: What should I return instead of null?

Body:
I've heard that it is bad practice to return null.

What are the alternatives to returning null in this case?

    public RollingStock getHeadPoint() {
        if (!train.isEmpty()) {
            return train.get(0);
        } else {
            return null;
        }
    }


问:
Making a WPF application retain focus at all times
I've got an issue with a WPF application that I'm writing. The app needs to be able to keep focus at all times. The computer it's running on is a highly specialized machine with the only purpose of running this application.

There is no keyboard connected to the machine (it has a touch screen), so the only thing that can steal focus is windows own "needy windows", such as windows update etc.

How can I make it so that my app retains focus at all times? Is it possible to make the entire app modal?

EDIT:

Thank you both for your answers. I think I'll end up using Topsmost for now, but I'll definitely check out the source of babysmash as that application works exactly the way I want mine to, in regards to the way it handles focus.

答:
I would use

```<code><Window ... Topmost="True">
</code>```

i xaml. But maybe this is not what you are looking for

OwnerDisplayName: Ciddan

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Ciddan

Body:
I would use

<Window ... Topmost="True">

i xaml. But maybe this is not what you are looking for

OwnerDisplayName: slamidtfyn

ContentLicense: CC BY-SA 2.5


问:
Is Java using pointer to access Array by index?
I am curious. is java using Pointer like C or C++ to access array by index? when use C languange, x[a] can be converted to *(x + a). What about Java languange? its same with c and c++ or it just use Sequential search to access the element?</p>

答: If it is an array of objects, it's essentially an array of pointers that reference those objects, this is not the case for primitive values however. Unlike c++, you cannot do pointer arithmetic in Java.</p>


问:
tinymce Strikethrough when pasting from Word
I'm using tinymce editor with the paste plugin.
In some cases when I paste from a word document some of the words have a Strikethrough , even though there isn't one in the word docuemnt.

I saw this question , but it dosen't have an answer and I can't find any other similar questions.

How can I prevent the strikethrough while pasting?

Thank's In Advancce.

答:
You could do some paste handling of your own using the paste parameter paste_preprocess.
For example could you remove some word formatings/styles of your own. The tinymce keep/remove-style-settings for the paste plugin do not seem to handle all cases.</p>


问:
python xml.etree.ElementTree remove empty tag in the middle of text
I have an xml document from which I want to extract text based on tags.

The part that I want to extract text from looks something like this :

```<code><BlockText attr1="blah" attr2=657 ID="Bhf76" lang="en">
Simply dummy text of the printing and typesetting industry. It has survived not only<TIP CONTENT=""/>\n five centuries, electronic typesetting, remaining essentially release.
</BlockText>
</code>```

When I do

```<code>tree = ET.parse("myfile.xml")
root = tree.getroot()
tags = list(set([elem.tag for elem in root.iter()]))
tag = list(filter(lambda i: "BlockText" in i, tags))[0]
for text in root.iter(tag):
    texte = text.text
</code>```

I'm only able to grab the part that comes before the empty tag <TIP CONTENT=""/>

I tried to delete this tag before getting the rest of the text.

I did :

```<code>emptyTag = list(filter(lambda i: "TIP" in i, tags))
for e in root.iter(emptyTag) :
    root.remove(e)
</code>```

But this is not working.

None of <BlockText> and <TIP> are direct children of root.

Thank you.

答:
The text After <TIP CONTENT=""/> belongs to its own tail not the text of the BlockText tag.

elem.text is the text following the open tag.
elem.tail is the text following the close tag. Usually whitespace but in this case it's has actual text.

Body:
I have an xml document from which I want to extract text based on tags.

The part that I want to extract text from looks something like this :

<BlockText attr1="blah" attr2=657 ID="Bhf76" lang="en">
Simply dummy text of the printing and typesetting industry. It has survived not only<TIP CONTENT=""/>\n five centuries, electronic typesetting, remaining essentially release.
</BlockText>

When I do

tree = ET.parse("myfile.xml")
root = tree.getroot()
tags = list(set([elem.tag for elem in root.iter()]))
tag = list(filter(lambda i: "BlockText" in i, tags))[0]
for text in root.iter(tag):
    texte = text.text

I'm only able to grab the part that comes before the empty tag <TIP CONTENT=""/>

I tried to delete this tag before getting the rest of the text.

I did :

emptyTag = list(filter(lambda i: "TIP" in i, tags))
for e in root.iter(emptyTag) :
    root.remove(e)

But this is not working.

None of <BlockText> and <TIP> are direct children of root.

Thank you.


问:
Can't understand exactly the pointers in 2d array
I have done something by looking to the internet but something is missing here is my code

```<code>void draw_way(int *arr,int lenght_row,int lenght_column) {
int s1 = 0, s2 = 0;
for (s1 = 0; s1 < lenght_row; s1++)
{
    for (s2 = 0; s2 < lenght_column; s2++) {
        if (*((arr + s1 * lenght_row) + s2) == 1)
        {
            printf("S");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 2)
        {
            printf("G");
        }
        else if(*((arr + s1 * lenght_row) + s2) == 3)
        {
            printf("#");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 4)
        {
            printf(".");
        }
    }
    printf("\n");
}
</code>```

it is actually printing a maze but is is not important. The thing I want to understand is why ı had to use *((arr + s1 * lenght_row) + s2) why this is not working if ı use *(*(arr+s1)+s2) what 'lenght_row' does.

答:
if you reduce number of paranthises it will easier to understand: if (*(arr + s1 * lenght_row + s2) == 2)

2D array has c columns and r rows. They are stored in the memory continuously  row0 then row 1 them row2 ...

So to access the particular element (row, column) you need multiply row by 'r' (whics is how many elements we hae in the row and add column.

Body:
I have done something by looking to the internet but something is missing here is my code

void draw_way(int *arr,int lenght_row,int lenght_column) {
int s1 = 0, s2 = 0;
for (s1 = 0; s1 < lenght_row; s1++)
{
    for (s2 = 0; s2 < lenght_column; s2++) {
        if (*((arr + s1 * lenght_row) + s2) == 1)
        {
            printf("S");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 2)
        {
            printf("G");
        }
        else if(*((arr + s1 * lenght_row) + s2) == 3)
        {
            printf("#");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 4)
        {
            printf(".");
        }
    }
    printf("\n");
}

it is actually printing a maze but is is not important. The thing I want to understand is why ı had to use *((arr + s1 * lenght_row) + s2) why this is not working if ı use *(*(arr+s1)+s2) what 'lenght_row' does.


问:
How to check if a value in object is a primitive?
So basically i want to check if my data (which is in JSON Format) has a value which is a primitive. So let's take an Example: I get data that looks like this: {name: Artikel, value: {"ArtNr": 1234}} and i want to check if 1234 is primitive or not. I also want to differentiate if the result is an Array with Primitives in it or an Object. Is that possible?

```<code>function isObjectContainingPrimitiveValues(test) {
        let values = Object.values(test);
        for (let i of values) {
            console.log(i);
            return (typeof i === 'string' || typeof i === 'number' || typeof i === 'boolean' || typeof i === null || typeof i === undefined);
        }
    }
</code>```

UPDATE

So with the awesome help of MaxK i have built a isResultContainingPrimitiveValues() Function which checks my data for Primitive/ Primitive Arrays and or Objects. The following part is the trickiest at least with my understanding. The following Example will hopefully help you understand my problems better.

So my let namesSplit = treeNode.name.split('.'); variable splits the data it gets and has as a result of nameSplit : Artikel,Artnr. Next i defined a key variable let key = namesSplit[0]; which has key : Artikel as a result. Than i define a contextEntry variable let contextEntry = exprData.contextEntry.find(_x => _x.name === key); and has contextEntry : {"name":"Artikel","value":{"ArtNr":123}} as a result. Now i want to check: if there's another split namesSplit.length > 1 check isResultContainingPrimitiveValues(). If it is primitive, throw an error, if it is an object -> get values from it and if it is an array -> get values form there. I know it's a lot but from all the confusing stuff i can't seem to think clear, so i appreciate every help i can get.

答:
You are returning from your function on the first iteration. You should only return false if you found an non-primitive and if you were able to loop over all values you can return true because all values are primitives:

```<code>function isObjectContainingPrimitiveValues(testObj) {
  let values = Object.values(testObj);
  for(let i of values){
     if (typeof i === 'object') {
       return false;
     }
  }
  return true;
};
</code>```

Update:

After reading your comment i changed the code to check for arrays with primitives as well. The idea is, to create a new function which only checks if a single value is a primitive.Now if we find an array, we can simply check - with the help
 of the arrays some function - if some element, inside the array is not primitive. If so return false,otherwise we do the same checks as before:

```<code>function isObjectContainingPrimitiveValues(testObj) {
  let values = Object.values(testObj);
  for (let i of values) {
    if (Array.isArray(i)) {
      if (i.some(val => !isPrimitive(val)))
        return false;
    } else {
      if (!isPrimitive(i))
        return false;
    }
  }
  return true;
};

function isPrimitive(test) {
  return typeof test !== 'object'
}
</code>```

Body:
So basically i want to check if my data (which is in JSON Format) has a value which is a primitive. So let's take an Example: I get data that looks like this: {name: Artikel, value: {"ArtNr": 1234}} and i want to check if 1234 is primitive or not. I also want to differentiate if the result is an Array with Primitives in it or an Object. Is that possible?

function isObjectContainingPrimitiveValues(test) {
        let values = Object.values(test);
        for (let i of values) {
            console.log(i);
            return (typeof i === 'string' || typeof i === 'number' || typeof i === 'boolean' || typeof i === null || typeof i === undefined);
        }
    }

UPDATE

So with the awesome help of MaxK i have built a isResultContainingPrimitiveValues() Function which checks my data for Primitive/ Primitive Arrays and or Objects. The following part is the trickiest at least with my understanding. The following Example will hopefully help you understand my problems better.

So my let namesSplit = treeNode.name.split('.'); variable splits the data it gets and has as a result of nameSplit : Artikel,Artnr. Next i defined a key variable let key = namesSplit[0]; which has key : Artikel as a result. Than i define a contextEntry variable let contextEntry = exprData.contextEntry.find(_x => _x.name === key); and has contextEntry : {"name":"Artikel","value":{"ArtNr":123}} as a result. Now i want to check: if there's another split namesSplit.length > 1 check isResultContainingPrimitiveValues(). If it is primitive, throw an error, if it is an object -> get values from it and if it is an array -> get values form there. I know it's a lot but from all the confusing stuff i can't seem to think clear, so i appreciate every help i can get.

Body:
You are returning from your function on the first iteration. You should only return false if you found an non-primitive and if you were able to loop over all values you can return true because all values are primitives:

function isObjectContainingPrimitiveValues(testObj) {
  let values = Object.values(testObj);
  for(let i of values){
     if (typeof i === 'object') {
       return false;
     }
  }
  return true;
};

Update:

After reading your comment i changed the code to check for arrays with primitives as well. The idea is, to create a new function which only checks if a single value is a primitive.Now if we find an array, we can simply check - with the help
 of the arrays some function - if some element, inside the array is not primitive. If so return false,otherwise we do the same checks as before:

function isObjectContainingPrimitiveValues(testObj) {
  let values = Object.values(testObj);
  for (let i of values) {
    if (Array.isArray(i)) {
      if (i.some(val => !isPrimitive(val)))
        return false;
    } else {
      if (!isPrimitive(i))
        return false;
    }
  }
  return true;
};

function isPrimitive(test) {
  return typeof test !== 'object'
}


问:
mysql how have in a report the ids of the newly inserted, updated, deleted records per month
I have a table where I need to have a report on a per month basis, on which records where updated.

```<code>Column     Type        Comment
id         bigint(20)  NULL
deleted    bit(1)      NULL
title      text        NULL
updateDate datetime    NULL
</code>```

I can get the records updated in any given period, with the help of the updateDate column.

How could I get a new table, that would not interfere with the scheme, that would have also in there stored the following info?

```<code>id action  updatedate
</code>```

I would like to have a result like

```<code>id  action    updatedate
23  inserted  2019-12-19 11:28:03
35  updated   2019-12-19 10:43:22
</code>```

Could you please give me an example of how I could achieve the above?

I have created a query that returns to me the records that had an update date between dates, but this does not give me a clue of what was the action that took place. I also do not want to alter at all the current scheme, so I would like to store the actions info in a new table

答:
You could add some more timestamps:

```<code>created_at
updated_at
deleted_at
</code>```

Or just two columns (updated_at) and another field which contain the performed action.

Whenever you perform an action, you have to set the timestamp to the current time.

Why do you want to store the information in another table? Isn't it enough to query the changes and display them without another table?

The query could look like this:

```<code>SELECT id, action, updated_at from table where MONTH(updated_at) = 4;
</code>```

The query would select and return all of the changes in April.

Body:
I have a table where I need to have a report on a per month basis, on which records where updated.

Column     Type        Comment
id         bigint(20)  NULL
deleted    bit(1)      NULL
title      text        NULL
updateDate datetime    NULL

I can get the records updated in any given period, with the help of the updateDate column.

How could I get a new table, that would not interfere with the scheme, that would have also in there stored the following info?

id action  updatedate

I would like to have a result like

id  action    updatedate
23  inserted  2019-12-19 11:28:03
35  updated   2019-12-19 10:43:22

Could you please give me an example of how I could achieve the above?

I have created a query that returns to me the records that had an update date between dates, but this does not give me a clue of what was the action that took place. I also do not want to alter at all the current scheme, so I would like to store the actions info in a new table

Body:
You could add some more timestamps:

created_at
updated_at
deleted_at

Or just two columns (updated_at) and another field which contain the performed action.

Whenever you perform an action, you have to set the timestamp to the current time.

Why do you want to store the information in another table? Isn't it enough to query the changes and display them without another table?

The query could look like this:

SELECT id, action, updated_at from table where MONTH(updated_at) = 4;

The query would select and return all of the changes in April.


问:
Excel: Downloading file LoadTestExcelAddIn.vsto did not succeed
I'm developing an Excel Add-In using Visual Studio 2017. In the registry, I accidentally deleted a folder related to Excel Add-Ins because I had problems with making Excel forget about an Add-In which has been disabled. Sorry for being vague but I don't remember the exact details and maybe that's not even the cause.

Now I'm always getting an error popup when launching Excel:
:

```<code>Name:
From: file:///C:/Program Files (x86)/Microsoft Visual Studio 12.0/Common7/IDE/PrivateAssemblies/Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto

************** Exception Text **************
System.Deployment.Application.DeploymentDownloadException: Downloading file:///C:/Program Files (x86)/Microsoft Visual Studio 12.0/Common7/IDE/PrivateAssemblies/Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto did not succeed. ---> System.Net.WebException: Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto'. ---> System.Net.WebException: Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto'. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.Net.FileWebStream..ctor(FileWebRequest request, String path, FileMode mode, FileAccess access, FileShare sharing, Int32 length, Boolean async)
   at System.Net.FileWebResponse..ctor(FileWebRequest request, Uri uri, FileAccess access, Boolean asyncHint)
   --- End of inner exception stack trace ---
   at System.Net.FileWebResponse..ctor(FileWebRequest request, Uri uri, FileAccess access, Boolean asyncHint)
   at System.Net.FileWebRequest.GetResponseCallback(Object state)
   --- End of inner exception stack trace ---
   at System.Net.FileWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.FileWebRequest.GetResponse()
   at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
   --- End of inner exception stack trace ---
   at Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.GetManifests(TimeSpan timeout)
   at Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.InstallAddIn()
</code>```

I thought that repairing Office or Visual Studio using the official installers would fix this problem as well but it did not. How can I repair the registry related to this Add-In error? Maybe the stack trace helps you figure it out.

Note:
The folder C:/Program Files (x86)/Microsoft Visual Studio 12.0 does not exist but 10.0 and 14.0 as well as one without version number do exist so maybe the installer can be pointed somewhere else?

答:
Answer is late, I had the same problem with  Excel Office 2013 today. I fixed the problem by deleting the add-in .

Open Excel as administrator

Create a new document

Click on the developer tab

Click on COM add-ins

Find the add-in, it will help you to know which one as it shows you the add-in path

If you need this add-in, you will have to reinstall it again.

Body:
I'm developing an Excel Add-In using Visual Studio 2017. In the registry, I accidentally deleted a folder related to Excel Add-Ins because I had problems with making Excel forget about an Add-In which has been disabled. Sorry for being vague but I don't remember the exact details and maybe that's not even the cause.

Now I'm always getting an error popup when launching Excel:
:

Name:
From: file:///C:/Program Files (x86)/Microsoft Visual Studio 12.0/Common7/IDE/PrivateAssemblies/Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto

************** Exception Text **************
System.Deployment.Application.DeploymentDownloadException: Downloading file:///C:/Program Files (x86)/Microsoft Visual Studio 12.0/Common7/IDE/PrivateAssemblies/Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto did not succeed. ---> System.Net.WebException: Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto'. ---> System.Net.WebException: Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto'. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   at System.Net.FileWebStream..ctor(FileWebRequest request, String path, FileMode mode, FileAccess access, FileShare sharing, Int32 length, Boolean async)
   at System.Net.FileWebResponse..ctor(FileWebRequest request, Uri uri, FileAccess access, Boolean asyncHint)
   --- End of inner exception stack trace ---
   at System.Net.FileWebResponse..ctor(FileWebRequest request, Uri uri, FileAccess access, Boolean asyncHint)
   at System.Net.FileWebRequest.GetResponseCallback(Object state)
   --- End of inner exception stack trace ---
   at System.Net.FileWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.FileWebRequest.GetResponse()
   at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
   --- End of inner exception stack trace ---
   at Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.GetManifests(TimeSpan timeout)
   at Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.InstallAddIn()

I thought that repairing Office or Visual Studio using the official installers would fix this problem as well but it did not. How can I repair the registry related to this Add-In error? Maybe the stack trace helps you figure it out.

Note:
The folder C:/Program Files (x86)/Microsoft Visual Studio 12.0 does not exist but 10.0 and 14.0 as well as one without version number do exist so maybe the installer can be pointed somewhere else?


问:
Filtering table multiple columns
I used w3School code for my page and it works fine but it only filters one column, don’t know how create loops but hopping there is easier solution.

```<code>    td = tr[i].getElementsByTagName("td")[0];
</code>```

changing here 0 to 1 changes the column, could find anything so tried many different thing but not the programmer have no idea if there any other properties that allows multiple columns, spent so much searching, please help

function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th,
#myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  background-color: #f1f1f1;
}</code>```

My Customers

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search             for names.." title="Type in a name">

    Name
    Country

    Alfreds Futterkiste
    Germany

    Berglunds snabbkop
    Sweden

    Island Trading
    UK

    Koniglich Essen
    Germany

    Laughing Bacchus Winecellars
    Canada

    Magazzini Alimentari Riuniti
    Italy

    North/South
    UK

    Paris specialites
    France

```

答:
Code that works for filtering multiple columns dynamically. No changes needed.</p>

```<code>    function myFunction(elem) {
        var input, filter, table, tr, td, i, txtValue;
        input = elem;
        filter = input.value.toUpperCase();
        table = document.getElementById("YourTableId");
        tr = table.getElementsByTagName("tr");
        for (i = 1; i < tr.length; i++) {
            tds = tr[i].getElementsByTagName("td");
            var matches = false;

            for (j = 0; j < tds.length; j++) {
                if (tds[j]) {
                    txtValue = tds[j].textContent || tds[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        matches = true;
                    }
                }
            }

            if(matches == true)
            {
                tr[i].style.display = "";
            }
             else {
                    tr[i].style.display = "none";
                }

            }
        }
</code>```

Title: Filtering table multiple columns

Body:
I used w3School code for my page and it works fine but it only filters one column, don’t know how create loops but hopping there is easier solution.

    td = tr[i].getElementsByTagName("td")[0];

changing here 0 to 1 changes the column, could find anything so tried many different thing but not the programmer have no idea if there any other properties that allows multiple columns, spent so much searching, please help

function myFunction() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th,
#myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  background-color: #f1f1f1;
}

My Customers

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search             for names.." title="Type in a name">

    Name
    Country

    Alfreds Futterkiste
    Germany

    Berglunds snabbkop
    Sweden

    Island Trading
    UK

    Koniglich Essen
    Germany

    Laughing Bacchus Winecellars
    Canada

    Magazzini Alimentari Riuniti
    Italy

    North/South
    UK

    Paris specialites
    France

Body:
Code that works for filtering multiple columns dynamically. No changes needed.

    function myFunction(elem) {
        var input, filter, table, tr, td, i, txtValue;
        input = elem;
        filter = input.value.toUpperCase();
        table = document.getElementById("YourTableId");
        tr = table.getElementsByTagName("tr");
        for (i = 1; i < tr.length; i++) {
            tds = tr[i].getElementsByTagName("td");
            var matches = false;

            for (j = 0; j < tds.length; j++) {
                if (tds[j]) {
                    txtValue = tds[j].textContent || tds[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        matches = true;
                    }
                }
            }

            if(matches == true)
            {
                tr[i].style.display = "";
            }
             else {
                    tr[i].style.display = "none";
                }

            }
        }


问:
Copy part of json key-values in javascript
Given a json like this

```<code>  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };
</code>```

how to get a new json like this, it will only copy the same key to the first one.

```<code>json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};
</code>```

I've tried on Object.assign  or _.assign of lodash

```<code> Object.assign(json1,json2)
 _.assign(json1,json2)
</code>```

but it will copy all the objects of json2 to json1.

答:
Live Demo: https://runkit.com/embed/0z916nnwl2w5

```<code>var output = Object.assign(json1,json2);
delete output.key4;  //Here is the key~~~
console.log(output);
</code>```

Body:
Given a json like this

  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };

how to get a new json like this, it will only copy the same key to the first one.

json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};

I've tried on Object.assign  or _.assign of lodash

 Object.assign(json1,json2)
 _.assign(json1,json2)

but it will copy all the objects of json2 to json1.

Body:
Live Demo: https://runkit.com/embed/0z916nnwl2w5

var output = Object.assign(json1,json2);
delete output.key4;  //Here is the key~~~
console.log(output);


问:
Activity class does not exist in android studio

I keep getting this error when I try to run my android studio. I tried to copy, paste my previous project bit by bit. After I finished it I got this error. I'm really stuck on this one.

Thanks in advance :D

This is my Activity manifest

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.iussystem">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".TermsOfService"></activity>
        <activity android:name=".ForgotPassword" />
        <activity android:name=".Registracija" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
If you are saying your app is in com/example/iusystem/MainActivity.java, isnt that a typo?

Either change your package:

```<code> package="com.example.iussystem"
</code>```

to

```<code> package="com.example.iusystem"
</code>```

Or move your activity the other way.

Body:
I keep getting this error when I try to run my android studio. I tried to copy, paste my previous project bit by bit. After I finished it I got this error. I'm really stuck on this one.

Thanks in advance :D

This is my Activity manifest

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.iussystem">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".TermsOfService"></activity>
        <activity android:name=".ForgotPassword" />
        <activity android:name=".Registracija" />
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Body:
If you are saying your app is in com/example/iusystem/MainActivity.java, isnt that a typo?

Either change your package:

 package="com.example.iussystem"

to

 package="com.example.iusystem"

Or move your activity the other way.


问:
No data getting to Google Analytics
GA Pro is not working on my website.

Below is the script in my site (GA account ID replaced with XXXXXXXX).

```<code><script type="text/javascript">
var s1 = new SWFObject("/player/player.swf","single","320","260","7");
s1.addParam("allowfullscreen","true");
s1.addParam("allowscriptaccess","always");
s1.addVariable("file","");
s1.addVariable("image","");
s1.addVariable("plugins","gapro-1");
s1.addVariable("gapro.accountid","UA-XXXXXXXX-1");
s1.addVariable("gapro.trackstarts","true");
s1.addVariable("gapro.trackpercentage","true");
s1.addVariable("gapro.tracktime","true");
s1.addVariable("gapro.idstring","||name||");
s1.write("player1");
</script>
</code>```

答:
The issue might be due to the fact that you've set gapro.idstring = ||name||, which likely isn't set in your playlist. You'll need to be sure to use an element from the list of playlist properties (http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/12536/configuration-options#pl...).

Additionally, there may be an issue where trackstarts, trackpercentage, and tracktime cause the plugin to work incorrectly so we don't recommend setting them to "true".

Finally, if you'd like to see what data is being sent to Google as-it-happens, open up a proxy like Firebug or Charles and verify that there are requests being made once you click play or finish the video.

Title: No data getting to Google Analytics


问:
Create a vector according to multiple conditions contained in vectors
Imagine I have this data.frame :

```<code>a <- c("Boy","Girl","Dog","Cat","Chair","Table")
b <- c(1:6)
df <- data.frame(a,b)
</code>```

I would like to create a third column groupings elements in the first column according to predefined vectors :

```<code>human <- c("Boy","Girl")
pet <- c("Dog","Cat")
object <- c("Chair","Table")
</code>```

With this wished result :

```<code>df$Type <- c("Human","Human","Animal","Animal","Object","Object")
</code>```

I managed to get it right for 2 groups but I don't know how to include the third one :

```<code>df$Type1 <- ifelse(df$a==human,"Human","Animal")
</code>```

答:
You could create a vector that links the specific types to the categories, and then subset this vector with your data frame. Like this:

```<code>a <- c("Boy","Girl","Dog","Cat","Chair","Table")
b <- c(1:6)
df <- data.frame(a,b,stringsAsFactors = F) #Note, the stringsAsFactors = F

links <- c(
  "Boy" = "Human",
  "Girl" = "Human",
  "Dog" = "Animal",
  "Cat" = "Animal",
  "Table" = "Object",
  "Chair" = "Object"
  )

df$Type <- links[df$a]
</code>```

Output:

```<code>> df
      a b   Type
1   Boy 1  Human
2  Girl 2  Human
3   Dog 3 Animal
4   Cat 4 Animal
5 Chair 5 Object
6 Table 6 Object
</code>```

Edit:

If there are a lot of values in human, pet, and object, my solution would require typing, e.g., ="human" repeatedly. Here's the a way to create the look-up table that is probably easier to scale

```<code>links_A <- c(
  "Boy" = "Human",
  "Girl" = "Human",
  "Dog" = "Animal",
  "Cat" = "Animal",
  "Chair" = "Object",
  "Table" = "Object"
  )

human <- c("Boy","Girl")
pet <- c("Dog","Cat")
object <- c("Chair","Table")

links_B <- rep(c("Human", "Animal", "Object"), times = lengths(list(human, pet, object)))
names(links_B) <- c(human, pet, object)

identical(links_A, links_B) # TRUE

</code>```

Body:
Imagine I have this data.frame :

a <- c("Boy","Girl","Dog","Cat","Chair","Table")
b <- c(1:6)
df <- data.frame(a,b)

I would like to create a third column groupings elements in the first column according to predefined vectors :

human <- c("Boy","Girl")
pet <- c("Dog","Cat")
object <- c("Chair","Table")

With this wished result :

df$Type <- c("Human","Human","Animal","Animal","Object","Object")

I managed to get it right for 2 groups but I don't know how to include the third one :

df$Type1 <- ifelse(df$a==human,"Human","Animal")

Body:
You could create a vector that links the specific types to the categories, and then subset this vector with your data frame. Like this:

a <- c("Boy","Girl","Dog","Cat","Chair","Table")
b <- c(1:6)
df <- data.frame(a,b,stringsAsFactors = F) #Note, the stringsAsFactors = F

links <- c(
  "Boy" = "Human",
  "Girl" = "Human",
  "Dog" = "Animal",
  "Cat" = "Animal",
  "Table" = "Object",
  "Chair" = "Object"
  )

df$Type <- links[df$a]

Output:

> df
      a b   Type
1   Boy 1  Human
2  Girl 2  Human
3   Dog 3 Animal
4   Cat 4 Animal
5 Chair 5 Object
6 Table 6 Object

Edit:

If there are a lot of values in human, pet, and object, my solution would require typing, e.g., ="human" repeatedly. Here's the a way to create the look-up table that is probably easier to scale

links_A <- c(
  "Boy" = "Human",
  "Girl" = "Human",
  "Dog" = "Animal",
  "Cat" = "Animal",
  "Chair" = "Object",
  "Table" = "Object"
  )

human <- c("Boy","Girl")
pet <- c("Dog","Cat")
object <- c("Chair","Table")

links_B <- rep(c("Human", "Animal", "Object"), times = lengths(list(human, pet, object)))
names(links_B) <- c(human, pet, object)

identical(links_A, links_B) # TRUE


问:
How to create static(hard coded) nested Array data in Typescript
I want to create multilevel dropdown list in Angular. For that I need static data of type below

```<code>Item1
Item2
    SubItem1
    SubItem2
Item3
Item4
    SubItem14
    SubItem15
Item5
</code>```

I Typescript, how can I create this data(hard coded) using array?

I have tried like this

```<code>public arrayname: string[] = ["Item1", "Item2", "Item3"];
</code>```

but that is not nested.

答:
You can use array of objects instead of array of string, like

```<code>interface Item {
    name: string;
    subItems: string[]
}

let dropdown: Item[] = [
{
    name: "Item1",
    subItems: []
},
{
    name: "Item2",
    subItems: ["SubItem1", "SubItem2"]
}
];
</code>```

Now you can traverse dropdown array to pupulate menu and for each item traverse subItems to populate submenu

Update :

```<code>interface Item {
    label: string;
    icon: string;
    link?: string;
    items?: Item[]
}

let dropdown = [
{
    label: "Item1",
    icon: " icon"
},
{
    label: "Item2",
    icon": " icon2",
    items: [
        {
            label: "subitem",
            icon: " icon",
            link: "link",
        }
    ]
}
];
</code>```

Now by this solution you can nest any no of times

Body:
I want to create multilevel dropdown list in Angular. For that I need static data of type below

Item1
Item2
    SubItem1
    SubItem2
Item3
Item4
    SubItem14
    SubItem15
Item5

I Typescript, how can I create this data(hard coded) using array?

I have tried like this

public arrayname: string[] = ["Item1", "Item2", "Item3"];

but that is not nested.

Body:
You can use array of objects instead of array of string, like

interface Item {
    name: string;
    subItems: string[]
}

let dropdown: Item[] = [
{
    name: "Item1",
    subItems: []
},
{
    name: "Item2",
    subItems: ["SubItem1", "SubItem2"]
}
];

Now you can traverse dropdown array to pupulate menu and for each item traverse subItems to populate submenu

Update :

interface Item {
    label: string;
    icon: string;
    link?: string;
    items?: Item[]
}

let dropdown = [
{
    label: "Item1",
    icon: " icon"
},
{
    label: "Item2",
    icon": " icon2",
    items: [
        {
            label: "subitem",
            icon: " icon",
            link: "link",
        }
    ]
}
];

Now by this solution you can nest any no of times


问:
Creating new column based on repeated consecutive row entries
Imagine a snippet of the follow data frame:

```<code>       ID        ActivityName     Time         Type    Shape
1       1             Request    0.000       Type_1      767
2       1             Request  600.000       Type_1      767
3       1               Start  600.000       Type_1     1376
4       1               Start  600.000       Type_1     1376
5       1               Delay 2962.295       Type_1     1022
6       1 Schedule Activities  600.000       Type_1       15
7       1 Schedule Activities 2062.295       Type_1       15
</code>```

What I'm trying to do is to create two new columns based on the repeating entries in ActivityName.

Specifically, I want to combine two subsequent rows for the same activity into one row with a start and complete timestamp (from Time, in seconds).

Given that not all entries in ActivityName have a matching second entry (however, max two consecutive entries are identical), I would also like to delete such rows, as Delay in this case.

It should then look something like:

```<code>       ID        ActivityName  StartTime   EndTime      Type    Shape
1       1             Request  0.000       600.000      Type_1  767
2       1               Start  600.000     600.000      Type_1  1375
3       1 Schedule Activities  600.000     2062.295     Type_1  15
</code>```

All categories in ActivityName occur many times in that column. I hope not to compare their associated Time not across the whole column, only those who have two consecutive identical occurrence.

Any ideas for how to go about this will be highly appreciated.

答:
Something like this?

```<code>df<-data.frame(activity_name = c("A", "A", "B", "B", "C", "C"),
               time = c(0,2,2,4,4,6))
df
</code>```

```<code>  activity_name time
1             A    0
2             A    2
3             B    2
4             B    4
5             C    4
6             C    6
</code>```

```<code>library(tidyverse)
df %>%
  group_by(activity_name) %>%
  summarise(StartTime = first(time),
            EndTime = last(time))
</code>```

```<code>  activity_name StartTime EndTime
  <fct>             <dbl>   <dbl>
1 A                     0       2
2 B                     2       4
3 C                     4       6
</code>```

Body:
Imagine a snippet of the follow data frame:

       ID        ActivityName     Time         Type    Shape
1       1             Request    0.000       Type_1      767
2       1             Request  600.000       Type_1      767
3       1               Start  600.000       Type_1     1376
4       1               Start  600.000       Type_1     1376
5       1               Delay 2962.295       Type_1     1022
6       1 Schedule Activities  600.000       Type_1       15
7       1 Schedule Activities 2062.295       Type_1       15

What I'm trying to do is to create two new columns based on the repeating entries in ActivityName.

Specifically, I want to combine two subsequent rows for the same activity into one row with a start and complete timestamp (from Time, in seconds).

Given that not all entries in ActivityName have a matching second entry (however, max two consecutive entries are identical), I would also like to delete such rows, as Delay in this case.

It should then look something like:

       ID        ActivityName  StartTime   EndTime      Type    Shape
1       1             Request  0.000       600.000      Type_1  767
2       1               Start  600.000     600.000      Type_1  1375
3       1 Schedule Activities  600.000     2062.295     Type_1  15

All categories in ActivityName occur many times in that column. I hope not to compare their associated Time not across the whole column, only those who have two consecutive identical occurrence.

Any ideas for how to go about this will be highly appreciated.

Body:
Something like this?

df<-data.frame(activity_name = c("A", "A", "B", "B", "C", "C"),
               time = c(0,2,2,4,4,6))
df

  activity_name time
1             A    0
2             A    2
3             B    2
4             B    4
5             C    4
6             C    6

library(tidyverse)
df %>%
  group_by(activity_name) %>%
  summarise(StartTime = first(time),
            EndTime = last(time))

  activity_name StartTime EndTime
  <fct>             <dbl>   <dbl>
1 A                     0       2
2 B                     2       4
3 C                     4       6


问:
How in store object to get access to parent vue page?
In my vue 2.6/cli 4/vuex 3.1 app I update some data in store vuex, like in src/store/index.js :

```<code>userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        self.$refs.userObserverForm.setErrors(error.body.errors)
    });
}, // userPropStore(context, userProp ) {
</code>```

and using ValidationProvider of vee-validate 3.2 I want to catch server errors (like not unique item)
but I got error :

```<code>index.js?4360:847 Uncaught (in promise) TypeError: Cannot read property 'userObserverForm' of undefined
</code>```

on line

```<code>self.$refs.userObserverForm.setErrors(error.body.errors)
</code>```

If there is a way in store object to get access to parent page, maybe with context, which has : https://imgur.com/a/P4St8Ri
?

Thanks!

答:
This is a very strange implementation.

Obviously self.$refs.userObserverForm.setErrors(error.body.errors) fails because you are NOT in a component, which is where $refs is available.

What you have to do in your catch block is setting the errors in Vuex and then make your component read from there.

Pseudocode follows:

I don't understand what your bus is doing... I guess you use it to send data to your component, but why use Vuex then?

```<code>userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
        commit('SET_USER_PROPS, data)
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        commit('SET_USER_PROPS_ERRORS', error.body.errors)
    });
}
</code>```

Body:
In my vue 2.6/cli 4/vuex 3.1 app I update some data in store vuex, like in src/store/index.js :

userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        self.$refs.userObserverForm.setErrors(error.body.errors)
    });
}, // userPropStore(context, userProp ) {

and using ValidationProvider of vee-validate 3.2 I want to catch server errors (like not unique item)
but I got error :

index.js?4360:847 Uncaught (in promise) TypeError: Cannot read property 'userObserverForm' of undefined

on line

self.$refs.userObserverForm.setErrors(error.body.errors)

If there is a way in store object to get access to parent page, maybe with context, which has : https://imgur.com/a/P4St8Ri
?

Thanks!

Body:
This is a very strange implementation.

Obviously self.$refs.userObserverForm.setErrors(error.body.errors) fails because you are NOT in a component, which is where $refs is available.

What you have to do in your catch block is setting the errors in Vuex and then make your component read from there.

Pseudocode follows:

I don't understand what your bus is doing... I guess you use it to send data to your component, but why use Vuex then?

userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
        commit('SET_USER_PROPS, data)
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        commit('SET_USER_PROPS_ERRORS', error.body.errors)
    });
}


问:
How to pass a limit parameter to an include using Jekyll's Liquid
I have a collection of projects on my site that I iterate over using {% for project in site.projects %} and store in an include called projects-list.html.

I would like to include the latest project from this collection on the homepage as a ‘featured’ item – is it possible to include the projects-list but pass in a limit:1 parameter so that only the first project is shown? Based on the Jekyll docs found here, I have tried passing the parameter to the include like this:

{% for project in site.projects limit:{{ include.limit }} %}

and refercing the include like this:

{% include projects-list.html limit=1 %}

but this does not appear to work. Is this a syntax error or am I missing something?

答:
You could try the first

```<code>{% assign projectFeatured = site.projects | first %}

{% for projects in site.projects %}
  {% include projects-list.html %}
{% endfor %}

{% for projects in projectFeatured %}
 {% include projects-list.html %}
{% endfor %}
</code>```

Though I encourage you to add a featured: True in your post and do something like that:

```<code>{% if post.featured == true %}

 {% include post.html %}

 {% endif %}
</code>```

https://shopify.github.io/liquid/filters/first/

Body:
You could try the first

{% assign projectFeatured = site.projects | first %}

{% for projects in site.projects %}
  {% include projects-list.html %}
{% endfor %}

{% for projects in projectFeatured %}
 {% include projects-list.html %}
{% endfor %}

Though I encourage you to add a featured: True in your post and do something like that:

{% if post.featured == true %}

 {% include post.html %}

 {% endif %}

https://shopify.github.io/liquid/filters/first/


问:
How can I print string array in java when method toString doesnt work?
I try to print the list of accounts but they appear as @164552...
I tried to call the toString method like Arrays.toString(accounts) but it doesnt compile.

It complains about static and the that it can not resolve method toString

```<code>import java.util.ArrayList;
import java.util.Arrays;

public class Customer {
    private String name;
    private String surname;
    private String personalNumber;
    private ArrayList<Account> accounts;

    public Customer(String customerName, String customerSurname,
                    String customerPersonalNumber) {
        this.name = customerName;
        this.surname = customerSurname;
        this.personalNumber = customerPersonalNumber;
        this.accounts = new ArrayList<Account>();
    }

    public Customer() {
    }

    public String getCustomerInfo() {
        return name + " " + surname + " " + personalNumber + accounts;
    }

    public ArrayList<Account> getAllAccounts() {
        return accounts;
    }

    public static void main(String[] arg) {
        Customer p = new Customer("Anna", "Larsson", "112323");
        p.addAccounts(new SavingsAccount());
        p.addAccounts(new SavingsAccount());
        System.out.println(Arrays.toString(accounts));
    }
}
</code>```

答:
You need to implement the toString method in your Account class, then you can do :

```<code>System.out.println(accounts);
</code>```

Body:
I try to print the list of accounts but they appear as @164552...
I tried to call the toString method like Arrays.toString(accounts) but it doesnt compile.

It complains about static and the that it can not resolve method toString

import java.util.ArrayList;
import java.util.Arrays;

public class Customer {
    private String name;
    private String surname;
    private String personalNumber;
    private ArrayList<Account> accounts;

    public Customer(String customerName, String customerSurname,
                    String customerPersonalNumber) {
        this.name = customerName;
        this.surname = customerSurname;
        this.personalNumber = customerPersonalNumber;
        this.accounts = new ArrayList<Account>();
    }

    public Customer() {
    }

    public String getCustomerInfo() {
        return name + " " + surname + " " + personalNumber + accounts;
    }

    public ArrayList<Account> getAllAccounts() {
        return accounts;
    }

    public static void main(String[] arg) {
        Customer p = new Customer("Anna", "Larsson", "112323");
        p.addAccounts(new SavingsAccount());
        p.addAccounts(new SavingsAccount());
        System.out.println(Arrays.toString(accounts));
    }
}

Body:
You need to implement the toString method in your Account class, then you can do :

System.out.println(accounts);


问:
Execute code on first emission of subscription while still being able to execute multiple times
I want to execute some code on first emission:

```<code>mySubscription
.pipe(
filter(res => res.loaded),
SomeRxjsOperator(res => //code to happen once))
.subscribe(res => {//code to happen on each emission});
</code>```

I know I can subscribe twice and use take(1), looking for a different solution.

答:
Try taking advantage of the index property in concatMap:

```<code>mySubscription.pipe(
  concatMap((value, index) => index === 0 ? of(value).pipe(
     tap(value => console.log(`will only be done once: ${value}`))
    ) : of(value)
  )
).subscribe(value => console.log(`subscription here: ${value}`));
</code>```

Body:
I want to execute some code on first emission:

mySubscription
.pipe(
filter(res => res.loaded),
SomeRxjsOperator(res => //code to happen once))
.subscribe(res => {//code to happen on each emission});

I know I can subscribe twice and use take(1), looking for a different solution.

Body:
Try taking advantage of the index property in concatMap:

mySubscription.pipe(
  concatMap((value, index) => index === 0 ? of(value).pipe(
     tap(value => console.log(`will only be done once: ${value}`))
    ) : of(value)
  )
).subscribe(value => console.log(`subscription here: ${value}`));


问:
Associate File Extension with Application
I've written a program that edits a specific filetype , and I want to give the user the option to set my application as the default editor for this filetype (since I don't want an installer) on startup.

I've tried to write a re-useable method that associates a file for me (preferably on any OS, although I'm running Vista) by adding a key to HKEY_CLASSES_ROOT, and am using it with my application, but it doesn't seem to work.

```<code>public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)
{
    RegistryKey BaseKey;
    RegistryKey OpenMethod;
    RegistryKey Shell;
    RegistryKey CurrentUser;

    BaseKey = Registry.ClassesRoot.CreateSubKey(Extension);
    BaseKey.SetValue("", KeyName);

    OpenMethod = Registry.ClassesRoot.CreateSubKey(KeyName);
    OpenMethod.SetValue("", FileDescription);
    OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + OpenWith + "\",0");
    Shell = OpenMethod.CreateSubKey("Shell");
    Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
    Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
    BaseKey.Close();
    OpenMethod.Close();
    Shell.Close();

    CurrentUser = Registry.CurrentUser.CreateSubKey(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" + Extension);
    CurrentUser = CurrentUser.OpenSubKey("UserChoice", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
    CurrentUser.SetValue("Progid", KeyName, RegistryValueKind.String);
    CurrentUser.Close();
}
</code>```

Any idea why it doesn't work? An example use might be

```<code>SetAssociation(".ucs", "UCS_Editor_File", Application.ExecutablePath, "UCS File");
</code>```

The part of the method that uses "CurrentUser" seems to work if I do the same using regedit, but using my application it doesn't.

答:
the actual way to associate your file extension with your own programm:

```<code>using Microsoft.Win32;
using System;
using System.IO;
using System.Runtime.InteropServices;

private static void RegisterForFileExtension(string extension, string applicationPath)
    {
        RegistryKey FileReg = Registry.CurrentUser.CreateSubKey("Software\\Classes\\" + extension);
        FileReg.CreateSubKey("shell\\open\\command").SetValue("", $"\"{applicationPath}\" \"%1\"");
        FileReg.Close();

        SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
    }
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
</code>```

EDIT: Thx, i changed the solution with your suggestion.

Body:
I've written a program that edits a specific filetype , and I want to give the user the option to set my application as the default editor for this filetype (since I don't want an installer) on startup.

I've tried to write a re-useable method that associates a file for me (preferably on any OS, although I'm running Vista) by adding a key to HKEY_CLASSES_ROOT, and am using it with my application, but it doesn't seem to work.

public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)
{
    RegistryKey BaseKey;
    RegistryKey OpenMethod;
    RegistryKey Shell;
    RegistryKey CurrentUser;

    BaseKey = Registry.ClassesRoot.CreateSubKey(Extension);
    BaseKey.SetValue("", KeyName);

    OpenMethod = Registry.ClassesRoot.CreateSubKey(KeyName);
    OpenMethod.SetValue("", FileDescription);
    OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + OpenWith + "\",0");
    Shell = OpenMethod.CreateSubKey("Shell");
    Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
    Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
    BaseKey.Close();
    OpenMethod.Close();
    Shell.Close();

    CurrentUser = Registry.CurrentUser.CreateSubKey(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" + Extension);
    CurrentUser = CurrentUser.OpenSubKey("UserChoice", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
    CurrentUser.SetValue("Progid", KeyName, RegistryValueKind.String);
    CurrentUser.Close();
}

Any idea why it doesn't work? An example use might be

SetAssociation(".ucs", "UCS_Editor_File", Application.ExecutablePath, "UCS File");

The part of the method that uses "CurrentUser" seems to work if I do the same using regedit, but using my application it doesn't.

Body:
the actual way to associate your file extension with your own programm:

using Microsoft.Win32;
using System;
using System.IO;
using System.Runtime.InteropServices;

private static void RegisterForFileExtension(string extension, string applicationPath)
    {
        RegistryKey FileReg = Registry.CurrentUser.CreateSubKey("Software\\Classes\\" + extension);
        FileReg.CreateSubKey("shell\\open\\command").SetValue("", $"\"{applicationPath}\" \"%1\"");
        FileReg.Close();

        SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
    }
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);

EDIT: Thx, i changed the solution with your suggestion.


问:
WooCommerce: Check if subcategory has specific parent category
I want to display content based on the current category and its parent category.
To do that, I need to know if the current category is a subcategory of a specific parent category.

For example, these are my categories:

Cars

Sportcars

Italian sportcars

Bikes

Dirtbikes

Japanese dirtbikes

I now want to display the content in on every category archive down the category tree.
In Cars, Sportcars and Italian sportcars for example.

For the first category I can use a Conditional Tag from WooCommerce:

```<code>is_product_category( 'cars' )
</code>```

But there is no in_product_category(). So I could not check, if the categegory "Italian sportcars" is a child of "Cars".

Is there any way to do that?

答:
You can check for parent category property on the child category object. A child category has a parent property that holds the ID of its parent category.
In your case the 'Italian sportcars' term object would have a parent property the points to the ID of 'Car' term.</p>

Body:
I want to display content based on the current category and its parent category.
To do that, I need to know if the current category is a subcategory of a specific parent category.

For example, these are my categories:

Cars

Sportcars

Italian sportcars

Bikes

Dirtbikes

Japanese dirtbikes

I now want to display the content in on every category archive down the category tree.
In Cars, Sportcars and Italian sportcars for example.

For the first category I can use a Conditional Tag from WooCommerce:

is_product_category( 'cars' )

But there is no in_product_category(). So I could not check, if the categegory "Italian sportcars" is a child of "Cars".

Is there any way to do that?


问:
PHP extracton foreach
Please can someone help me,I have the following array and would like to extract the data

```<code>
array(2) {
  [0]=>
  array(3) {
    ["from"]=>
    string(7) "coltest"
    ["to"]=>
    string(13) "+447000000000"
    ["body"]=>
    string(12) "Hello World!"
  }
  [1]=>
  array(3) {
    ["from"]=>
    string(8) "coltest2"
    ["to"]=>
    string(14) "+447000000001"
    ["body"]=>
    string(13) "Hello World2!"
  }
}
</code>```

I can extract the first one using

```<code>extract($array[0]);
echo("$from $to $body");

</code>```

But I would like to pass each $from, $to and $body to my suppliers API - I am guessing i need to write a foreach statement but I dont know where to begin

答:
If you want those separate variables in each iteration of a foreach loop, you can use list().

```<code>foreach (array as list($from, $to, $body)) {
    echo "$from $to $body";
}
</code>```

extract will also work in foreach, but I usually avoid using it. It can have unintended consequences if it's accidentally applied to the wrong thing, and it can potentially make it difficult to see where a variable came from when you're reading the code.

```<code>foreach (array as $item) {
    extract($item);
    echo "$from $to $body";
}
</code>```

But keep in mind you don't really need separate variables at all.

```<code>foreach (array as $item) {
    echo "$item[from] $item[to] $item[body]";
}
</code>```

By the way, echo is not a function, so you don't need to use parentheses with it.

Title: PHP extracton foreach

Body:
Please can someone help me,I have the following array and would like to extract the data

array(2) {
  [0]=>
  array(3) {
    ["from"]=>
    string(7) "coltest"
    ["to"]=>
    string(13) "+447000000000"
    ["body"]=>
    string(12) "Hello World!"
  }
  [1]=>
  array(3) {
    ["from"]=>
    string(8) "coltest2"
    ["to"]=>
    string(14) "+447000000001"
    ["body"]=>
    string(13) "Hello World2!"
  }
}

I can extract the first one using

extract($array[0]);
echo("$from $to $body");

But I would like to pass each $from, $to and $body to my suppliers API - I am guessing i need to write a foreach statement but I dont know where to begin

Body:
If you want those separate variables in each iteration of a foreach loop, you can use list().

foreach (array as list($from, $to, $body)) {
    echo "$from $to $body";
}

extract will also work in foreach, but I usually avoid using it. It can have unintended consequences if it's accidentally applied to the wrong thing, and it can potentially make it difficult to see where a variable came from when you're reading the code.

foreach (array as $item) {
    extract($item);
    echo "$from $to $body";
}

But keep in mind you don't really need separate variables at all.

foreach (array as $item) {
    echo "$item[from] $item[to] $item[body]";
}

By the way, echo is not a function, so you don't need to use parentheses with it.


问:
Editing the elements of a list in python 3
My question is kind of a two part question.

If you are given a list

```<code>numbers = [10, 20, 30, 100]
</code>```

and you wish to edit every element inside the list by adding 10 to each element. How would I go about doing this? And are you able to do this without creating a separate list?

Similarly, if you are given a list such as:

```<code>words = ['hello', 'hey', 'hi']
</code>```

and wish to change every letter h inside the list to another letter say 'r' would it be a similar algorithm as the last?

答:
Because you said you don't want to create a new list, you can't use list comprehension or map function as @gcandal suggested. You can try this instead.</p>

```<code>def update_list(l, fn):
    for i in range(len(l)):
        l[i] = fn(l[i])

update_list(numbers, lambda a: a + 10)
update_list(words, lambda s: s.replace('h', 'r'))
</code>```

Body:
My question is kind of a two part question.

If you are given a list

numbers = [10, 20, 30, 100]

and you wish to edit every element inside the list by adding 10 to each element. How would I go about doing this? And are you able to do this without creating a separate list?

Similarly, if you are given a list such as:

words = ['hello', 'hey', 'hi']

and wish to change every letter h inside the list to another letter say 'r' would it be a similar algorithm as the last?

Body:
Because you said you don't want to create a new list, you can't use list comprehension or map function as @gcandal suggested. You can try this instead.

def update_list(l, fn):
    for i in range(len(l)):
        l[i] = fn(l[i])

update_list(numbers, lambda a: a + 10)
update_list(words, lambda s: s.replace('h', 'r'))


问:
UIImageView is not scrolling inside a scrollView
I am creating a scrollview with a page control. I have a scrollview added to my viewcontroller and inside the scrollview there is a UIImageView. But for some reason I cannot scroll it to the left or right side. Can anyone help me out to fix this problem?

My Code:

```<code>    var tutorialImages: [String] = ["1", "2", "3"]
var frame = CGRect.zero

func pageControll() {
    pageControllTutorial.numberOfPages = tutorialImages.count

    for i in 0..<tutorialImages.count {

        imageViewTutorial.frame = frame
        imageViewTutorial.image = UIImage(named: tutorialImages[i])
        scrollViewTutorial.addSubview(imageViewTutorial)
    }

    scrollViewTutorial.contentSize = CGSize(width: imageViewTutorial.frame.size.width * CGFloat(tutorialImages.count), height: imageViewTutorial.frame.size.height)

    scrollViewTutorial.delegate = self
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
    pageControllTutorial.currentPage = Int(pageNumber)
}
</code>```

答:
With the little bit of code you've shown, you're doing a number of things wrong.

Based on this line:

```<code>imageViewTutorial.image = UIImage(named: tutorialImages[I])
</code>```

it looks like you have one UIImageView and you are setting its .image property 3 times, instead of creating 3 different image views.

Also, there is nothing in your code indicating how you are setting the frames of the image views.

I highly recommend using auto-layout instead of explicit frames - makes things much, much easier going forward.

Here is a complete example. It will create a square (1:1 ratio) scroll view 20-pts from the top with 20-pts padding on each side, and a UIPageControl below. It then adds a horizontal UIStackView to the scroll view. That stack view will hold the image views. Once the image views are added, the stack view will automatically define the "scrollable area" -- no need for calculating .contentSize.

Here's what it will look like:

Everything is done in code, so just assign the class of an empty view controller to SlidesExampleViewController ... no @IBOutlet or @IBAction connections needed.

```<code>class SlidesExampleViewController: UIViewController, UIScrollViewDelegate {

    lazy var pageControl: UIPageControl = {
        let v = UIPageControl()
        v.backgroundColor = .brown
        return v
    }()

    lazy var scrollView: UIScrollView = {
        let v = UIScrollView(frame: .zero)
        v.backgroundColor = .yellow
        v.delegate = self
        return v
    }()

    lazy var stackView: UIStackView = {
        let v = UIStackView()
        v.axis = .horizontal
        v.alignment = .fill
        v.distribution = .fill
        v.spacing = 0
        return v
    }()

    let tutorialImages: [String] = ["1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        scrollView.translatesAutoresizingMaskIntoConstraints = false
        stackView.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(scrollView)
        view.addSubview(pageControl)
        scrollView.addSubview(stackView)

        let v = view.safeAreaLayoutGuide
        let g = scrollView.contentLayoutGuide

        NSLayoutConstraint.activate([

            // constrain scroll view to top, leading, trailing with 20-pts "padding"
            scrollView.topAnchor.constraint(equalTo: v.topAnchor, constant: 20.0),
            scrollView.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: 20.0),
            scrollView.trailingAnchor.constraint(equalTo: v.trailingAnchor, constant: -20.0),

            // constrain scroll view height equal to scroll view width
            scrollView.heightAnchor.constraint(equalTo: scrollView.widthAnchor),

            // constrain stack view to all 4 sides of scroll view's contentLayoutGuide
            stackView.topAnchor.constraint(equalTo: g.topAnchor),
            stackView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
            stackView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: g.trailingAnchor),

            // constrain stack view height equal to scroll view height
            stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor),

            // constrain page control width to 80% of scroll view width
            pageControl.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 0.8),

            // constrain page control top to 8-pts below scroll view bottom
            pageControl.topAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 8.0),

            // constrain page control centerX to centerX of scroll view
            pageControl.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor, constant: 0.0),

        ])

        tutorialImages.forEach { name in
            if let img = UIImage(named: name) {
                let imgView = UIImageView(image: img)
                stackView.addArrangedSubview(imgView)
                imgView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
            }
        }

        pageControl.numberOfPages = tutorialImages.count

        scrollView.isPagingEnabled = true

    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
        pageControl.currentPage = Int(pageIndex)
    }
}
</code>```

Body:
I am creating a scrollview with a page control. I have a scrollview added to my viewcontroller and inside the scrollview there is a UIImageView. But for some reason I cannot scroll it to the left or right side. Can anyone help me out to fix this problem?

My Code:

    var tutorialImages: [String] = ["1", "2", "3"]
var frame = CGRect.zero

func pageControll() {
    pageControllTutorial.numberOfPages = tutorialImages.count

    for i in 0..<tutorialImages.count {

        imageViewTutorial.frame = frame
        imageViewTutorial.image = UIImage(named: tutorialImages[i])
        scrollViewTutorial.addSubview(imageViewTutorial)
    }

    scrollViewTutorial.contentSize = CGSize(width: imageViewTutorial.frame.size.width * CGFloat(tutorialImages.count), height: imageViewTutorial.frame.size.height)

    scrollViewTutorial.delegate = self
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
    pageControllTutorial.currentPage = Int(pageNumber)
}

Body:
With the little bit of code you've shown, you're doing a number of things wrong.

Based on this line:

imageViewTutorial.image = UIImage(named: tutorialImages[I])

it looks like you have one UIImageView and you are setting its .image property 3 times, instead of creating 3 different image views.

Also, there is nothing in your code indicating how you are setting the frames of the image views.

I highly recommend using auto-layout instead of explicit frames - makes things much, much easier going forward.

Here is a complete example. It will create a square (1:1 ratio) scroll view 20-pts from the top with 20-pts padding on each side, and a UIPageControl below. It then adds a horizontal UIStackView to the scroll view. That stack view will hold the image views. Once the image views are added, the stack view will automatically define the "scrollable area" -- no need for calculating .contentSize.

Here's what it will look like:

Everything is done in code, so just assign the class of an empty view controller to SlidesExampleViewController ... no @IBOutlet or @IBAction connections needed.

class SlidesExampleViewController: UIViewController, UIScrollViewDelegate {

    lazy var pageControl: UIPageControl = {
        let v = UIPageControl()
        v.backgroundColor = .brown
        return v
    }()

    lazy var scrollView: UIScrollView = {
        let v = UIScrollView(frame: .zero)
        v.backgroundColor = .yellow
        v.delegate = self
        return v
    }()

    lazy var stackView: UIStackView = {
        let v = UIStackView()
        v.axis = .horizontal
        v.alignment = .fill
        v.distribution = .fill
        v.spacing = 0
        return v
    }()

    let tutorialImages: [String] = ["1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        scrollView.translatesAutoresizingMaskIntoConstraints = false
        stackView.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(scrollView)
        view.addSubview(pageControl)
        scrollView.addSubview(stackView)

        let v = view.safeAreaLayoutGuide
        let g = scrollView.contentLayoutGuide

        NSLayoutConstraint.activate([

            // constrain scroll view to top, leading, trailing with 20-pts "padding"
            scrollView.topAnchor.constraint(equalTo: v.topAnchor, constant: 20.0),
            scrollView.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: 20.0),
            scrollView.trailingAnchor.constraint(equalTo: v.trailingAnchor, constant: -20.0),

            // constrain scroll view height equal to scroll view width
            scrollView.heightAnchor.constraint(equalTo: scrollView.widthAnchor),

            // constrain stack view to all 4 sides of scroll view's contentLayoutGuide
            stackView.topAnchor.constraint(equalTo: g.topAnchor),
            stackView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
            stackView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: g.trailingAnchor),

            // constrain stack view height equal to scroll view height
            stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor),

            // constrain page control width to 80% of scroll view width
            pageControl.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 0.8),

            // constrain page control top to 8-pts below scroll view bottom
            pageControl.topAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 8.0),

            // constrain page control centerX to centerX of scroll view
            pageControl.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor, constant: 0.0),

        ])

        tutorialImages.forEach { name in
            if let img = UIImage(named: name) {
                let imgView = UIImageView(image: img)
                stackView.addArrangedSubview(imgView)
                imgView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
            }
        }

        pageControl.numberOfPages = tutorialImages.count

        scrollView.isPagingEnabled = true

    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
        pageControl.currentPage = Int(pageIndex)
    }
}


问:
How to save csv or xlsx into S3 bucket?
Even though actual use case is to store the data within shiny session,
I have simplified to be clear on the goal.

Could you please help me understand what changes I need to make in order to save the Csv/xlsx into S3 bucket ?

Relevant but python
save a csv file into s3 bucket from pypark dataframe

```<code>library(tidyverse)
library(aws.s3)

# Authetication
aws.signature::use_credentials()
s3_bucket_link = # My s3 bucket link

  df = fread("mtcars.csv")

  #put object to s3
  aws.s3::put_object(object = "mtcars.csv",
                     file = "mtcars.csv",
                     bucket = s3_bucket_link)
  # Gives 403 or 404 error
  # But when I check my S3 bucket file isnt available !!!
</code>```

答:
```<code>library(tidyverse)
library(aws.s3)

# Authetication
aws.signature::use_credentials()
s3_bucket_link = # s3 bucket link
complete_path = # Complete S3 bucket path including folder within S3 bucket link

write.csv(mtcars,"mtcars.csv")

aws.s3::s3write_using(mtcars,
                      object = paste0(complete_path,"mtcars.csv"),
                      FUN = write.csv,
                      bucket = s3_bucket_link)
</code>```

Title: How to save csv or xlsx into S3 bucket?

Body:
Even though actual use case is to store the data within shiny session,
I have simplified to be clear on the goal.

Could you please help me understand what changes I need to make in order to save the Csv/xlsx into S3 bucket ?

Relevant but python
save a csv file into s3 bucket from pypark dataframe

library(tidyverse)
library(aws.s3)

# Authetication
aws.signature::use_credentials()
s3_bucket_link = # My s3 bucket link

  df = fread("mtcars.csv")

  #put object to s3
  aws.s3::put_object(object = "mtcars.csv",
                     file = "mtcars.csv",
                     bucket = s3_bucket_link)
  # Gives 403 or 404 error
  # But when I check my S3 bucket file isnt available !!!


问:
addClass to every div with data-attribute tag
How can I add CSS classes like widget-00, widget-01 etc. to each of these divs via jQuery?

```<code><div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="00">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="01">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="02">
<div class="mdl-form  mdl-color--white mdl-shadow--2dp mdl-cell mdl-grid mdl-cell--12-col" data-widget-id="03">
</code>```

答:
To achieve this you could use the attribute selector along with addClass(). If you provide a function to the latter then you can read the data-widget-id attribute value and use it in the class you apply to the element. Try this:

$('[data-widget-id]').addClass(function() {
  return `widget-${$(this).data('widget-id')}`;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mdl-form other-classes" data-widget-id="00">Foo</div>
<div class="mdl-form other-classes" data-widget-id="01">Bar</div>
<div class="mdl-form other-classes" data-widget-id="02">Fizz</div>
<div class="mdl-form other-classes" data-widget-id="03">Buzz</div></code>```

That said, it's worth noting that dynamically assigning classes at runtime is an anti-pattern. If you want to identify elements then you already have the widget-id you can select by, amongst other methods.

Body:
To achieve this you could use the attribute selector along with addClass(). If you provide a function to the latter then you can read the data-widget-id attribute value and use it in the class you apply to the element. Try this:

$('[data-widget-id]').addClass(function() {
  return `widget-${$(this).data('widget-id')}`;
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mdl-form other-classes" data-widget-id="00">Foo</div>
<div class="mdl-form other-classes" data-widget-id="01">Bar</div>
<div class="mdl-form other-classes" data-widget-id="02">Fizz</div>
<div class="mdl-form other-classes" data-widget-id="03">Buzz</div>

That said, it's worth noting that dynamically assigning classes at runtime is an anti-pattern. If you want to identify elements then you already have the widget-id you can select by, amongst other methods.


问:
How can I copy a line from a Richtextbox when I select it?
I am trying to automatically highlight and copy a single line from a rich text box and store it in a variable when I click on any part of the line.

Is this possible?

答:
The Click event and something like the following should help:

```<code>private void richTextBox1_Click(object sender, EventArgs e)
{
    int index = richTextBox1.SelectionStart;
    int line = richTextBox1.GetLineFromCharIndex(index);
    string lineText = (richTextBox1.Lines.Length > 0) ? richTextBox1.Lines[line] : "";

    //Debug output for my own testing purposes
    Debug.WriteLine(lineText);
}
</code>```

You may want to do something different when the RichTextBox is empty. I just use an empty string.

Here's an example of the output from a simple app:

The text show in the output window reflects the order in which I clicked the lines after typing.

However, one caveat to this is that you don't need to click exactly on the line for it to count. For example, clicking in the empty space below the last line registers as clicking the last line, because that's where the cursor ends up. It might not matter a whole lot, but it's something to be aware of.

Body:
The Click event and something like the following should help:

private void richTextBox1_Click(object sender, EventArgs e)
{
    int index = richTextBox1.SelectionStart;
    int line = richTextBox1.GetLineFromCharIndex(index);
    string lineText = (richTextBox1.Lines.Length > 0) ? richTextBox1.Lines[line] : "";

    //Debug output for my own testing purposes
    Debug.WriteLine(lineText);
}

You may want to do something different when the RichTextBox is empty. I just use an empty string.

Here's an example of the output from a simple app:

The text show in the output window reflects the order in which I clicked the lines after typing.

However, one caveat to this is that you don't need to click exactly on the line for it to count. For example, clicking in the empty space below the last line registers as clicking the last line, because that's where the cursor ends up. It might not matter a whole lot, but it's something to be aware of.