问:
python docx set table cell background and text color
I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.

I could not find any usefull resources about single cell formatting

Any suggestions?

Edit 1

my code

```<code>style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
    #V headinh se piše prvo polje iz table heada
    document.add_heading(rec['tableHead'][0][0], level=1)
    image_path = imageFolder + "\\" + slike[a]
    document.add_picture(image_path, height=Inches(3.5))

    #y += 28
    #worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])

    for i, head in enumerate(rec['tableHead']):
        table = document.add_table(rows=1, cols = len(head))
        hdr_cells = table.rows[0].cells
        for a in range(0,len(head)):
            hdr_cells[a].text = head[a]

    for a,body in enumerate(rec['tableData']):
        row_cells = table.add_row().cells

        for a in range(0,len(body)):
            if body[a]['style'] == 'footer':
                stil = style_footer
            elif body[a]['style'] == 'red':
                stil = style_red

            elif body[a]['style'] == 'yellow':
                stil = style_yellow
            elif body[a]['style'] == 'green':
                stil = style_green

            else:
                stil = style_transperent

            row_cells[a].add_paragraph(body[a]['value'], stil)

document.save(wordDoc)
</code>```

All cells are still the same.

答:
With Nikos Tavoularis' solution, we have to create a new element for every cell.
I have created a function that achieves this. Works in Python revision 3.5.6 and python-docx revision 0.8.10</p>
```<code>from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def set_table_header_bg_color(table.rows[row_ix].cell):
    """
    set background shading for Header Rows
    """
    tblCell = cell._tc
    tblCellProperties = tblCell.get_or_add_tcPr()
    clShading = OxmlElement('w:shd')
    clShading.set(qn('w:fill'), "00519E") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
    tblCellProperties.append(clShading)
    return cell
"""
End of set_table_header_bg_color Function
"""
# main function
"""
..
..
..
1. Load Document
..
2. Access the required section
..
3. Load the required Table
..
4. Traverse to the cell by accessing the rows object
..
"""
for each_row in table.rows :
    for each_cell in each_row.cells:
        if each_cell.value satisfies a condition:
            set_table_header_bg_color(each_cell)
"""
5. Continue execution
"""
</code>```

Body:
I am using python 2.7 with docx and I would like to change the background and text color of cells in my table based on condition.

I could not find any usefull resources about single cell formatting

Any suggestions?

Edit 1

my code

style_footer = "DarkList"
style_red = "ColorfulList"
style_yellow = "LightShading"
style_green = "MediumShading2-Accent6"
style_transperent = "TableNormal"
for a,rec in enumerate(data):
    #V headinh se piše prvo polje iz table heada
    document.add_heading(rec['tableHead'][0][0], level=1)
    image_path = imageFolder + "\\" + slike[a]
    document.add_picture(image_path, height=Inches(3.5))

    #y += 28
    #worksheet.insert_image( y, 1,imageFolder + "/" + slike[a])

    for i, head in enumerate(rec['tableHead']):
        table = document.add_table(rows=1, cols = len(head))
        hdr_cells = table.rows[0].cells
        for a in range(0,len(head)):
            hdr_cells[a].text = head[a]

    for a,body in enumerate(rec['tableData']):
        row_cells = table.add_row().cells

        for a in range(0,len(body)):
            if body[a]['style'] == 'footer':
                stil = style_footer
            elif body[a]['style'] == 'red':
                stil = style_red

            elif body[a]['style'] == 'yellow':
                stil = style_yellow
            elif body[a]['style'] == 'green':
                stil = style_green

            else:
                stil = style_transperent

            row_cells[a].add_paragraph(body[a]['value'], stil)

document.save(wordDoc)

All cells are still the same.

Body:
With Nikos Tavoularis' solution, we have to create a new element for every cell.
I have created a function that achieves this. Works in Python revision 3.5.6 and python-docx revision 0.8.10

from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def set_table_header_bg_color(table.rows[row_ix].cell):
    """
    set background shading for Header Rows
    """
    tblCell = cell._tc
    tblCellProperties = tblCell.get_or_add_tcPr()
    clShading = OxmlElement('w:shd')
    clShading.set(qn('w:fill'), "00519E") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
    tblCellProperties.append(clShading)
    return cell
"""
End of set_table_header_bg_color Function
"""
# main function
"""
..
..
..
1. Load Document
..
2. Access the required section
..
3. Load the required Table
..
4. Traverse to the cell by accessing the rows object
..
"""
for each_row in table.rows :
    for each_cell in each_row.cells:
        if each_cell.value satisfies a condition:
            set_table_header_bg_color(each_cell)
"""
5. Continue execution
"""


来源: stackexchange

问:
Trying to run a update query for access tables using VBA
i am just a beginner in Vba. i am able to get the select query results using recordset. But while i am trying to run the below update query code i am facing issue near execution part. i am getting  Run time error -2147217904(80040e10), No value given for one or more required parameters. Can anyone help me with this.</p>

```<code>Sub Button8_Click()
Dim cmd As New ADODB.Connection

Dim Path As String

Path = "C:\Users\Documents\"

cmd.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & "Productivity_Tracker.accdb"

For Each chkbx In ActiveSheet.CheckBoxes
    If chkbx.Value = 1 Then
        For r = 1 To Rows.Count
            If Cells(r, 1).Top = chkbx.Top Then
                'With Worksheets("Sheet2")
                    'LRow = .Range("A" & Rows.Count).End(xlUp).Row + 1
                    '.Range("A" & LRow & ":D" & LRow) =

                     'Sheet3.Range("A" & r & ":F" & r).Value
                     Dim alloc_per As Integer
                     Dim emp_id As Integer
                     Dim proj_id As Integer
                     alloc_per = Sheet3.Range("E" & r).Value
                     emp_id = Sheet3.Range("A" & r).Value
                     proj_id = Sheet3.Range("B" & r).Value
                qry = "UPDATE Employee_Project_Assignment SET Employee_Project_Assignment.Allocation_Percentage = alloc_per WHERE Employee_Project_Assignment.Employee_ID = emp_id and Employee_Project_Assignment.Project_ID = proj_id"

              cmd.Execute qry

                'Exit For
            End If
        Next r
    End If
Next

Dim recordsChanged As Integer
    cmd.Execute (recordsChanged)
    If recordsChanged > 0 Then
        Console.WriteLine ("Update succesfull")
   End If

End Sub
</code>```

答:
You are passing literal strings "alloc_per" etc in your SQL, instead of the values held in those variables.

Try this:

```<code>qry = " UPDATE Employee_Project_Assignment t SET " & _
      " t.Allocation_Percentage = " & alloc_per & " WHERE " & _
      " t.Employee_ID = " & emp_id & " and " & _
      " t.Project_ID = " & proj_id
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i am just a beginner in Vba. i am able to get the select query results using recordset. But while i am trying to run the below update query code i am facing issue near execution part. i am getting  Run time error -2147217904(80040e10), No value given for one or more required parameters. Can anyone help me with this.

Sub Button8_Click()
Dim cmd As New ADODB.Connection

Dim Path As String

Path = "C:\Users\Documents\"

cmd.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path & "Productivity_Tracker.accdb"

For Each chkbx In ActiveSheet.CheckBoxes
    If chkbx.Value = 1 Then
        For r = 1 To Rows.Count
            If Cells(r, 1).Top = chkbx.Top Then
                'With Worksheets("Sheet2")
                    'LRow = .Range("A" & Rows.Count).End(xlUp).Row + 1
                    '.Range("A" & LRow & ":D" & LRow) =

                     'Sheet3.Range("A" & r & ":F" & r).Value
                     Dim alloc_per As Integer
                     Dim emp_id As Integer
                     Dim proj_id As Integer
                     alloc_per = Sheet3.Range("E" & r).Value
                     emp_id = Sheet3.Range("A" & r).Value
                     proj_id = Sheet3.Range("B" & r).Value
                qry = "UPDATE Employee_Project_Assignment SET Employee_Project_Assignment.Allocation_Percentage = alloc_per WHERE Employee_Project_Assignment.Employee_ID = emp_id and Employee_Project_Assignment.Project_ID = proj_id"

              cmd.Execute qry

                'Exit For
            End If
        Next r
    End If
Next

Dim recordsChanged As Integer
    cmd.Execute (recordsChanged)
    If recordsChanged > 0 Then
        Console.WriteLine ("Update succesfull")
   End If

End Sub

Body:
You are passing literal strings "alloc_per" etc in your SQL, instead of the values held in those variables.

Try this:

qry = " UPDATE Employee_Project_Assignment t SET " & _
      " t.Allocation_Percentage = " & alloc_per & " WHERE " & _
      " t.Employee_ID = " & emp_id & " and " & _
      " t.Project_ID = " & proj_id


问:
React Authentication Context being null initially
I'm using React contexts in order to hold my authentication state for my application. Currently, I'm having an issue where whenever I try and hit /groups/:id, it always redirects me to /login first and then to /UserDash. This is happening because the context of my AuthProvider isn't updating fast enough, and my Private Route utilized the AuthContext to decide whether to redirect or not.

```<code><AuthProvider>
    <Router>
        <Switch>
            <LoggedRoute exact path = "/" component = {Home}/>
            <Route exact path = "/login" component = {Login}/>
            <PrivateRoute exact path = "/groups/:id" component = {GroupDash}/>
            <PrivateRoute exact path = "/UserDash" component = {UserDash}/>
        </Switch>
    </Router>
</AuthProvider>
</code>```

In another file:

```<code>export const AuthContext = React.createContext();

export const AuthProvider = ({children}) => {
  const [currentUser, setCurrentUser] = useState(null);
  useEffect(() => {
      firebaseApp.auth().onAuthStateChanged(setCurrentUser);
  },[]);
    return (
        <AuthContext.Provider
            value = {{currentUser}}
        >
            {children}
        </AuthContext.Provider>
    );
</code>```

My private route:

```<code>const PrivateRoute = ({component: RouteComponent, ...rest}) => {
    const {currentUser} = useContext((context) => AuthContext);
    return (
        <Route
            {...rest}
            render={routeProps => (currentUser) ? (<RouteComponent{...routeProps}/>) : (<Redirect to={"/login"}/>)}
        />
    )
};
</code>```

And my login page

```<code> const {currentUser} = useContext(AuthContext);
    if (currentUser) {
        return <Redirect to = "/UserDash" />
    }
    return (
        <button onClick={(e) => {googleLogin(history)}}>Log In</button>
    );
</code>```

Is there any way to force the context to load before the private route redirects the user to the login page? I've tried using firebase.auth().currentUser inside my PrivateRoute instead, but that also fails and I still get redirected to "/login", before getting pushed to "/UserDash".

答:
Since useEffect runs after a render and the value being fetched in useEffect is from a async call what can do is to actually maintain a loading state till data is available like

```<code>export const AuthContext = React.createContext();

export const AuthProvider = ({children}) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
      firebaseApp.auth().onAuthStateChanged((user) => {
          setCurrentUser(); setIsLoading(false)
      });
  },[]);
    return (
        <AuthContext.Provider
            value = {{currentUser, isLoading}}
        >
            {children}
        </AuthContext.Provider>
    );
  }
</code>```

Then in privateRoute

```<code>const PrivateRoute = ({component: RouteComponent, ...rest}) => {
    const {currentUser, isLoading} = useContext((context) => AuthContext);
    if(isLoading) return <div>Loading...</div>
    return (
        <Route
            {...rest}
            render={routeProps => (currentUser) ? (<RouteComponent{...routeProps}/>) : (<Redirect to={"/login"}/>)}
        />
    )
};
</code>```

Body:
I'm using React contexts in order to hold my authentication state for my application. Currently, I'm having an issue where whenever I try and hit /groups/:id, it always redirects me to /login first and then to /UserDash. This is happening because the context of my AuthProvider isn't updating fast enough, and my Private Route utilized the AuthContext to decide whether to redirect or not.

<AuthProvider>
    <Router>
        <Switch>
            <LoggedRoute exact path = "/" component = {Home}/>
            <Route exact path = "/login" component = {Login}/>
            <PrivateRoute exact path = "/groups/:id" component = {GroupDash}/>
            <PrivateRoute exact path = "/UserDash" component = {UserDash}/>
        </Switch>
    </Router>
</AuthProvider>

In another file:

export const AuthContext = React.createContext();

export const AuthProvider = ({children}) => {
  const [currentUser, setCurrentUser] = useState(null);
  useEffect(() => {
      firebaseApp.auth().onAuthStateChanged(setCurrentUser);
  },[]);
    return (
        <AuthContext.Provider
            value = {{currentUser}}
        >
            {children}
        </AuthContext.Provider>
    );

My private route:

const PrivateRoute = ({component: RouteComponent, ...rest}) => {
    const {currentUser} = useContext((context) => AuthContext);
    return (
        <Route
            {...rest}
            render={routeProps => (currentUser) ? (<RouteComponent{...routeProps}/>) : (<Redirect to={"/login"}/>)}
        />
    )
};

And my login page

 const {currentUser} = useContext(AuthContext);
    if (currentUser) {
        return <Redirect to = "/UserDash" />
    }
    return (
        <button onClick={(e) => {googleLogin(history)}}>Log In</button>
    );

Is there any way to force the context to load before the private route redirects the user to the login page? I've tried using firebase.auth().currentUser inside my PrivateRoute instead, but that also fails and I still get redirected to "/login", before getting pushed to "/UserDash".

Body:
Since useEffect runs after a render and the value being fetched in useEffect is from a async call what can do is to actually maintain a loading state till data is available like

export const AuthContext = React.createContext();

export const AuthProvider = ({children}) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
      firebaseApp.auth().onAuthStateChanged((user) => {
          setCurrentUser(); setIsLoading(false)
      });
  },[]);
    return (
        <AuthContext.Provider
            value = {{currentUser, isLoading}}
        >
            {children}
        </AuthContext.Provider>
    );
  }

Then in privateRoute

const PrivateRoute = ({component: RouteComponent, ...rest}) => {
    const {currentUser, isLoading} = useContext((context) => AuthContext);
    if(isLoading) return <div>Loading...</div>
    return (
        <Route
            {...rest}
            render={routeProps => (currentUser) ? (<RouteComponent{...routeProps}/>) : (<Redirect to={"/login"}/>)}
        />
    )
};


问:
instantiating a class from another class in Python
I was looking at linked list program in Python
I did'nt quite understand it.

I would appreciate if you help me on it.

Im pasting a part of code here, to simplify and understand one functionality

```<code>class node:

    def __init__(self,data,nnext=None):
        self.data = data
        self.nnext = nnext

class linkedList:
    def __init__(self):
        self.head = None

    def insertion(self,data):
        myinsertobj = node(data)
</code>```

Here
1. We have created a class for a node.
2. We created another class with a single head node.
3. In second class we have written a method for inserting. In the insertion() method, we are creating an object to the first class.

Now what I dont understand is,
how to create object for the second class i.e linkedList class and how to call the insertion() Method,considering the above code only.(I don't want to use helper method yet)

Please help me understand it, as Im new to Python and trying to learn it.
The complete code is @ ==> https://www.educative.io/edpresso/how-to-create-a-linked-list-in-python

Also, Please suggest me few references for data structures in simple way.

答:
Given the code you posted, in order to create an object for the second class, you would call

```<code>obj1 = linkedList()
</code>```

where obj1 is now and instance of the linked list class.

To insert a node into obj1 you call the insertion method like so

```<code>obj1.insertion(data)
</code>```

where data can be anything you want to insert.

Body:
I was looking at linked list program in Python
I did'nt quite understand it.

I would appreciate if you help me on it.

Im pasting a part of code here, to simplify and understand one functionality

class node:

    def __init__(self,data,nnext=None):
        self.data = data
        self.nnext = nnext

class linkedList:
    def __init__(self):
        self.head = None

    def insertion(self,data):
        myinsertobj = node(data)

Here
1. We have created a class for a node.
2. We created another class with a single head node.
3. In second class we have written a method for inserting. In the insertion() method, we are creating an object to the first class.

Now what I dont understand is,
how to create object for the second class i.e linkedList class and how to call the insertion() Method,considering the above code only.(I don't want to use helper method yet)

Please help me understand it, as Im new to Python and trying to learn it.
The complete code is @ ==> https://www.educative.io/edpresso/how-to-create-a-linked-list-in-python

Also, Please suggest me few references for data structures in simple way.

Body:
Given the code you posted, in order to create an object for the second class, you would call

obj1 = linkedList()

where obj1 is now and instance of the linked list class.

To insert a node into obj1 you call the insertion method like so

obj1.insertion(data)

where data can be anything you want to insert.


问:
javascript enter number of seconds - not less than zero
i am facing an issue in javascript. i want to do user enter number of seconds in input field.
but the condition is that users can't enter number of seconds less than zero.

how can a make the code logic?

function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <label for="seconds">Number of seconds:</label>
  <input type="number" id="seconds" name="seconds">
  <button onclick="sec()">Click</button>
</form></code>```

what should i do? anyone help me?

答:
Add your expectation about the input value as attributes on your input:

Specifically required min="0" would meet your needs.

function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <label for="seconds">Number of seconds:</label>
  <input type="number" id="seconds" name="seconds" required min="0">
  <button onclick="sec()">Click</button>
</form></code>```

Body:
i am facing an issue in javascript. i want to do user enter number of seconds in input field.
but the condition is that users can't enter number of seconds less than zero.

how can a make the code logic?

function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}

<form>
  Number of seconds:
  <input type="number" id="seconds" name="seconds">
  <button onclick="sec()">Click</button>
</form>

what should i do? anyone help me?

Body:
Add your expectation about the input value as attributes on your input:

Specifically required min="0" would meet your needs.

function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}

<form>
  <label for="seconds">Number of seconds:</label>
  <input type="number" id="seconds" name="seconds" required min="0">
  <button onclick="sec()">Click</button>
</form>


问:
How to include moment Js in Lightning Web Component? I have used the below code
```<code>import moment from '@salesforce/resourceUrl/XXX';
import { loadScript } from 'lightning/platformResourceLoader';

    export default class ProjectActivity extends LightningElement {
    connectedCallback(){
    Promise.all([
        loadScript(this, moment + '/js/moment.js')
        ]);
        this.loadActivities();
    }
    loadActivities(){
        let eventStartDate = moment(new Date()).format('YYYY-MM-DD');
    }
}
</code>```

答:
Your problem is that your loadActivities does not wait for moment to actually load.

What you need to do is:

```<code>connectedCallback(){
    Promise.all([
          loadScript(this, moment + '/js/moment.js')
        ]).then(() => {
          this.loadActivities();
      });
    }
</code>```

Body:
Your problem is that your loadActivities does not wait for moment to actually load.

What you need to do is:

connectedCallback(){
    Promise.all([
          loadScript(this, moment + '/js/moment.js')
        ]).then(() => {
          this.loadActivities();
      });
    }


问:
How to get value from object in php
I need to get the value of [text] from all these object - class.

I can get values from arrays But from these class object thing in array ,I am unable to get the values of [text].

Any help would be greatly appreciated.

```<code>Array
(
 [0] => stdClass Object
 (
    [text] => time
    [tr] => Array
    (
        [0] => stdClass Object
        (
            [text] => while
            [syn] => Array
            (
                [0] => stdClass Object
                (
                    [text] => when
                )
            )
        )
        [1] => stdClass Object
        (
            [text] => occasion
            [syn] => Array
            (
                [0] => stdClass Object
                (
                    [text] => moment
                )
                [1] => stdClass Object
                    (
                        [text] => day
                    )
                    [2] => stdClass Object
                        (
                            [text] => date
                        )
                )
            )
        )
    )
)
</code>```

答:
It's not the most elegant solution but something like this should do the trick:

```<code><?php
$data = [
    [
        'text' => 'time',
        'tr' => [
            'text' => 'while',
            'syn' => [
                'text' => 'when'
            ],
            [
                'text' => 'occasion',
                'syn' => [
                    [
                        'text' => 'moment'
                    ],
                    [
                        'text' => 'day'
                    ],
                    [
                        'text' => 'date'
                    ]
                ]
            ]
        ]
    ]
];

$data = json_decode(json_encode($data));

function recurseProperties($object) {
    $text = [];
    foreach ($object as $property => $value) {
        if ($property === 'text') {
            echo $property . '  =>  ' . $value . "\n";
            $text[] = $value;
        } else {
            $text = array_merge($text, recurseProperties($value));
        }
    }
    return $text;
}

function extractText($data) {
    $text = [];
    foreach ($data as $object) {
        $text = array_merge($text, recurseProperties($object));
    }

    return $text;
}

var_dump(extractText($data));
</code>```

Alternatively if you are comfortable working with arrays and it is a json source, you can just do:

```<code>  json_decode($jsonString, true)
</code>```

Which will convert it to an associative array see: https://www.php.net/manual/en/function.json-decode.php

Title: How to get value from object in php

Body:
I need to get the value of [text] from all these object - class.

I can get values from arrays But from these class object thing in array ,I am unable to get the values of [text].

Any help would be greatly appreciated.

Array
(
 [0] => stdClass Object
 (
    [text] => time
    [tr] => Array
    (
        [0] => stdClass Object
        (
            [text] => while
            [syn] => Array
            (
                [0] => stdClass Object
                (
                    [text] => when
                )
            )
        )
        [1] => stdClass Object
        (
            [text] => occasion
            [syn] => Array
            (
                [0] => stdClass Object
                (
                    [text] => moment
                )
                [1] => stdClass Object
                    (
                        [text] => day
                    )
                    [2] => stdClass Object
                        (
                            [text] => date
                        )
                )
            )
        )
    )
)

Body:
It's not the most elegant solution but something like this should do the trick:

<?php
$data = [
    [
        'text' => 'time',
        'tr' => [
            'text' => 'while',
            'syn' => [
                'text' => 'when'
            ],
            [
                'text' => 'occasion',
                'syn' => [
                    [
                        'text' => 'moment'
                    ],
                    [
                        'text' => 'day'
                    ],
                    [
                        'text' => 'date'
                    ]
                ]
            ]
        ]
    ]
];

$data = json_decode(json_encode($data));

function recurseProperties($object) {
    $text = [];
    foreach ($object as $property => $value) {
        if ($property === 'text') {
            echo $property . '  =>  ' . $value . "\n";
            $text[] = $value;
        } else {
            $text = array_merge($text, recurseProperties($value));
        }
    }
    return $text;
}

function extractText($data) {
    $text = [];
    foreach ($data as $object) {
        $text = array_merge($text, recurseProperties($object));
    }

    return $text;
}

var_dump(extractText($data));

Alternatively if you are comfortable working with arrays and it is a json source, you can just do:

  json_decode($jsonString, true)

Which will convert it to an associative array see: https://www.php.net/manual/en/function.json-decode.php


问:
How to use selenium module?
This is what I have so far. I want to open the instagram using selenium</p>

```<code>#code should be inside three backticks
from selenium import webdriver

class InstaBot:
    def __init__(self):
        self.driver = webdriver.chrome()
        self.driver.get("https://instagram.com")

InstaBot()
</code>```

答:
I think you don't have the chromewebdriver

Install Webdriver manager using pip command

pip install webdriver-manager

```<code>from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
class InstaBot:
    def __init__(self):
        self.driver = webdriver.Chrome(ChromeDriverManager().install())
        self.driver.get("https://instagram.com")
InstaBot()
</code>```

Title: How to use selenium module?

Body:
This is what I have so far. I want to open the instagram using selenium

#code should be inside three backticks
from selenium import webdriver

class InstaBot:
    def __init__(self):
        self.driver = webdriver.chrome()
        self.driver.get("https://instagram.com")

InstaBot()

Body:
I think you don't have the chromewebdriver

Install Webdriver manager using pip command

pip install webdriver-manager

from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
class InstaBot:
    def __init__(self):
        self.driver = webdriver.Chrome(ChromeDriverManager().install())
        self.driver.get("https://instagram.com")
InstaBot()


问:
Qt: Storing a custom object in a collection by value
Let's say I have this class:

```<code>class Bear
{
public:
    Bear ();
    Bear (Bear &other);

    // ... methods

private:
    BearInfo* m_pInfo;
};
</code>```

Can I store Bear objects in a QList<Bear> by value?  According to the documentation:

Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a
  pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared
  classes, then QList<T> stores the items directly in the pointer array.

While my class just consists of a pointer, it is neither a pointer type nor a basic type, so it seems to me that the QList will store pointers (Bear*), which is not what I want. And since the BearInfo structure must be mutable, I cannot derive Bear from QSharedDataPointer.

Any suggestions how I can enable this class to be stored by value in the Qt collections?

答:
Can I store Bear objects in a
  QList<Bear> by value?

No.  Your quote from the documentation was correct:  Internally, QList<T> stores pointers to items of type T.

Instead, use QVector, which stores objects by value of type larger than a pointer (that is its purpose).

A similar issue with items in QList<> are issues with containment by QVariant, which holds any primitive type, or some other small types (like QDate).  So, you get value semantics in QVariant only if your value fits into a primitive or a pointer.

Full containment would be achieved if you had a container of objects like QPointer or QSharedPointer instances, which logically share-and-track references to (reference counted) objects, etc.

Unlike STL (with value semantics), Qt leans on containers of "pointers-to-items" because of problems when those items are polymorphic (different sizes in derived classes).  (This is quite common in object oriented systems, which is why Qt defaults to pointer semantics.)

For example, in Qt, QList<Bear> is fine (implemented as a container of pointers-to-Bear instances), but the std::list<Bear> would be problematic when all Bear instances are not the same size (for example, if KodiakBear and BlackBear derived from Bear, and you added those derived instances to the std::list<Bear> class).  In that case, the derived state would be "stripped" through value semantics.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have this class:

class Bear
{
public:
    Bear ();
    Bear (Bear &other);

    // ... methods

private:
    BearInfo* m_pInfo;
};

Can I store Bear objects in a QList<Bear> by value?  According to the documentation:

Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a
  pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared
  classes, then QList<T> stores the items directly in the pointer array.

While my class just consists of a pointer, it is neither a pointer type nor a basic type, so it seems to me that the QList will store pointers (Bear*), which is not what I want. And since the BearInfo structure must be mutable, I cannot derive Bear from QSharedDataPointer.

Any suggestions how I can enable this class to be stored by value in the Qt collections?


问:
Pushing to GitHub, how to replace config file with sensitive information?
I have a project with SETTINGS.ini config file which has sensitive information which I obviously don't want to include in GitHub repository. I know that .gitignore will not push it to remote repository, but I am wondering how can I replace SETTINGS.ini with some other SETTINGS.ini file without manually removing it in remote repository?</p>

答: Best practice would be to place SETTINGS.ini.sample (or similarly named) file in your repository, with some dummy values in it, and include instructions to copy that file as SETTINGS.ini with correct values for whoever is using it. Keep SETTINGS.ini in gitignore.</p>


问:
Python TypeError - : 'str' object is not callable
This is my code.

```<code>n1, n2 = (int(input("Enter number: ")) for _ in range(2))
print("Select Your Choice: ")
print(" 1: Addition",
       "2: Substraction",
       "3: Multiplication",
       "4: Division")
choice = int(input())

switcher = {
        1: "Addition",
        2: "Substraction",
        3: "Multiplication",
        4: "Division",
    }
def addition(n1,n2):
    n1 += n2
    return n1

def substraction(n1,n2):
    n1 -= n2
    return n1

def multiplication(n1,n2):
    n1 *= n2
    return n1

def division(n1,n2):
    n1 /= n2
    return n1

def calculator(choice,n1,n2):
    return switcher.get(choice,"Invalid")(n1,n2)

print(calculator(choice,n1,n2))
</code>```

I got below error.

```<code>> Traceback (most recent call last):
> simple calculator with dictionary.py", line 36, in <module>
> print(calculator(choice,n1,n2))
> simple calculator with dictionary.py", line 34, in calculator

> > return switcher.get(choice,"Invalid")(n1,n2)
> TypeError: 'str' object is not callable
</code>```

Can anyone solve this error?

答:
The values in switcher have to be the functions you defined, not strings.

```<code>switcher = {
    1: addition,
    2: substraction,
    3: multiplication,
    4: division,
}
</code>```

Put this initialization of switcher after the definition of your functions.

You'll still get the "string not callable" error for invalid inputs, because

```<code>"Invalid"(n1, n2)
</code>```

is not a valid function call. Adjust calculator to do something else for invalid inputs.

Body:
This is my code.

n1, n2 = (int(input("Enter number: ")) for _ in range(2))
print("Select Your Choice: ")
print(" 1: Addition",
       "2: Substraction",
       "3: Multiplication",
       "4: Division")
choice = int(input())

switcher = {
        1: "Addition",
        2: "Substraction",
        3: "Multiplication",
        4: "Division",
    }
def addition(n1,n2):
    n1 += n2
    return n1

def substraction(n1,n2):
    n1 -= n2
    return n1

def multiplication(n1,n2):
    n1 *= n2
    return n1

def division(n1,n2):
    n1 /= n2
    return n1

def calculator(choice,n1,n2):
    return switcher.get(choice,"Invalid")(n1,n2)

print(calculator(choice,n1,n2))

I got below error.

> Traceback (most recent call last):
> simple calculator with dictionary.py", line 36, in <module>
> print(calculator(choice,n1,n2))
> simple calculator with dictionary.py", line 34, in calculator

> > return switcher.get(choice,"Invalid")(n1,n2)
> TypeError: 'str' object is not callable

Can anyone solve this error?

Body:
The values in switcher have to be the functions you defined, not strings.

switcher = {
    1: addition,
    2: substraction,
    3: multiplication,
    4: division,
}

Put this initialization of switcher after the definition of your functions.

You'll still get the "string not callable" error for invalid inputs, because

"Invalid"(n1, n2)

is not a valid function call. Adjust calculator to do something else for invalid inputs.


问:
image src get lost when submitted in ckeditor5
I used simple custom MyUploadAdapter following the ckeditor5 online document.

Images show up from both copy-paste and file upload dialog, and uploaded to the server. But once clicked save the textarea content to my server, the image src is empty, shown as:

```<code><figure class="image"><img></figure>

<figure class="image"><img src="" alt="16 Days of Activism | The Rose Campaign - Women in Crisis"></figure>
</code>```

The libray I am using:
https://cdn.ckeditor.com/ckeditor5/19.0.0/classic/ckeditor.js

Here are the codes:

```<code>function synchValues()
{
/*
    for(var instanceName in CKEDITOR.instances)
        CKEDITOR.instances[instanceName].updateElement();
CKEDITOR.on('instanceReady', function(){
   $.each( CKEDITOR.instances, function(instance) {
    CKEDITOR.instances[instance].on("change", function(e) {
        for ( instance in CKEDITOR.instances )
        CKEDITOR.instances[instance].updateElement();
    });
   });
});

    document.getElementById('editor').value = editor.getData();
*/

$('textarea.editor').each(function () {
   var $textarea = $(this);
   $textarea.val(CKEDITOR.instances[$textarea.attr('name')].getData());
});

    return true;
}

function MyCustomUploadAdapterPlugin( editor ) {

    editor.plugins.get( 'FileRepository' ).createUploadAdapter = ( loader ) => {
        // Configure the URL to the upload script in your back-end here!
        return new MyUploadAdapter( loader );
    };
}

let editor;

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        extraPlugins: [ MyCustomUploadAdapterPlugin ],

        styles: [
            // This option is equal to a situation where no style is applied.
            'full',

            'side',

            // This represents an image aligned to the left.
            'alignLeft',

            'alignCenter',

            // This represents an image aligned to the right.
            'alignRight'
        ],

        image: {
            upload:  {
                types: ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'mp3', 'mp4', 'm4v', 'm4a', 'm1v', 'm2v', 'mp2', 'mpa', 'mpe', 'mpeg', 'mpg', 'mpv2', 'wav', 'pdf']
                // Image upload feature options.
            }
        }
    } )
    .then( newEditor => {
        console.log( 'Editor was initialized', newEditor );
        editor = newEditor;
    } )
    .catch( error => {
        console.log( error );
    } );

Here is the upload class:

class MyUploadAdapter {
    constructor( loader ) {
        // The file loader instance to use during the upload.
        this.loader = loader;
    }

    // Initializes the XMLHttpRequest object using the URL passed to the constructor.
    _initRequest() {
        const xhr = this.xhr = new XMLHttpRequest();

        // Note that your request may look different. It is up to you and your editor
        // integration to choose the right communication channel. This example uses
        // a POST request with JSON as a data structure but your configuration
        // could be different.
        xhr.open( 'POST', 'http://...../uploadc.php', true );
        xhr.responseType = 'json';
    }

    // Initializes XMLHttpRequest listeners.
    _initListeners( resolve, reject, file ) {
        const xhr = this.xhr;
        const loader = this.loader;
        const genericErrorText = `Couldn't upload file: ${ file.name }.`;

        xhr.addEventListener( 'error', () => reject( genericErrorText ) );
        xhr.addEventListener( 'abort', () => reject() );
        xhr.addEventListener( 'load', () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    const response = xhr.response;
                    if ( response && (response.url || response.urls) ) {
                        resolve( response.url ? { default: response.url } : response.urls );
                    } else if ( response && response.error ) {
                        return reject( response.error.message );
                    } else {
                        resolve( response.url ? { default: response.url } : response.urls );
                    }

                } else {
                    return reject( genericErrorText );
                }
            }

        } );

        // Upload progress when it is supported. The file loader has the #uploadTotal and #uploaded
        // properties which are used e.g. to display the upload progress bar in the editor
        // user interface.
        if ( xhr.upload ) {
            xhr.upload.addEventListener( 'progress', evt => {
                if ( evt.lengthComputable ) {
                    loader.uploadTotal = evt.total;
                    loader.uploaded = evt.loaded;
                }
            } );
        }
    }

    // Prepares the data and sends the request.
    _sendRequest( file ) {
        // Prepare the form data.
        const data = new FormData();

        data.append( 'upload', file );

        // Important note: This is the right place to implement security mechanisms
        // like authentication and CSRF protection. For instance, you can use
        // XMLHttpRequest.setRequestHeader() to set the request headers containing
        // the CSRF token generated earlier by your application.

        // Send the request.
        this.xhr.send( data );
    }

    // Starts the upload process.
    upload() {
        return this.loader.file
            .then( file => new Promise( ( resolve, reject ) => {
                this._initRequest();
                this._initListeners( resolve, reject, file );
                this._sendRequest( file );
            } ) );
    }

    // Aborts the upload process.
    abort() {
        if ( this.xhr ) {
            this.xhr.abort();
        }
    }

}
</code>```

答:
Sorry, nothing wrong with the code. This issue is caused by server side data not being clean:

it only allows registered users to do this file upload, which causes some unvisible stuff in the response, so xmlhttprequest cannot handle it properly.

I used ob_end_clean() to cast off cached data, and it works now

thanks

Body:
I used simple custom MyUploadAdapter following the ckeditor5 online document.

Images show up from both copy-paste and file upload dialog, and uploaded to the server. But once clicked save the textarea content to my server, the image src is empty, shown as:

The libray I am using:
https://cdn.ckeditor.com/ckeditor5/19.0.0/classic/ckeditor.js

Here are the codes:

function synchValues()
{
/*
    for(var instanceName in CKEDITOR.instances)
        CKEDITOR.instances[instanceName].updateElement();
CKEDITOR.on('instanceReady', function(){
   $.each( CKEDITOR.instances, function(instance) {
    CKEDITOR.instances[instance].on("change", function(e) {
        for ( instance in CKEDITOR.instances )
        CKEDITOR.instances[instance].updateElement();
    });
   });
});

    document.getElementById('editor').value = editor.getData();
*/

$('textarea.editor').each(function () {
   var $textarea = $(this);
   $textarea.val(CKEDITOR.instances[$textarea.attr('name')].getData());
});

    return true;
}

function MyCustomUploadAdapterPlugin( editor ) {

    editor.plugins.get( 'FileRepository' ).createUploadAdapter = ( loader ) => {
        // Configure the URL to the upload script in your back-end here!
        return new MyUploadAdapter( loader );
    };
}

let editor;

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        extraPlugins: [ MyCustomUploadAdapterPlugin ],

        styles: [
            // This option is equal to a situation where no style is applied.
            'full',

            'side',

            // This represents an image aligned to the left.
            'alignLeft',

            'alignCenter',

            // This represents an image aligned to the right.
            'alignRight'
        ],

        image: {
            upload:  {
                types: ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'mp3', 'mp4', 'm4v', 'm4a', 'm1v', 'm2v', 'mp2', 'mpa', 'mpe', 'mpeg', 'mpg', 'mpv2', 'wav', 'pdf']
                // Image upload feature options.
            }
        }
    } )
    .then( newEditor => {
        console.log( 'Editor was initialized', newEditor );
        editor = newEditor;
    } )
    .catch( error => {
        console.log( error );
    } );

Here is the upload class:

class MyUploadAdapter {
    constructor( loader ) {
        // The file loader instance to use during the upload.
        this.loader = loader;
    }

    // Initializes the XMLHttpRequest object using the URL passed to the constructor.
    _initRequest() {
        const xhr = this.xhr = new XMLHttpRequest();

        // Note that your request may look different. It is up to you and your editor
        // integration to choose the right communication channel. This example uses
        // a POST request with JSON as a data structure but your configuration
        // could be different.
        xhr.open( 'POST', 'http://...../uploadc.php', true );
        xhr.responseType = 'json';
    }

    // Initializes XMLHttpRequest listeners.
    _initListeners( resolve, reject, file ) {
        const xhr = this.xhr;
        const loader = this.loader;
        const genericErrorText = `Couldn't upload file: ${ file.name }.`;

        xhr.addEventListener( 'error', () => reject( genericErrorText ) );
        xhr.addEventListener( 'abort', () => reject() );
        xhr.addEventListener( 'load', () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    const response = xhr.response;
                    if ( response && (response.url || response.urls) ) {
                        resolve( response.url ? { default: response.url } : response.urls );
                    } else if ( response && response.error ) {
                        return reject( response.error.message );
                    } else {
                        resolve( response.url ? { default: response.url } : response.urls );
                    }

                } else {
                    return reject( genericErrorText );
                }
            }

        } );

        // Upload progress when it is supported. The file loader has the #uploadTotal and #uploaded
        // properties which are used e.g. to display the upload progress bar in the editor
        // user interface.
        if ( xhr.upload ) {
            xhr.upload.addEventListener( 'progress', evt => {
                if ( evt.lengthComputable ) {
                    loader.uploadTotal = evt.total;
                    loader.uploaded = evt.loaded;
                }
            } );
        }
    }

    // Prepares the data and sends the request.
    _sendRequest( file ) {
        // Prepare the form data.
        const data = new FormData();

        data.append( 'upload', file );

        // Important note: This is the right place to implement security mechanisms
        // like authentication and CSRF protection. For instance, you can use
        // XMLHttpRequest.setRequestHeader() to set the request headers containing
        // the CSRF token generated earlier by your application.

        // Send the request.
        this.xhr.send( data );
    }

    // Starts the upload process.
    upload() {
        return this.loader.file
            .then( file => new Promise( ( resolve, reject ) => {
                this._initRequest();
                this._initListeners( resolve, reject, file );
                this._sendRequest( file );
            } ) );
    }

    // Aborts the upload process.
    abort() {
        if ( this.xhr ) {
            this.xhr.abort();
        }
    }

}


问:
How to merge two CSV files with Linux column wise?
I am looking for a simple line of code (if possible) to simply merge two files column wise and save the final result into a new file.

Edited to response to the first answer @heitor:

By using paste file1.csv file2.csv, What happened is:

For instance file 1:

```<code>A B
1 2
</code>```

file2:

```<code>C D
3 4
</code>```

By doing paste -d , file1.csv file2.csv >output.csv I got

```<code> A B
 C D
 1 2
 3 4
</code>```

not

```<code>A B C D
1 2 3 4
</code>```

By doing cat file1.csv file2.csv I got

```<code>A B
1 2
C D
3 4
</code>```

Neither of them is what I want. Any idea?

Any idea?

答:
Use paste -d , to merge the two files and > to redirect the command output to another file:

$ paste -d , file1.csv file2.csv > output.csv
```

<p>E.g.:</p>

<pre class="lang-sh prettyprint-override"><code>$ cat file1.csv
A,B

$ cat file2.csv
C,D

$ paste -d , file1.csv file2.csv > output.csv

$ cat output.csv
A,B,C,D

</code>```

-d , tells paste to use , as the delimiter to join the columns.

> tells the shell to write the output of the paste command to the file output.csv

Body:
I am looking for a simple line of code (if possible) to simply merge two files column wise and save the final result into a new file.

Edited to response to the first answer @heitor:

By using paste file1.csv file2.csv, What happened is:

For instance file 1:

A B
1 2

file2:

C D
3 4

By doing paste -d , file1.csv file2.csv >output.csv I got

 A B
 C D
 1 2
 3 4

not

A B C D
1 2 3 4

By doing cat file1.csv file2.csv I got

A B
1 2
C D
3 4

Neither of them is what I want. Any idea?

Any idea?

Body:
Use paste -d , to merge the two files and > to redirect the command output to another file:

$ paste -d , file1.csv file2.csv > output.csv

E.g.:

$ cat file1.csv
A,B

$ cat file2.csv
C,D

$ paste -d , file1.csv file2.csv > output.csv

$ cat output.csv
A,B,C,D

-d , tells paste to use , as the delimiter to join the columns.

> tells the shell to write the output of the paste command to the file output.csv


问:
card box across full screen width - bootstrap
How can I adjust my 'card' so that it is displayed across the entire width of the screen?
I am using bootstrap

{{$tipo->tipo }}

```

i need width similar to footer

答:
If you are using the latest Bootstrap 4 then this code will create a card across the entire width:

```<code><div class="card w-100 mt-2">
    <h4>Restaurante</h4>
</div>
</code>```

If there is still a gap then it is likely you have padding on the container div surrounding the card, so you would need to remove that.

Body:
How can I adjust my 'card' so that it is displayed across the entire width of the screen?
I am using bootstrap

{{$tipo->tipo }}

i need width similar to footer

Body:
If you are using the latest Bootstrap 4 then this code will create a card across the entire width:

<div class="card w-100 mt-2">
    <h4>Restaurante</h4>
</div>

If there is still a gap then it is likely you have padding on the container div surrounding the card, so you would need to remove that.


问:
Where to place code to set Firebase auth state persistence in Vue.js?

Overview

I'm building a web app in Quasar/Vue.js and Firebase which needs to authenticate users.

What I'm trying to achieve

A pretty common feature - keep users logged even after they close the browser/tab.

Possible Solutions

I'm aware that I can use localStorage or cookies to set the user auth state. However, I want to allow Firebase auth do it for me (if it can do it).

I checked the docs in this regard - https://firebase.google.com/docs/auth/web/auth-state-persistence
and they're nice, except I cannot figure out where to place this piece of code mentioned there:

```<code>firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
  .then(function() {
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });
</code>```

I'm not sure where to place it out of the following places:

with the onAuthStatechanged listener?

in the App.vue (root Vue) instance?

somewhere else?

Would be glad if anyone could help out. Thanks.

答:
I'd do it wherever you have firebase.initializeApp(). Eg

firebase.initializeApp({
  // config goes here
});

export const auth = firebase.auth()

auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
```
<p>Note that <code>LOCAL</code> is the default in web apps already.</p>
<p>You don't really need to wait for that promise. From the docs</p>
<blockquote>
<p>This will return a promise that will resolve once the state finishes copying from one type of storage to the other. <strong>Calling a sign-in method after changing persistence will wait for that persistence change to complete</strong> before applying it on the new Auth state.</p>
</blockquote>
<hr />
<p>The modular version (v9+) of this would look like the following...</p>
<pre class="lang-js prettyprint-override"><code>import { initializeApp } from "firebase/app";
import {
  browserLocalPersistence,
  getAuth,
  setPersistence
} from "firebase/auth";

const app = initializeApp({
  // config goes here
})

export const auth = getAuth(app);

setPersistence(auth, browserLocalPersistence)
</code>```

Body:
Overview

I'm building a web app in Quasar/Vue.js and Firebase which needs to authenticate users.

What I'm trying to achieve

A pretty common feature - keep users logged even after they close the browser/tab.

Possible Solutions

I'm aware that I can use localStorage or cookies to set the user auth state. However, I want to allow Firebase auth do it for me (if it can do it).

I checked the docs in this regard - https://firebase.google.com/docs/auth/web/auth-state-persistence
and they're nice, except I cannot figure out where to place this piece of code mentioned there:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
  .then(function() {
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

I'm not sure where to place it out of the following places:

with the onAuthStatechanged listener?

in the App.vue (root Vue) instance?

somewhere else?

Would be glad if anyone could help out. Thanks.

Body:
I'd do it wherever you have firebase.initializeApp(). Eg

firebase.initializeApp({
  // config goes here
});

export const auth = firebase.auth()

auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)

Note that LOCAL is the default in web apps already.

You don't really need to wait for that promise. From the docs

This will return a promise that will resolve once the state finishes copying from one type of storage to the other. Calling a sign-in method after changing persistence will wait for that persistence change to complete before applying it on the new Auth state.

The modular version (v9+) of this would look like the following...

import { initializeApp } from "firebase/app";
import {
  browserLocalPersistence,
  getAuth,
  setPersistence
} from "firebase/auth";

const app = initializeApp({
  // config goes here
})

export const auth = getAuth(app);

setPersistence(auth, browserLocalPersistence)


问:
purrr - pmap - Supplying different column names to function parameter names in tidy style
I'm wondering if there's a way to specify which columns should be matched to which arguments when calling pmap on a data.frame or named list.

The default behaviour, which is useful and intuititive in most contexts is to match column names to argument names, as in

check_row_deidentified <- function(encntr_key, clinical_event_key, note_value, ...) {
  # Do stuff
  tibble::tibble(encntr_key, clinical_event_key, note_value)
}

notes_1 <- tibble::tibble(
  encntr_key = c(1,2,3),
  clinical_event_key = c(1,2,3),
  note_value = c("foo", "bar", "baz")
  )

out <- notes_1 %>%
 purrr::pmap_dfr(check_row_deidentified)
```

<p>But I'm wondering if there's a way to give an input with different column names, and specify how pmap should treat those. </p>

<p>As in:</p>

<pre class="lang-r prettyprint-override"><code>check_row_deidentified <- function(encntr_key, clinical_event_key, note_value, ...) {
  # Do stuff
}

notes_1 <- tibble::tibble(
  key_enc = c(1,2,3),
  key_clinical = c(1,2,3),
  free_text = c("foo", "bar", "baz")
  )

out <- notes_1 %>%
 purrr::pmap_dfr(check_row_deidentified, encntr_key = key_enc, clinical_event_key = key_clinical, note_value = note_value)
</code>```

I guess an obvious choice would be to just rename those columns before I call pmap, as in

# Given as arg
to_rename <- rlang::exprs(
  note_value = free_text,
  encntr_key = key_enc,
  clinical_event_key = key_clinical
)

notes_1 %>%
  dplyr::rename(!!!to_rename) %>%
  purrr::pmap_dfr(check_row_deidentified)
```

But I'm not sure if something less cludgey exists

答:
I decided that my "cludgey" workaround is good enough for this excercise:

I guess an obvious choice would be to just rename those columns before I call pmap, as in

# Given as arg
to_rename <- rlang::exprs(
  note_value = free_text,
  encntr_key = key_enc,
  clinical_event_key = key_clinical
)

notes_1 %>%
  dplyr::rename(!!!to_rename) %>%
  purrr::pmap_dfr(check_row_deidentified)
```

But I'm not sure if something less cludgey exists

Body:
I'm wondering if there's a way to specify which columns should be matched to which arguments when calling pmap on a data.frame or named list.

The default behaviour, which is useful and intuititive in most contexts is to match column names to argument names, as in

check_row_deidentified <- function(encntr_key, clinical_event_key, note_value, ...) {
  # Do stuff
  tibble::tibble(encntr_key, clinical_event_key, note_value)
}

notes_1 <- tibble::tibble(
  encntr_key = c(1,2,3),
  clinical_event_key = c(1,2,3),
  note_value = c("foo", "bar", "baz")
  )

out <- notes_1 %>%
 purrr::pmap_dfr(check_row_deidentified)

But I'm wondering if there's a way to give an input with different column names, and specify how pmap should treat those.

As in:

check_row_deidentified <- function(encntr_key, clinical_event_key, note_value, ...) {
  # Do stuff
}

notes_1 <- tibble::tibble(
  key_enc = c(1,2,3),
  key_clinical = c(1,2,3),
  free_text = c("foo", "bar", "baz")
  )

out <- notes_1 %>%
 purrr::pmap_dfr(check_row_deidentified, encntr_key = key_enc, clinical_event_key = key_clinical, note_value = note_value)

I guess an obvious choice would be to just rename those columns before I call pmap, as in

# Given as arg
to_rename <- rlang::exprs(
  note_value = free_text,
  encntr_key = key_enc,
  clinical_event_key = key_clinical
)

notes_1 %>%
  dplyr::rename(!!!to_rename) %>%
  purrr::pmap_dfr(check_row_deidentified)

But I'm not sure if something less cludgey exists

Body:
I decided that my "cludgey" workaround is good enough for this excercise:

I guess an obvious choice would be to just rename those columns before I call pmap, as in

# Given as arg
to_rename <- rlang::exprs(
  note_value = free_text,
  encntr_key = key_enc,
  clinical_event_key = key_clinical
)

notes_1 %>%
  dplyr::rename(!!!to_rename) %>%
  purrr::pmap_dfr(check_row_deidentified)

But I'm not sure if something less cludgey exists


问:
vscode custom edtior extension development: No editors associated with document
I am developing a markdown vscode extension based on CustomEditor，and it works as expectation.

But a warning appeared in Console：No editors associated with document: xxx.md

Source Code： https://github.com/TobiasTao/vscode-md

答:
In package.json:

Change

```<code>  "main": "./out/extension.js",
</code>```

to

```<code>  "main": "./dist/extension.js",
</code>```

Body:
In package.json:

Change

  "main": "./out/extension.js",

to

  "main": "./dist/extension.js",


问:
Regular expression syntax
I have a similar problem, to a previously asked question. But similar practices apparently do not produce similar results.

Previous Question

New question - I want to match the lines beginning in T as the first match, and the following lines beginning with X as the second match (as a whole string, to be later matched by another regex)

What I have so far is (^T(\d+)\n(.*?)(?:the_problem)/m) I don't know what to replace "the_problem" with, or even if that is the issue. I assumed some rendition (?:\n|\z), but apparently not. Everything I tried, would not count the next occurrence of ^T(\d+) as the start of a new group, and continue to capture all of the lines between each occurrence, at the same time.

```<code>Sample text;
T01C0.025
T02C0.035
T03C0.055
T04C0.150
T05C0.065
T06C0.075
%
G05
G90
T01
X011200Y004700
X011200Y009700
X018500Y011200
X013500Y-011200
X023800Y019500
T02
X034800Y017800
X-033800Y-017800
X032800Y017800
T03
X036730Y003000
X038700Y003000
X040668Y-003000
X059230Y003000
T04
X110580Y017800
X023800Y027300
X095500Y028500
X005500Y-006500
X021500Y-006500
T05
X003950Y002000
X003950Y004500
X003950Y007000
T06
X026300Y027300
M30
</code>```

I only want to capture the shorter version of T01, T02,...T0n, not the longer version at the top, then the entire collection of ^X(-?\d+)Y(-?\d+) that follows it, as another match.

```<code>Result 1.
Match 1. T01
Match 2. X011200Y004700
         X011200Y009700
         X018500Y011200
         X013500Y-011200
         X023800Y019500

Result 2.
Match 1. T02
Match 2. X034800Y017800
         X-033800Y-017800
         X032800Y017800

Result 3.
Match 1. T03
Match 2. X036730Y003000
         X038700Y003000

         ....etc....
</code>```

Thanks in advance for any help ;-) Note: I prefer to use raw Ruby, without extensions or plugins. My version of ruby is 1.8.6.

Title: Regular expression syntax

Body:
I have a similar problem, to a previously asked question. But similar practices apparently do not produce similar results.

Previous Question

New question - I want to match the lines beginning in T as the first match, and the following lines beginning with X as the second match (as a whole string, to be later matched by another regex)

What I have so far is (^T(\d+)\n(.*?)(?:the_problem)/m) I don't know what to replace "the_problem" with, or even if that is the issue. I assumed some rendition (?:\n|\z), but apparently not. Everything I tried, would not count the next occurrence of ^T(\d+) as the start of a new group, and continue to capture all of the lines between each occurrence, at the same time.

Sample text;
T01C0.025
T02C0.035
T03C0.055
T04C0.150
T05C0.065
T06C0.075
%
G05
G90
T01
X011200Y004700
X011200Y009700
X018500Y011200
X013500Y-011200
X023800Y019500
T02
X034800Y017800
X-033800Y-017800
X032800Y017800
T03
X036730Y003000
X038700Y003000
X040668Y-003000
X059230Y003000
T04
X110580Y017800
X023800Y027300
X095500Y028500
X005500Y-006500
X021500Y-006500
T05
X003950Y002000
X003950Y004500
X003950Y007000
T06
X026300Y027300
M30

I only want to capture the shorter version of T01, T02,...T0n, not the longer version at the top, then the entire collection of ^X(-?\d+)Y(-?\d+) that follows it, as another match.

Result 1.
Match 1. T01
Match 2. X011200Y004700
         X011200Y009700
         X018500Y011200
         X013500Y-011200
         X023800Y019500

Result 2.
Match 1. T02
Match 2. X034800Y017800
         X-033800Y-017800
         X032800Y017800

Result 3.
Match 1. T03
Match 2. X036730Y003000
         X038700Y003000

         ....etc....

Thanks in advance for any help ;-) Note: I prefer to use raw Ruby, without extensions or plugins. My version of ruby is 1.8.6.

Body:
this seems to work...

^(T[^\s]+)[\n\r\s]((X[^\s]+)[\n\r\s]){1,}


问:
Web Share API not working on iOS: Angular
I am trying to share an image like a native app via web. I am using Angular for the same. I have used the web share API. This works normally on Android however, throws an error while in iOS(Both Safari and Chrome). I am using a share button to trigger this.

This is my code:

```<code>if (
      this.windowNavigator.canShare &&
      this.windowNavigator.canShare({ files: [file] })
    ) {
      this.windowNavigator
        .share({
          files: [file],
          title: "Vacation Pictures",
          text: "Photos from September 27 to October 14.",
        })
        .then(() => console.log("Share was successful."))
        .catch((error) => console.log("Sharing failed", error));
    } else {
      console.error("Cannot use Web Share API");
    }
</code>```

The error I receive is: Cannot use Web Share API

This should typically happen if the browser is not supported.
However, according to https://caniuse.com/#search=web%20share , Safari 13 on iOS is supported.
Please note that I tried logging the navigator object to the console and it does have the share() proto. I am running it over an HTTPS server.
Kindly guide me as to how to proceed.

答:
Edit (9 June 2021): Web Share API Level 2 is available and usable by default in the iOS 15 Developer Beta, which means it most likely will be available in the final public release of iOS 15.

Like Aluan noted, the API has limited support and is not supported on iOS at all. Keep in mind that this means it is not supported on any iOS browser, even Chrome, since all browsers on iOS use the same (WebKit) engine.

From the App Store Review Guidelines:

2.5.6 Apps that browse the web must use the appropriate WebKit framework and WebKit Javascript.

Body:
I am trying to share an image like a native app via web. I am using Angular for the same. I have used the web share API. This works normally on Android however, throws an error while in iOS(Both Safari and Chrome). I am using a share button to trigger this.

This is my code:

if (
      this.windowNavigator.canShare &&
      this.windowNavigator.canShare({ files: [file] })
    ) {
      this.windowNavigator
        .share({
          files: [file],
          title: "Vacation Pictures",
          text: "Photos from September 27 to October 14.",
        })
        .then(() => console.log("Share was successful."))
        .catch((error) => console.log("Sharing failed", error));
    } else {
      console.error("Cannot use Web Share API");
    }

The error I receive is: Cannot use Web Share API

This should typically happen if the browser is not supported.
However, according to https://caniuse.com/#search=web%20share , Safari 13 on iOS is supported.
Please note that I tried logging the navigator object to the console and it does have the share() proto. I am running it over an HTTPS server.
Kindly guide me as to how to proceed.