问:
How to fix "Database is locked" when UPDATE?
I want to update datas from the variable, but I don't know why this error message display when I execute my code:

```<code>line 18, in save
curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )
sqlite3.OperationalError: database is locked
</code>```

I'm runing on Atom for the script, using python 3.7.2, and using SQLite3 and SQLite Studio for all datas.

import sqlite3
from tkinter import *

connexion = sqlite3.connect('Base_SAV.db')
curseur = connexion.cursor()
curseur.execute("PRAGMA foreign_keys =ON")

def save(event):
   curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )

...

L_Comment = Label(my_frame, text='Commentaires SAV :', font=('Arial', 22, 'bold','underline')).grid(row=1, column=1, sticky='w')
T_Comment = Text(my_frame, height=10, width=100,font=('Arial',14))
T_Comment.grid(row=2, column=1,columnspan=7, sticky='w')

...
my_frame.bind("<Return>", save)
```

I don't know how to fix this issue. Thank you if you can help me.

答:
You need to connect to the database, commit the changes and then close the conexion.

Try changing this:

```<code>def save(event):
       curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )
</code>```

to this:

```<code>def save(event):
   with conexion:
      curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )
</code>```

thus avoiding the use of curseur.commit and curseur.close as the with conexion: statement stablishes the conexion and closes it by itself.

Body:
I want to update datas from the variable, but I don't know why this error message display when I execute my code:

line 18, in save
curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )
sqlite3.OperationalError: database is locked

I'm runing on Atom for the script, using python 3.7.2, and using SQLite3 and SQLite Studio for all datas.

import sqlite3
from tkinter import *

connexion = sqlite3.connect('Base_SAV.db')
curseur = connexion.cursor()
curseur.execute("PRAGMA foreign_keys =ON")

def save(event):
   curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )

...

L_Comment = Label(my_frame, text='Commentaires SAV :', font=('Arial', 22, 'bold','underline')).grid(row=1, column=1, sticky='w')
T_Comment = Text(my_frame, height=10, width=100,font=('Arial',14))
T_Comment.grid(row=2, column=1,columnspan=7, sticky='w')

...
my_frame.bind("<Return>", save)

I don't know how to fix this issue. Thank you if you can help me.

Body:
You need to connect to the database, commit the changes and then close the conexion.

Try changing this:

def save(event):
       curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )

to this:

def save(event):
   with conexion:
      curseur.execute("UPDATE SAV SET Commentaires_SAV=(?)", (T_Comment.get("1.0", END),) )

thus avoiding the use of curseur.commit and curseur.close as the with conexion: statement stablishes the conexion and closes it by itself.


来源: stackexchange

问:
SettingWithCopyWarning on index
When I try to create a column of mdates from the index(which contains datetime64[ns]), via:

```<code>df['mdates'] = mdates.date2num(df.index)
</code>```

I get the:

SettingWithCopyWarning

How do I fix this. Normally I'd use df.loc but how can you use df.loc on the index?

答:
The issue only occurs when I pass the df to a function, slice a range of dates via:

```<code>df.loc[start_date:end_date]
</code>```

and then try to create a:

```<code>df['mdates'] = mdates.date2num(df.index)
</code>```

I solved the issue  by copying the df when its passed inside the function. First line of code in the function is:

```<code>df = df.copy()
</code>```

May not be the most efficient way to do it but it solved the problem. If someone can explain why it throws an error without this bit of code I'd be grateful.

ContentLicense: CC BY-SA 4.0

Title: SettingWithCopyWarning on index

Body:
When I try to create a column of mdates from the index(which contains datetime64[ns]), via:

df['mdates'] = mdates.date2num(df.index)

I get the:

SettingWithCopyWarning

How do I fix this. Normally I'd use df.loc but how can you use df.loc on the index?

Body:
The issue only occurs when I pass the df to a function, slice a range of dates via:

df.loc[start_date:end_date]

and then try to create a:

df['mdates'] = mdates.date2num(df.index)

I solved the issue  by copying the df when its passed inside the function. First line of code in the function is:

df = df.copy()

May not be the most efficient way to do it but it solved the problem. If someone can explain why it throws an error without this bit of code I'd be grateful.


问:
Android Studio java file gets corrupted
Unfortunaetly my laptop shutdown unproperly during coding in Android Studio. When I turned on again and tried to reload the project one class / java file was corrupted and suddenly all code was gone!

What I already tried:

Local History -> Show History = nothing to show

File / Invalidate Caches and Restart = no luck

Decompiled apk, but code has been obfuscated by Proguard, so it is almost impossible to read

Weird thing is that the java file has a size but the content is empty (I already deleted "nul nul nul" characters but still no luck.

Any help or advice?

答: To solve the problem I would cut all the files from the project, allowing android studio to update its indices showing no files in the project tree. Soon after I move them all back then let android studio to load the files again. After loading the cache would get updated with the correct information.</p>

ContentLicense: CC BY-SA 3.0

Title: Android Studio java file gets corrupted


问:
Correctly extend a tkinter widget using inheritance
Im kinda new to python classes and I dont know how to handle them well yet, and I promise I've done some research to solve this problem but still cant figure out how to. So, here it goes:

I'm trying to use python classes to define tkinter widgets so I can implement them rather quickly. It all worked well with buttons and labels but with I cant get it with entries. I'll show you how I've coded buttons and labels to illustrate what im trying to do with entries as well (and maybe you guys can help me improve this if necessary?).

```<code>class buttonStatic:
    def __init__(self, parent, row, col,rowspan, text, font, bg, fg, bd,width=None, function=None,sticky=None):
        button = tk.Button(parent, text=text, font=(font), bg=bg, fg=fg,bd=bd, width=width, command=function)
        button.grid(row=row, column=col,rowspan=rowspan, padx=padx, pady=pady, sticky=sticky)

class buttonDinamic:
    def __init__(self, parent, row, col,rowspan, textVar, font, bg, fg,bd,width=None, function=None,sticky=None):
        variable = tk.StringVar()
        variable.set(textVar)
        button = tk.Button(parent, textvariable=variable, font=(font), bg=bg, fg=fg,bd=bd, width=width, command=function)
        button.grid(row=row, column=col,rowspan=rowspan, padx=padx, pady=pady, sticky=sticky)

class labelStatic:
    def __init__(self, parent, row, col, text, font, bg, fg, sticky=None):
        label = tk.Label(parent, text=text, font=(font), bg=bg, fg=fg)
        label.grid(row=row, column=col, padx=padx, pady=pady, sticky=sticky)

class labelDinamic:
    def __init__(self, parent, row, col, textVar, font, bg, fg, sticky=None):
        variable = tk.StringVar()
        variable.set(textVar)
        label = tk.Label(parent, textvariable=variable, font=(font), bg=bg, fg=fg)
        label.grid(row=row, column=col, padx=padx, pady=pady, sticky=sticky)
</code>```

Now, this is what I've coded for the entries, following the answer in this (I've added some lambda functions to make it "reusable")

```<code>def focusIn(entry):
    entry.delete(0,'end')
    entry.config(fg=fColor_1)
    return

def focusOut(entry):
    entry.delete(0,'end')
    entry.config(fg=fColor_3)
    entry.insert(0,'Presupuesto')
    return

def enter(entry):
    x = entry.get()
    print(entry.get())
    focusOut(entry)
    return

testEntry = tk.Entry(module,bg=bgColor_1,width = 30, fg='grey')
testEntry.grid(row=0,column = 1)
testEntry.insert(0,'Presupuesto')
testEntry.bind('<FocusIn>',lambda x: focusIn(testEntry))
testEntry.bind('<FocusOut>',lambda x: focusIn(testEntry))
testEntry.bind('<Return>',lambda x: enter(testEntry))
</code>```

Here is my actual question

How to make into a class and, how to use the .get() and .set() methods when the widget is made into a class?

As im not very experienced in python classes (and especially combining them with tkinter) I dont even know if what I'm asking is possible!
p.d.: Sorry if my english is not very good, it's not my native language

答:
Question: How to make into a own class from a tkinter.Entry

It's called inheritance.

All. inherited methods, e.g. .get() behave the same.

```<code>class MyEntry(tk.Entry):
    def __init__(self, parent, **kwargs):
        # Defaults
        kwargs['fg'] = 'grey'
        super().__init__(parent, **kwargs)

        self.bind('<FocusIn>', self.on_event)
        self.bind('<FocusOut>', self.on_event)
        self.bind('<Return>', self.on_event)

    def on_event(self, event):
        print('on_event type:{}'.format(event.type))
</code>```

Usage:

```<code>testEntry = MyEntry(module, bg=bgColor_1, width = 30)
testEntry.grid(row=0,column = 1)
testEntry.insert(0,'Presupuesto')

print(testEntry.get())
</code>```

Body:
Im kinda new to python classes and I dont know how to handle them well yet, and I promise I've done some research to solve this problem but still cant figure out how to. So, here it goes:

I'm trying to use python classes to define tkinter widgets so I can implement them rather quickly. It all worked well with buttons and labels but with I cant get it with entries. I'll show you how I've coded buttons and labels to illustrate what im trying to do with entries as well (and maybe you guys can help me improve this if necessary?).

class buttonStatic:
    def __init__(self, parent, row, col,rowspan, text, font, bg, fg, bd,width=None, function=None,sticky=None):
        button = tk.Button(parent, text=text, font=(font), bg=bg, fg=fg,bd=bd, width=width, command=function)
        button.grid(row=row, column=col,rowspan=rowspan, padx=padx, pady=pady, sticky=sticky)

class buttonDinamic:
    def __init__(self, parent, row, col,rowspan, textVar, font, bg, fg,bd,width=None, function=None,sticky=None):
        variable = tk.StringVar()
        variable.set(textVar)
        button = tk.Button(parent, textvariable=variable, font=(font), bg=bg, fg=fg,bd=bd, width=width, command=function)
        button.grid(row=row, column=col,rowspan=rowspan, padx=padx, pady=pady, sticky=sticky)

class labelStatic:
    def __init__(self, parent, row, col, text, font, bg, fg, sticky=None):
        label = tk.Label(parent, text=text, font=(font), bg=bg, fg=fg)
        label.grid(row=row, column=col, padx=padx, pady=pady, sticky=sticky)

class labelDinamic:
    def __init__(self, parent, row, col, textVar, font, bg, fg, sticky=None):
        variable = tk.StringVar()
        variable.set(textVar)
        label = tk.Label(parent, textvariable=variable, font=(font), bg=bg, fg=fg)
        label.grid(row=row, column=col, padx=padx, pady=pady, sticky=sticky)

Now, this is what I've coded for the entries, following the answer in this (I've added some lambda functions to make it "reusable")

def focusIn(entry):
    entry.delete(0,'end')
    entry.config(fg=fColor_1)
    return

def focusOut(entry):
    entry.delete(0,'end')
    entry.config(fg=fColor_3)
    entry.insert(0,'Presupuesto')
    return

def enter(entry):
    x = entry.get()
    print(entry.get())
    focusOut(entry)
    return

testEntry = tk.Entry(module,bg=bgColor_1,width = 30, fg='grey')
testEntry.grid(row=0,column = 1)
testEntry.insert(0,'Presupuesto')
testEntry.bind('<FocusIn>',lambda x: focusIn(testEntry))
testEntry.bind('<FocusOut>',lambda x: focusIn(testEntry))
testEntry.bind('<Return>',lambda x: enter(testEntry))

Here is my actual question

How to make into a class and, how to use the .get() and .set() methods when the widget is made into a class?

As im not very experienced in python classes (and especially combining them with tkinter) I dont even know if what I'm asking is possible!
p.d.: Sorry if my english is not very good, it's not my native language

Body:
Question: How to make into a own class from a tkinter.Entry

It's called inheritance.

All. inherited methods, e.g. .get() behave the same.

class MyEntry(tk.Entry):
    def __init__(self, parent, **kwargs):
        # Defaults
        kwargs['fg'] = 'grey'
        super().__init__(parent, **kwargs)

        self.bind('<FocusIn>', self.on_event)
        self.bind('<FocusOut>', self.on_event)
        self.bind('<Return>', self.on_event)

    def on_event(self, event):
        print('on_event type:{}'.format(event.type))

Usage:

testEntry = MyEntry(module, bg=bgColor_1, width = 30)
testEntry.grid(row=0,column = 1)
testEntry.insert(0,'Presupuesto')

print(testEntry.get())


问:
How to click on an element which is visible=false in an ios mobile app
I have to automate an iOS pega mobile app, there I have a field which i need to click. But that field in set to visible "false". Is there a way where i can click on that element?

Image of the mobile screen

Approach (1) I used
Click on the Time(secs) text field, but this is set to visible false

String selector = "type=='XCUIElementTypeStaticText' AND rect.x==101 AND rect.y==150 AND(visible == 0 OR enabled == 1)";
        MobileElement timeEle = driver.findElementByIosNsPredicate(selector);
        timeEle.click();

Approach (2) I used
Click on the "Clock" icon, even for that i used predicate string still it's not working.

xpath shown in Appium,

```<code>//XCUIElementTypeOther[@name="Center Panel, region"]/XCUIElementTypeOther[1]/XCUIElementTypeOther[1]/XCUIElementTypeOther[4]/XCUIElementTypeOther[1]/XCUIElementTypeOther[1]/XCUIElementTypeOther[3]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther
</code>```

答:
When working with hidden elements, you'll typically want to use javascript to interact with them.

In java, and with your example, this would look like

```<code>import org.openqa.selenium.JavascriptExecutor; # added to the top of the script
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click()", timeEle);
</code>```

Body:
I have to automate an iOS pega mobile app, there I have a field which i need to click. But that field in set to visible "false". Is there a way where i can click on that element?

Image of the mobile screen

Approach (1) I used
Click on the Time(secs) text field, but this is set to visible false

String selector = "type=='XCUIElementTypeStaticText' AND rect.x==101 AND rect.y==150 AND(visible == 0 OR enabled == 1)";
        MobileElement timeEle = driver.findElementByIosNsPredicate(selector);
        timeEle.click();

Approach (2) I used
Click on the "Clock" icon, even for that i used predicate string still it's not working.

xpath shown in Appium,

//XCUIElementTypeOther[@name="Center Panel, region"]/XCUIElementTypeOther[1]/XCUIElementTypeOther[1]/XCUIElementTypeOther[4]/XCUIElementTypeOther[1]/XCUIElementTypeOther[1]/XCUIElementTypeOther[3]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther

Body:
When working with hidden elements, you'll typically want to use javascript to interact with them.

In java, and with your example, this would look like

import org.openqa.selenium.JavascriptExecutor; # added to the top of the script
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click()", timeEle);


问:
How do I set the date of a calendar view from another view using Jquery FullCalendar?
I have 2 Jquery fullcalendar controls on my page.

I want to be able to click on a day on the 1st calendar which is in 'month mode', and then set the 2nd calendar which is by default using the AgengaDay view, to the day that has been clicked on the 1st calendar?

I've tried the following:

```<code> $('#firstCalendar').fullCalendar({

            dayClick: function (date, allDay, jsEvent, view) {

                $('#secondcalendary').fullCalendar('select', date, date, allDay);
            }
 });
</code>```

but it doesn't seem to work

答:
Here you go--- Its not that difficult actually. Click on the Cal1 day and the Cal2 Changes!

http://jsfiddle.net/ppumkin/A56LN/

CODE

```<code>$('#mycalendar1').fullCalendar(
{
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    dayClick: function( date, allDay, jsEvent, view ) {
        dayClicked(date);
    },
    events: [
        {
            title  : 'event2',
            start  : '2011-03-10',
            end    : '2011-07-25'
        }
    ]
});

$('#mycalendar2').fullCalendar(
            {
             header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                    },

                defaultView: 'agendaDay',

                events: [
                        {
                            title  : 'event2',
                            start  : '2011-03-10',
                            end    : '2011-07-25'
                        }
                    ]
           });

function dayClicked(date){
    $('#mycalendar2').fullCalendar( 'gotoDate', date );
}
</code>```

Clicking the "TODAY" and other buttons..

I got some code like this. but this is not the solution. because it shows the date before the calendar changes. so basically the old date- maybe you can use a time-out? 500ms? or something - because jquery binds before the fullcalendar...

```<code>$('.fc-button-today').click(function() {
     alert($('#mycalendar2').fullCalendar( 'getDate' ));
   //dayClicked($('#mycalendar2').fullCalendar( 'getDate' ))

        });
</code>```

You might have to use the viewDisplay event. But it gets a bit complicated in there. Here is a document how to use it.

http://arshaw.com/fullcalendar/docs/display/viewDisplay/

Look at DoomsDay answer- nice solution :D

An internal hack for day click and possibly other buttons.

You can open fullcalendar.js and goto line about... 3220 or search for Slot/Day clicking and binding

```<code>/* Slot/Day clicking and binding
-----------------------------------------------------------------------*/

function dayBind(cells) {
    cells.click(slotClick)
        .mousedown(daySelectionMousedown);

   //OVER HERE INSERT YOUR CUSTOM CALL!
     setMyOtherCalendar();
}
</code>```

and in your page somewhere you would havbe a public function of setMyOtherCalendar and it would have this simple code in it.. init mate?

```<code>function setMyOtherCalendar(){

  $('#mycalendar2').fullCalendar( 'gotoDate',      $('#mycalendar1').fullCalendar( 'getDate' ) );

};
</code>```

Body:
I have 2 Jquery fullcalendar controls on my page.

I want to be able to click on a day on the 1st calendar which is in 'month mode', and then set the 2nd calendar which is by default using the AgengaDay view, to the day that has been clicked on the 1st calendar?

I've tried the following:

 $('#firstCalendar').fullCalendar({

            dayClick: function (date, allDay, jsEvent, view) {

                $('#secondcalendary').fullCalendar('select', date, date, allDay);
            }
 });

but it doesn't seem to work

Body:
Here you go--- Its not that difficult actually. Click on the Cal1 day and the Cal2 Changes!

http://jsfiddle.net/ppumkin/A56LN/

CODE

$('#mycalendar1').fullCalendar(
{
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    dayClick: function( date, allDay, jsEvent, view ) {
        dayClicked(date);
    },
    events: [
        {
            title  : 'event2',
            start  : '2011-03-10',
            end    : '2011-07-25'
        }
    ]
});

$('#mycalendar2').fullCalendar(
            {
             header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'
                    },

                defaultView: 'agendaDay',

                events: [
                        {
                            title  : 'event2',
                            start  : '2011-03-10',
                            end    : '2011-07-25'
                        }
                    ]
           });

function dayClicked(date){
    $('#mycalendar2').fullCalendar( 'gotoDate', date );
}

Clicking the "TODAY" and other buttons..

I got some code like this. but this is not the solution. because it shows the date before the calendar changes. so basically the old date- maybe you can use a time-out? 500ms? or something - because jquery binds before the fullcalendar...

$('.fc-button-today').click(function() {
     alert($('#mycalendar2').fullCalendar( 'getDate' ));
   //dayClicked($('#mycalendar2').fullCalendar( 'getDate' ))

        });

You might have to use the viewDisplay event. But it gets a bit complicated in there. Here is a document how to use it.

http://arshaw.com/fullcalendar/docs/display/viewDisplay/

Look at DoomsDay answer- nice solution :D

An internal hack for day click and possibly other buttons.

You can open fullcalendar.js and goto line about... 3220 or search for Slot/Day clicking and binding

/* Slot/Day clicking and binding
-----------------------------------------------------------------------*/

function dayBind(cells) {
    cells.click(slotClick)
        .mousedown(daySelectionMousedown);

   //OVER HERE INSERT YOUR CUSTOM CALL!
     setMyOtherCalendar();
}

and in your page somewhere you would havbe a public function of setMyOtherCalendar and it would have this simple code in it.. init mate?

function setMyOtherCalendar(){

  $('#mycalendar2').fullCalendar( 'gotoDate',      $('#mycalendar1').fullCalendar( 'getDate' ) );

};


问:
How to filter and append arrays
I have a code that I am using to try and filter out arrays that are missing values as seen here:

```<code>from astropy.table import Table
import numpy as np

data = '/home/myname/data.fits'
data = Table.read(data, format="fits")

ID = np.array(data['id'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['M'])
mag.astype(float)

def stack(array1, array2, array3, array4):
    #stacks multiple arrays to have corresponding values next to eachother
    stacked_array = [(array1[i], array2[i], array3[i], array4[i]) for i in range(0, array1.size)]
    stacked_array = np.array(stacked_array)
    return(stacked_array)

stacked = stack(ID, redshift, radius, mag)

filtered_array = np.array([])

for i in stacked:
    if not i.any == 'nan':
        np.insert(filtered_array, i[0], axis=0)
</code>```

The last for loop is where i'm having difficulty. I want to insert the rows from my stacked array into my filtered array if it has all of the information (some rows are missing redshift, others are missing magnitude etc...). How would I be able to loop over my stacked array and filter out all of the rows that have all 4 values I want? I keep getting this error currently.

```<code>TypeError: _insert_dispatcher() missing 1 required positional argument: 'values'
</code>```

答:
You can switch:

```<code>for i in stacked:
    if not i.any == 'nan':
        np.insert(filtered_array, i[0], axis=0)
</code>```

to:

```<code>def any_is_nan(col):
    return len(list(filter(lambda x: x=='nan',col))) > 0

filtered_array = list(filter(lambda x: not any_is_nan(x),stacked))
</code>```

Please refer to filter.

Title: How to filter and append arrays

Body:
I have a code that I am using to try and filter out arrays that are missing values as seen here:

from astropy.table import Table
import numpy as np

data = '/home/myname/data.fits'
data = Table.read(data, format="fits")

ID = np.array(data['id'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['M'])
mag.astype(float)

def stack(array1, array2, array3, array4):
    #stacks multiple arrays to have corresponding values next to eachother
    stacked_array = [(array1[i], array2[i], array3[i], array4[i]) for i in range(0, array1.size)]
    stacked_array = np.array(stacked_array)
    return(stacked_array)

stacked = stack(ID, redshift, radius, mag)

filtered_array = np.array([])

for i in stacked:
    if not i.any == 'nan':
        np.insert(filtered_array, i[0], axis=0)

The last for loop is where i'm having difficulty. I want to insert the rows from my stacked array into my filtered array if it has all of the information (some rows are missing redshift, others are missing magnitude etc...). How would I be able to loop over my stacked array and filter out all of the rows that have all 4 values I want? I keep getting this error currently.

TypeError: _insert_dispatcher() missing 1 required positional argument: 'values'

Body:
You can switch:

for i in stacked:
    if not i.any == 'nan':
        np.insert(filtered_array, i[0], axis=0)

to:

def any_is_nan(col):
    return len(list(filter(lambda x: x=='nan',col))) > 0

filtered_array = list(filter(lambda x: not any_is_nan(x),stacked))

Please refer to filter.


问:
Linux-PAM not finding module
I have written my own custom Linux-pam module which will call facial recognition software (embedded Python3 in C) to recognise a users face and, subsequently , provide authentication.

I have ran into a problem, whenever I modify the /etc/pam.d/sudo file to use my pam_authnew.so module, it gives the error

PAM module not found

I have compiled the C file to a .so, I have loaded said file into /lib/x86_64/security (where all my other default pam modules reside)

Below are the /etc/pam.d/sudo , /lib/x86_64-linux-gnu/security and the /etc/var/auth.log files to aid in troubleshooting.

/etc/pam.d/sudo

```<code>
session    required   pam_env.so readenv=1 user_readenv=0
session    required   pam_env.so readenv=1 envfile=/etc/default/locale user_rea$
#@include common-auth
@include common-account
@include common-session-noninteractive
</code>```

/etc/var/auth.log

```<code>Feb 20 14:11:58 berns-HP-Pavilion-Laptop-15-cw0xxx sudo: PAM unable to dlopen(/lib/x86_64-linux-gnu/security/pam_authnew.so): /lib/x86_64-linux-gnu/security/pam_authnew.so: undefined symbol: Py_Initialize
Feb 20 14:11:58 berns-HP-Pavilion-Laptop-15-cw0xxx sudo: PAM adding faulty module: /lib/x86_64-linux-gnu/security/pam_authnew.so
Feb 20 14:11:58 berns-HP-Pavilion-Laptop-15-cw0xxx sudo:    berns : PAM authentication error: Module is unknown ; TTY=pts/1 ; PWD=/home/berns ; USER=root ; COMMAND=/usr/bin/apt update
</code>```

答:
I kept troubleshooting and discovered I never linked with

-lpython3.6m

So the Python libraries were NOT included in the .so file.

Title: Linux-PAM not finding module

Body:
I have written my own custom Linux-pam module which will call facial recognition software (embedded Python3 in C) to recognise a users face and, subsequently , provide authentication.

I have ran into a problem, whenever I modify the /etc/pam.d/sudo file to use my pam_authnew.so module, it gives the error

PAM module not found

I have compiled the C file to a .so, I have loaded said file into /lib/x86_64/security (where all my other default pam modules reside)

Below are the /etc/pam.d/sudo , /lib/x86_64-linux-gnu/security and the /etc/var/auth.log files to aid in troubleshooting.

/etc/pam.d/sudo

session    required   pam_env.so readenv=1 user_readenv=0
session    required   pam_env.so readenv=1 envfile=/etc/default/locale user_rea$
#@include common-auth
@include common-account
@include common-session-noninteractive

/etc/var/auth.log

Feb 20 14:11:58 berns-HP-Pavilion-Laptop-15-cw0xxx sudo: PAM unable to dlopen(/lib/x86_64-linux-gnu/security/pam_authnew.so): /lib/x86_64-linux-gnu/security/pam_authnew.so: undefined symbol: Py_Initialize
Feb 20 14:11:58 berns-HP-Pavilion-Laptop-15-cw0xxx sudo: PAM adding faulty module: /lib/x86_64-linux-gnu/security/pam_authnew.so
Feb 20 14:11:58 berns-HP-Pavilion-Laptop-15-cw0xxx sudo:    berns : PAM authentication error: Module is unknown ; TTY=pts/1 ; PWD=/home/berns ; USER=root ; COMMAND=/usr/bin/apt update


问:
Laravel - How to Sum relative table with limit result?
I have these 2 models.

I want to get sum of 12 columns comment_count in youtube_video_insights table.

How can I do that with Query Builder or Eloquent.

I try to use something like in my Repository this but it didn't work.

It's just sum all the comment_count columns.

```<code>$this->youtube_channel_insight
            ->join('youtube_video_insights',function ($q){
                $q->on('youtube_channel_insights.id','=','youtube_video_insights.youtube_channel_insight_id')
                    ->orderBy('youtube_video_insights.id','desc')
                    ->limit(12);
            })
            ->where('youtube_channel_insights.id',$id)
            ->select(\DB::raw(
                "SUM(youtube_video_insights.comment_count) as total_comment"
            ))->get();
</code>```

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeChannelInsight extends Model
{
    protected $guarded = ['id'];

    public function videos()
    {
        return $this->hasMany(YoutubeVideoInsight::class);
    }
}

</code>```

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeVideoInsight extends Model
{
    protected $guarded = ['id'];
}

</code>```

答:
I assume the structure of your tables are:

for youtube_channel_insights's table you have :

```<code>id | name
----------------------------------------
1  | channel_01
2  | channel_02
</code>```

and for youtube_video_insights's table you have:

```<code>id | channel_id|    name    | comment_count
----------------------------------------
1  |     1     |  video_01  |      20
2  |     1     |  video_02  |      40
3  |     2     |  video_03  |      5
4  |     2     |  video_04  |      15
</code>```

Now you should wright your query like this:

```<code>$sub1 = YoutubeVideoInsight ::select('comment_count', 'channel_id')
->whereRaw('channel_id = 2')->orderBy('id', 'Desc')->limit(2);

$sub2 = DB::table(DB::raw("({$sub1->toSql()}) as sub"))
->select(DB::raw('
SUM(`comment_count`) AS total_comment,
channel_id
'));

return $query = YoutubeChannelInsight ::joinSub($sub2,'sub2',function($join){
$join->on('channels.id','=','sub2.channel_id');
})->get();
</code>```

Body:
I have these 2 models.

I want to get sum of 12 columns comment_count in youtube_video_insights table.

How can I do that with Query Builder or Eloquent.

I try to use something like in my Repository this but it didn't work.

It's just sum all the comment_count columns.

$this->youtube_channel_insight
            ->join('youtube_video_insights',function ($q){
                $q->on('youtube_channel_insights.id','=','youtube_video_insights.youtube_channel_insight_id')
                    ->orderBy('youtube_video_insights.id','desc')
                    ->limit(12);
            })
            ->where('youtube_channel_insights.id',$id)
            ->select(\DB::raw(
                "SUM(youtube_video_insights.comment_count) as total_comment"
            ))->get();

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeChannelInsight extends Model
{
    protected $guarded = ['id'];

    public function videos()
    {
        return $this->hasMany(YoutubeVideoInsight::class);
    }
}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeVideoInsight extends Model
{
    protected $guarded = ['id'];
}

Body:
I assume the structure of your tables are:

for youtube_channel_insights's table you have :

id | name
----------------------------------------
1  | channel_01
2  | channel_02

and for youtube_video_insights's table you have:

id | channel_id|    name    | comment_count
----------------------------------------
1  |     1     |  video_01  |      20
2  |     1     |  video_02  |      40
3  |     2     |  video_03  |      5
4  |     2     |  video_04  |      15

Now you should wright your query like this:

$sub1 = YoutubeVideoInsight ::select('comment_count', 'channel_id')
->whereRaw('channel_id = 2')->orderBy('id', 'Desc')->limit(2);

$sub2 = DB::table(DB::raw("({$sub1->toSql()}) as sub"))
->select(DB::raw('
SUM(`comment_count`) AS total_comment,
channel_id
'));

return $query = YoutubeChannelInsight ::joinSub($sub2,'sub2',function($join){
$join->on('channels.id','=','sub2.channel_id');
})->get();


问:
Jekyll cannot find include files from within a collection
Sorry if this has been answered before, I've tried searching and haven't found anything.

I am using Jekyll 3.8.5 (the version supported by github pages). I have an include file youtube.html which is located inside my jekyll _includes directory. I am trying to reference the file from a file within a collection and it is just erroring - stating that it could not find the file within [collection]/_includes which is clearly wrong and should just be _includes.

Any idea how to fix the path so it can correctly find the include file?

You can see my implementation here: https://github.com/dtsn/jungleskipper/blob/feature/members/_members/jonas-brisbane.md

I did try this in jekyll 4 without a problem.

答: I was running on MacOS beta, I switched back to the non-beta channel, reinstalled Ruby and Jekyll and I'm not getting the error any more. Wierd one...</p>


问:
Github pull request - Waiting for status to be reported
I have a pull request, build passed on VSTS, but another check "Expected - Waiting for status to be reported" never succeeds, no matter how many times I try to trigger build. I had many other pull requests with no issues.

I am not sure how to tackle this problem, how to debug this? There is no specific info than this:

Where should I check first to resolve this?

答:
To amels. All that you need it is only rerun build for the branch.
I did it for the PR in GitHub and it helped me.

For example. Go to Jenkins (or where is build can be managed manually) via details link and select your branch that relates to your pull request then push "Build Now" link. This action will rerun branch build.
After the build will complete the merge button will became accessible.


问:
Looking for information on a Sentiment Analysis algorithm / tool for .NET
I need to use/purchase some sort of tool for doing Sentiment Analysis to determine positive or negative connotation in text content. There are some terrific threads on this topic which I have read and listed below:

Algorithm to determine how positive or negative a statement/text is

NLP: Qualitatively "positive" vs "negative" sentence

Algorithm to determine how positive or negative a statement/text is (same name different thread)

The problem is each one gives a great description of the algorithm, but alludes to the complexity of doing the job from scratch and offers links to the algorithm explanations.

I need a .NET (VB.NET or C#) solution either in the form of a toolkit, API, .dll, etc. I have seen links to JAVA solutions but none really in my searches for .NET solutions.

My fallback plan is to create dictionaries of words with weights and go that route, but I would prefer something a bit more robust.

Does anyone have any information on a Sentiment Analysis solution specifically for .NET?

Thanks!

答:
After extensive research on the topic, this was found to be an depth topic way to complex to answer here in a single post. SA is not just some .dll that you drop in an application and magically the tonality of some text content can be determined. It is based on the extensive study of Natural Language Processing and is not something homegrown from some simple block of code.

The most accurate SA tools require extensive training of a system on the topic you want to analyze so the accuracy is increased. You can run text through many of the SA tools with their default algorithms, but the accuracy is quite a bit lower and not a viable solution. I spent several weeks doing the research against a sample and the results of this research is below:

Sentiment Analysis Processing For .NET Solutions:

http://allen-conway-dotnet.blogspot.com/2011/05/sentiment-analysis-processing-for-net.html

Bottom line, to have true Sentiment Analysis performed at a high accuracy, it will involve massaging and training a system that then bumps the processed data up against the SA tool to get the best results. But this is not going to be some .dll that gets dropped in a .NET application.

ContentLicense: CC BY-SA 2.5


问:
How to Query range in Cassandra
I’m trying to query a integer on Cassandra table and get the error Only EQ and IN relation are supported on the partition key(unless you use the token()function) My table is setup Is below with the query I ran. Be aware I did not setup the table nor can I change it currently.

```<code>CREATE TABLE USERS(
accName text,
accContext text,
accNumber int,
accCount int,
accHost text,
PRIMARY KEY (accName,accContext,accNumber)
);

SELECT * FROM Users WHERE accName = 'tear' and accContext = 'db1'
   and accNumber> 20200101 and accNumber<= 202002018;
</code>```

答:
It looks like your post-edit query:

```<code>SELECT * FROM Users
    WHERE accName = 'tear' and accContext = 'db1'
    and accNumber> 20200101 and accNumber<= 202002018;
</code>```

...works just fine.  If you specify accName (partition key) and accContext (1st clustering key), you absolutely can run a range query on an integer, assuming that it is the next clustering key.  However, if you were to eliminate accContext from your query, this would fail because you're not giving Cassandra enough information to efficiently retrieve the desired data.

```<code>SELECT * FROM Users WHERE accNumber> 20200101 and accNumber<= 202002018;
</code>```

So this was your query before being edited with a working solution.  And of course, you saw the error stating that range queries on partition keys only work with the token function.

Why is that?

You've probably heard that Cassandra requires a "query based" approach to data modeling.  This is because all data usually does not reside on a single node.
 Cross-node queries are expensive.  Forcing range queries on partition keys via token gives you the tools to limit your query to a node that is responsible for a specific token range.  In your case, this works:

```<code>aaron@cqlsh:stackoverflow> SELECT token(accname),accname FROM Users
    WHERE token(accname) <= -6425313154088713591
      AND token(accname) >  -7367992452875979971;

 system.token(accname) | accname
-----------------------+---------
  -6611994791738996364 |    tear

(1 rows)
</code>```

Deconstructing what I did here, by using the token function in my SELECT, I can see what the token of the string "tear" is.  Next, I can query system.peers to see which node(s) are responsible for that token, as well as to get an idea of the exact token ranges the target nodes are responsible for.

Title: How to Query range in Cassandra

Body:
I’m trying to query a integer on Cassandra table and get the error Only EQ and IN relation are supported on the partition key(unless you use the token()function) My table is setup Is below with the query I ran. Be aware I did not setup the table nor can I change it currently.

CREATE TABLE USERS(
accName text,
accContext text,
accNumber int,
accCount int,
accHost text,
PRIMARY KEY (accName,accContext,accNumber)
);

SELECT * FROM Users WHERE accName = 'tear' and accContext = 'db1'
   and accNumber> 20200101 and accNumber<= 202002018;

Body:
It looks like your post-edit query:

SELECT * FROM Users
    WHERE accName = 'tear' and accContext = 'db1'
    and accNumber> 20200101 and accNumber<= 202002018;

...works just fine.  If you specify accName (partition key) and accContext (1st clustering key), you absolutely can run a range query on an integer, assuming that it is the next clustering key.  However, if you were to eliminate accContext from your query, this would fail because you're not giving Cassandra enough information to efficiently retrieve the desired data.

SELECT * FROM Users WHERE accNumber> 20200101 and accNumber<= 202002018;

So this was your query before being edited with a working solution.  And of course, you saw the error stating that range queries on partition keys only work with the token function.

Why is that?

You've probably heard that Cassandra requires a "query based" approach to data modeling.  This is because all data usually does not reside on a single node.
 Cross-node queries are expensive.  Forcing range queries on partition keys via token gives you the tools to limit your query to a node that is responsible for a specific token range.  In your case, this works:

aaron@cqlsh:stackoverflow> SELECT token(accname),accname FROM Users
    WHERE token(accname) <= -6425313154088713591
      AND token(accname) >  -7367992452875979971;

 system.token(accname) | accname
-----------------------+---------
  -6611994791738996364 |    tear

(1 rows)

Deconstructing what I did here, by using the token function in my SELECT, I can see what the token of the string "tear" is.  Next, I can query system.peers to see which node(s) are responsible for that token, as well as to get an idea of the exact token ranges the target nodes are responsible for.


问:
git describe with two tags on the same commit
We occasionally have two tags on the same commit. When we use git describe for that commit, git describe always returns the first tag. My reading of the git-describe man page seems to indicate that the second tag should be returned (which makes more sense).

```<code>  SEARCH STRATEGY
     For each committish supplied, git describe will first look for a tag which tags
     exactly that commit. Annotated tags will always be preferred over lightweight tags,
     and tags with newer dates will always be preferred over tags with older dates.
     If an exact match is found, its name will be output and searching will stop.
</code>```

Is there a way to have git describe return the second tag?

答:
I had two tagging conventions on the same commit and wanted to keep the git describe features such as dirty, sha, and commit counts past tag etc.
So in git version 2.24.1 since I had a unique differentiating string in one tag vs the other I just used the match operator. You can also use exclude

git describe --tags --match '*xXx*'

Body:
We occasionally have two tags on the same commit. When we use git describe for that commit, git describe always returns the first tag. My reading of the git-describe man page seems to indicate that the second tag should be returned (which makes more sense).

  SEARCH STRATEGY
     For each committish supplied, git describe will first look for a tag which tags
     exactly that commit. Annotated tags will always be preferred over lightweight tags,
     and tags with newer dates will always be preferred over tags with older dates.
     If an exact match is found, its name will be output and searching will stop.

Is there a way to have git describe return the second tag?


问:
count unique values in groups pandas
I have a dataframe like this:

```<code>data = {'id': [1,1,1,2,2,3],
        'value': ['a','a','a','b','b','c'],
        'obj_id': [1,2,3,3,3,4]
}
df = pd.DataFrame (data, columns = ['id','value','obj_id'])
</code>```

I would like to get the unique counts of obj_id groupby id and value:

```<code>1 a 3
2 b 1
3 c 1
</code>```

But when I do:

```<code>result=df.groupby(['id','value'])['obj_id'].nunique().reset_index(name='obj_counts')
</code>```

the result I got was:

```<code>1 a 2
1 a 1
2 b 1
3 c 1
</code>```

so the first two rows with same id and value don't group together.

How can I fix this? Many thanks!

答:
For me your solution working nice with sample data.

Like mentioned @YOBEN_S in comments is possible problem traling whitespeces, then solution is add Series.str.strip:

```<code>data = {'id': [1,1,1,2,2,3],
        'value': ['a ','a','a','b','b','c'],
        'obj_id': [1,2,3,3,3,4]
}
df = pd.DataFrame (data, columns = ['id','value','obj_id'])

df['value'] = df['value'].str.strip()
df = df.groupby(['id','value'])['obj_id'].nunique().reset_index(name='obj_counts')
print (df)
   id value  obj_counts
0   1     a           3
1   2     b           1
2   3     c           1
</code>```

Title: count unique values in groups pandas

Body:
I have a dataframe like this:

data = {'id': [1,1,1,2,2,3],
        'value': ['a','a','a','b','b','c'],
        'obj_id': [1,2,3,3,3,4]
}
df = pd.DataFrame (data, columns = ['id','value','obj_id'])

I would like to get the unique counts of obj_id groupby id and value:

1 a 3
2 b 1
3 c 1

But when I do:

result=df.groupby(['id','value'])['obj_id'].nunique().reset_index(name='obj_counts')

the result I got was:

1 a 2
1 a 1
2 b 1
3 c 1

so the first two rows with same id and value don't group together.

How can I fix this? Many thanks!

Body:
For me your solution working nice with sample data.

Like mentioned @YOBEN_S in comments is possible problem traling whitespeces, then solution is add Series.str.strip:

data = {'id': [1,1,1,2,2,3],
        'value': ['a ','a','a','b','b','c'],
        'obj_id': [1,2,3,3,3,4]
}
df = pd.DataFrame (data, columns = ['id','value','obj_id'])

df['value'] = df['value'].str.strip()
df = df.groupby(['id','value'])['obj_id'].nunique().reset_index(name='obj_counts')
print (df)
   id value  obj_counts
0   1     a           3
1   2     b           1
2   3     c           1


问:
Are there viable usecases for using standalone PHP scripts in a TYPO3 site?
I just came across this question How can I use a PHP script in typo3 v9?
 and for me more interesting is right now - should you even do it and what are the possible usecases?

The reason I am asking: I am currently useing standalone legacy PHP scripts on a site. Not happily, as I had always intended to migrate this to an extension or deprecate it, but as is often the case - the PHP scripts may long outlive PHP itself ;-)

Consider you have some functionality, which you want to integrate in your website (as content inside the existing theme) which uses no specific TYPO3 functionality. Are there reasonable usecases to do this as PHP script without creating an extension? This answer suggests that it was possible but has been discouraged.

What are the pros / cons? Is this not recommended? Why? ...

TYPO3 >= 9.

答:
Web Content Management is quite an old discipline and proably most requirements are known and years old. TYPO3 has adapted its architecture over the years to be more safe, more easy, more secure and to easily expand functionality. Thus, the idea of adding a plain PHP script instead of using the (omnipotent) API and extension library to include functionality means skipping the offered ideas of functionality, security and maintainability.

Nevertheless, adding functionality which is like a custom PHP script is easy, as the overhead to adapt a "spaghetti code php script" into the TYPO3 API is marginal (e.g. "put it in an extension", use PSR-0, with namespaces classes register the function with a ext_localconf.php line) and would easily improve the implementation (e.g. allowing a Command in backend-context as well as CLI, or adapting a Fluid/TypoScript wrapper depending on context Web-Frontend vs PDF).

So the basic overhead is not implementation time, but having a bootstrap extension skeleton (which exists) and the necessary API knowledge (which should exist for integrators). So "quick and dirty" isn't really a valid reason.

Basically it IMHO boils down to NIH syndrome, which shouldn't need to be supported at all.

So only con's here.


问:
Combine data from different sheets BUT replace content with a given variable
Example

I have three schedules and want a merged view but content must not be displayed. Can I replace it somehow?

Body:
try:

={"Monday"\"Tuesday"\"Wednesday"\"Thursday"\"Friday";
 ARRAYFORMULA(REGEXREPLACE(
 IF(C2:G7<>""; B1&", "; )&
 IF(C10:G15<>""; B9&", "; )&
 IF(C18:G23<>""; B17; ); ", $"; ))}


问:
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.

答:
arr is a flat array, not a multi-dimensional array.  It emulates a mult-dimensional array by way of passing in the grid size.  So, if it was 5x2, then arr as a flat array would be 10 integers long, not an array of 5 rows of another array of 2 columns.

Hence, it uses simple pointer arithmetic to emulate the r,c dimensions by way of the flat array index calculation

((arr + s1 * lenght_row) + s2)

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 read browser url in sitecore jss
I tried to read browser url(this.props.location) in sitecore jss scaffold component but not able to get that.

Can anybody help with this to read browser url please ?

or

Is it possible to read window url in sitecore jss like normal javascript/reactjs?

答:
There is no special need to read browser url.

Using javascript window.location or document.location we can read.

```<code>console.log(window.location)
</code>```

Title: How to read browser url in sitecore jss

Body:
There is no special need to read browser url.

Using javascript window.location or document.location we can read.

console.log(window.location)


问:
Convert UNIX time string to date in R
I have the following UNIX time string:

"1575824800.169"

If you convert this time you will get: 12/08/2019 17:06
on an online unix converter.

However when trying to convert this in R using the following code:

```<code>as.POSIXct("1575824800.169", format='%d/%m/%Y %H:%M', origin = "1970-01-01")
</code>```

I am returned with the value NA

i'm struggling to see why the above code does not work - i have looked into different answers on here, but have not found one where the unix time string has 3 digits after the period (dot) in the string. Maybe this is the problem?

答:
The anytime package aims to help here with some built-in heuristics.  So numeric data in that range is automagically taken as (fractional) seconds since the epoch:

```<code>R> anytime::anytime(1575824800.169)
[1] "2019-12-08 11:06:40.168 CST"
R>
</code>```

There is also a wrapper for UTC and some other options should you need them:

```<code>R> anytime::utctime(1575824800.169)
[1] "2019-12-08 17:06:40.168 UTC"
R>
</code>```

Title: Convert UNIX time string to date in R

Body:
I have the following UNIX time string:

"1575824800.169"

If you convert this time you will get: 12/08/2019 17:06
on an online unix converter.

However when trying to convert this in R using the following code:

as.POSIXct("1575824800.169", format='%d/%m/%Y %H:%M', origin = "1970-01-01")

I am returned with the value NA

i'm struggling to see why the above code does not work - i have looked into different answers on here, but have not found one where the unix time string has 3 digits after the period (dot) in the string. Maybe this is the problem?

Body:
The anytime package aims to help here with some built-in heuristics.  So numeric data in that range is automagically taken as (fractional) seconds since the epoch:

R> anytime::anytime(1575824800.169)
[1] "2019-12-08 11:06:40.168 CST"
R>

There is also a wrapper for UTC and some other options should you need them:

R> anytime::utctime(1575824800.169)
[1] "2019-12-08 17:06:40.168 UTC"
R>


问:
Assigning Macro/Script to a button which changes sheets
I am looking to create a button which when pressed will take me from my Master sheet to a sheet titled '01-03'. I have used the macro function to set this up and have the following script:

```<code>function myFunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('B8').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('01-03'), true);
};
</code>```

The script works when I go into the script and click run, when I use the CTRL+ALT+SHIFT+1 keyboard shortcut and when I click on the Tools drop down and go into the Macros drop down and find the relevant macro. The only time it doesn't work is when I click on the button I have set up as I get the following error message:

"Script function 01-03 could not be found"

I have checked and double checked that I have named the macro correctly and I've run out of ideas as to why this may be happening. Can anyone help please?

答:
Your problem is that you are trying to assign the name of the script instead of the name of the function to the button.

To solve this, right click on your button -> assign script -> What script do you want to assign? -> myFunction (instead of 01-03 as you were doing).

It can seem a bit confusing as the question is not asking for the function name but for the script name. Here you can find out more about assigning scripts/functions to buttons.

I hope this has helped you, let me know if you need anything else or if you did not understood something.

Body:
I am looking to create a button which when pressed will take me from my Master sheet to a sheet titled '01-03'. I have used the macro function to set this up and have the following script:

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('B8').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('01-03'), true);
};

The script works when I go into the script and click run, when I use the CTRL+ALT+SHIFT+1 keyboard shortcut and when I click on the Tools drop down and go into the Macros drop down and find the relevant macro. The only time it doesn't work is when I click on the button I have set up as I get the following error message:

"Script function 01-03 could not be found"

I have checked and double checked that I have named the macro correctly and I've run out of ideas as to why this may be happening. Can anyone help please?


问:
Using coTurn TCP allocations with DataChannel
I have configured a coturn server which I need to use with DataChannel for a chat app.

I am trying to reach a point where I can get the coturn server provide me with a tcp allocation.

I am using the standard call of RTCPeerConnection in JS client, providing the turn URI, username and credentials.

The transport I am providing in the URI params is TCP ?transport=tcp.

With all this, I am always receiving a UDP allocation and the server logs ChannelBind requests (UDP based)

Question:

How can I achieve TCP allocations throught webRTC client, to guarantee proper data delivery of the chat app in case of using my relay server?

答:
RFC 6062, opening a TCP port on the TURN server is not supported by WebRTC. It is optional in the spec and nobody needs it since reliability is provided by SCTP.

TCP in the turn uri refers to the protocol between the client and the TURN server


问:
I want to create a layout with background with two different parts upper part will have different background color and bottom part will have different
Also outer view should have rounded corners.

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff"></solid>
    <corners android:radius="10dp" />
    <stroke
        android:width="@dimen/dimen_1"
        android:color="#1877ee" />
</shape>
</code>```

答:
Why not just use a layout over another layout?

For example, a parent linear layout overall and two children linear layouts with equal weights and different backgrounds:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical"
    android:background="#FFEB3B">
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical"
    android:background="#CC2323">
</LinearLayout>

</LinearLayout>
</code>```

Body:
Also outer view should have rounded corners.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff"></solid>
    <corners android:radius="10dp" />
    <stroke
        android:width="@dimen/dimen_1"
        android:color="#1877ee" />
</shape>

Body:
Why not just use a layout over another layout?

For example, a parent linear layout overall and two children linear layouts with equal weights and different backgrounds:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical"
    android:background="#FFEB3B">
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical"
    android:background="#CC2323">
</LinearLayout>

</LinearLayout>


答:
For any array or pointer arr and index i, the expression *(arr + i) is exactly equal to arr[i].

If we do this translation for *(*(arr+s1)+s2) that would be (arr[s1])[s2] (or arr[s1][s2]). Since arr isn't a pointer to a pointer (or array of arrays) then arr[s1][s2] doesn't make sense.

Instead you kind of emulate a 2d array (array of arrays) using a array (whose first element is pointed to by arr) and use arithmetic to calculate the single index into this array.

This is very common for dynamically allocated memory, where instead of using a jagged array (using pointers to pointers) you use a single contiguous area or memory.

It might be easier to understand with an illustration...

Lets say we want a 2d array of 2 by 3 elements. We can create it using dynamic allocation as a jagged array:

```<code>int **arr;
arr = malloc(2 * sizeof *arr);  // First dimension
for (size_t i = 0; i < 2; ++i)
    arr[i] = malloc(3 * sizeof *arr[i]);  // Second dimension
</code>```

Since we have multiple allocations, there's no locality in the array, arr[0][2] might not be followed by arr[1][0]. Locality and having the 2d array being contiguous could be good for some algorithm and use-cases.

A contiguous 2d array would be an array of arrays like

```<code>int arr[2][3];
</code>```

but this is harder to handle dynamically, so instead we allocate a single  contiguous memory area of 2 * 3 elements:

```<code>int *arr;
arr = malloc(2 * 3 * sizeof *arr);
</code>```

Unfortunately this can't be indexed in the same intuitive way as a jagged array or array of arrays (i.e. arr[0][1] isn't possible). But with some clever arithmetic it is possible: arr[row_index * row_length + column_index] will be like arr[row_index][column_index] (for a jagged array or array of arrays).

Title: Can't understand exactly the pointers in 2d array

Body:
For any array or pointer arr and index i, the expression *(arr + i) is exactly equal to arr[i].

If we do this translation for *(*(arr+s1)+s2) that would be (arr[s1])[s2] (or arr[s1][s2]). Since arr isn't a pointer to a pointer (or array of arrays) then arr[s1][s2] doesn't make sense.

Instead you kind of emulate a 2d array (array of arrays) using a array (whose first element is pointed to by arr) and use arithmetic to calculate the single index into this array.

This is very common for dynamically allocated memory, where instead of using a jagged array (using pointers to pointers) you use a single contiguous area or memory.

It might be easier to understand with an illustration...

Lets say we want a 2d array of 2 by 3 elements. We can create it using dynamic allocation as a jagged array:

int **arr;
arr = malloc(2 * sizeof *arr);  // First dimension
for (size_t i = 0; i < 2; ++i)
    arr[i] = malloc(3 * sizeof *arr[i]);  // Second dimension

Since we have multiple allocations, there's no locality in the array, arr[0][2] might not be followed by arr[1][0]. Locality and having the 2d array being contiguous could be good for some algorithm and use-cases.

A contiguous 2d array would be an array of arrays like

int arr[2][3];

but this is harder to handle dynamically, so instead we allocate a single  contiguous memory area of 2 * 3 elements:

int *arr;
arr = malloc(2 * 3 * sizeof *arr);

Unfortunately this can't be indexed in the same intuitive way as a jagged array or array of arrays (i.e. arr[0][1] isn't possible). But with some clever arithmetic it is possible: arr[row_index * row_length + column_index] will be like arr[row_index][column_index] (for a jagged array or array of arrays).


问:
sklearn ImportError: cannot import name plot_roc_curve
I am trying to plot a Receiver Operating Characteristics (ROC) curve with cross validation, following the example provided in sklearn's documentation. However, the following import gives an ImportError, in both python2 and python3.

```<code>from sklearn.metrics import plot_roc_curve
</code>```

Error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name plot_roc_curve
</code>```

python-2.7 sklearn version: 0.20.2.

python-3.6 sklearn version: 0.21.3.

I found that the following import works fine, but it's not quite the same as plot_roc_curve.

```<code>from sklearn.metrics import roc_curve
</code>```

Is plot_roc_curve deprecated? Could somebody try the code and let me know the sklearn version if it works?

答: Plotting API was introduced in the version 0.22. As mentioned here, Scikit-learn 0.20 was the last version to support Python 2.7 and Python 3.4. Scikit-learn now requires Python 3.5 or newer.</p>

Body:
I am trying to plot a Receiver Operating Characteristics (ROC) curve with cross validation, following the example provided in sklearn's documentation. However, the following import gives an ImportError, in both python2 and python3.

from sklearn.metrics import plot_roc_curve

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name plot_roc_curve

python-2.7 sklearn version: 0.20.2.

python-3.6 sklearn version: 0.21.3.

I found that the following import works fine, but it's not quite the same as plot_roc_curve.

from sklearn.metrics import roc_curve

Is plot_roc_curve deprecated? Could somebody try the code and let me know the sklearn version if it works?


问:
Copy constructor with non-const argument suggested by thread-safety rules?
I have a wrapper to some piece of legacy code.

```<code>class A{
   L* impl_; // the legacy object has to be in the heap, could be also unique_ptr
   A(A const&) = delete;
   L* duplicate(){L* ret; legacy_duplicate(impl_, &L); return ret;}
   ... // proper resource management here
};
</code>```

In this legacy code, the function that “duplicates” an object is not thread safe (when calling on the same first argument), therefore it is not marked const in the wrapper. I guess following modern rules: https://herbsutter.com/2013/01/01/video-you-dont-know-const-and-mutable/

This duplicate looks like a good way to implement a copy constructor, except for the detail that is it not const. Therefore I cannot do this directly:

```<code>class A{
   L* impl_; // the legacy object has to be in the heap
   A(A const& other) : L{other.duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

So what is the way out this paradoxical situation?

(Let's say also that legacy_duplicate is not thread-safe but I know leaves the object in the original state when it exits. Being a C-function the behavior is only documented but has no concept of constness.)

I can think of many possible scenarios:

(1) One possibility is that there is no way to implement a copy constructor with the usual semantics at all. (Yes, I can move the object and that is not what I need.)

(2) On the other hand, copying an object is inherently non-thread-safe in the sense that copying a simple type can find the source in an half-modified state, so I can just go forward and do this perhaps,

```<code>class A{
   L* impl_;
   A(A const& other) : L{const_cast<A&>(other).duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

(3) or even just declare duplicate const and lie about thread safety in all contexts. (After all the legacy function doesn't care about const so the compiler will not even complain.)

```<code>class A{
   L* impl_;
   A(A const& other) : L{other.duplicate()}{}
   L* duplicate() const{L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

(4) Finally, I can follow the logic and make a copy-constructor that takes a non-const argument.

```<code>class A{
   L* impl_;
   A(A const&) = delete;
   A(A& other) : L{other.duplicate()}{}
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};
</code>```

It turns out that this works in many contexts, because these objects are not usually const.

The question is, it this a valid or common route?

I cannot name them, but I intuitively expect lots of problems down the road of having a non-const copy constructor. Probably it will not qualify as a value-type because of this subtlety.

(5) Finally, although this seems to be an overkill and could have a steep runtime cost, I could add a mutex:

```<code>class A{
   L* impl_;
   A(A const& other) : L{other.duplicate_locked()}{}
   L* duplicate(){
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   L* duplicate_locked() const{
      std::lock_guard<std::mutex> lk(mut);
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   mutable std::mutex mut;
};
</code>```

But being forced to do this looks like pessimization and makes the class bigger. I am not sure. I am currently leaning towards (4), or (5) or a combination of both.

EDIT 1:

Another option:

(6) Forget about all the non-sense of the duplicate member function and simply call legacy_duplicate from the constructor and declare that the copy constructor is not thread safe. (And if necessary make another thread-safe versión of the type, A_mt)

```<code>class A{
   L* impl_;
   A(A const& other){legacy_duplicate(other.impl_, &impl_);}
};
</code>```

EDIT 2:

This could be a good model for what the legacy function does. Note that by touching the input the call is not thread safe with respect to the value represented by the first argument.

```<code>void legacy_duplicate(L* in, L** out){
   *out = new L{};
   char tmp = in[0];
   in[0] = tmp;
   std::memcpy(*out, in, sizeof *in); return;
}
</code>```

EDIT 3:
I lately learned that std::auto_ptr had a similar problem of having a non-const "copy" constructor. The effect was that auto_ptr couldn't be used inside a container. https://www.quantstart.com/articles/STL-Containers-and-Auto_ptrs-Why-They-Dont-Mix/

答:
TLDR: Either fix the implementation of your duplication function, or introduce a mutex (or some more appropriate locking device, perhaps a spinlock, or make sure your mutex is configured to spin before doing anything heavier) for now, then fix the implementation of duplication and remove the locking when the locking actually becomes a problem.

I think a key point to notice is that you are adding a feature that did not exist before: the ability to duplicate an object from multiple threads at the same time.

Obviously, under the conditions you have decribed, that would have been a bug - a race condition, if you had been doing that before, without using some kind of external synchronization.

Therefore, any use of the this new feature will be something you add to your code, not inherit as existing functionality. You should be the one who knows whether adding the extra locking will actually be costly - depending on how often you are going to be using this new feature.

Also, based on the perceived complexity of the object - by the special treatment you are giving it, I'm going to assume that the duplication procedure is not a trivial one, therefore, already quite expensive in terms of performance.

Based on the above, you have two paths you can follow:

A) You know that copying this object from multiple threads will not happen often enough for the overhead of the additional locking to be costly - perfhaps trivially cheap, at least given that the existing duplication procedure is costly enough on its own, if you use a spinlock/pre-spinning mutex, and there is no contention on it.

B) You suspect that copying from multiple threads will happen often enough for the extra locking to be a problem. Then you really have only one option - fix your duplication code. If you don't fix it, you will need locking anyway, whether at this layer of abstraction or somewhere else, but you will need it if you don't want bugs - and as we've established, in this path, you assume that locking will be too costly, therefore, the only option is fixing the duplication code.

I suspect that you are really in situation A, and just adding a spinlock/spinning mutex that has close to no performance penalty when uncontested, will work just fine (remember to benchmark it, though).

There is, in theory, another situation:

C) In contrast to the seeming complexity of the duplication function, it is actually trivial, but can't be fixed for some reason; it is so trivial that even an uncontested spinlock introduces an unacceptable performance degradation to duplication; duplication on parallell threads is used rarely; duplication on a single thread is used all the time, making the performance degradation absolutely unacceptable.

In this case, I suggest the following: declare the default copy constructors / operators deleted, to prevent anyone from using them accidentally. Create two explicitly callable duplication methods, a thread safe one, and a thread unsafe one; make your users call them explicitly, depending on context. Again, there is no other way to achieve acceptable single thread performance and safe multi threading, if you really are in this situation and you just can't fix the existing duplication implementation. But I feel it is highly unlikely that you really are.

Just add that mutex/spinlock and benchmark.

Body:
I have a wrapper to some piece of legacy code.

class A{
   L* impl_; // the legacy object has to be in the heap, could be also unique_ptr
   A(A const&) = delete;
   L* duplicate(){L* ret; legacy_duplicate(impl_, &L); return ret;}
   ... // proper resource management here
};

In this legacy code, the function that “duplicates” an object is not thread safe (when calling on the same first argument), therefore it is not marked const in the wrapper. I guess following modern rules: https://herbsutter.com/2013/01/01/video-you-dont-know-const-and-mutable/

This duplicate looks like a good way to implement a copy constructor, except for the detail that is it not const. Therefore I cannot do this directly:

class A{
   L* impl_; // the legacy object has to be in the heap
   A(A const& other) : L{other.duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

So what is the way out this paradoxical situation?

(Let's say also that legacy_duplicate is not thread-safe but I know leaves the object in the original state when it exits. Being a C-function the behavior is only documented but has no concept of constness.)

I can think of many possible scenarios:

(1) One possibility is that there is no way to implement a copy constructor with the usual semantics at all. (Yes, I can move the object and that is not what I need.)

(2) On the other hand, copying an object is inherently non-thread-safe in the sense that copying a simple type can find the source in an half-modified state, so I can just go forward and do this perhaps,

class A{
   L* impl_;
   A(A const& other) : L{const_cast(other).duplicate()}{} // error calling a non-const function
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

(3) or even just declare duplicate const and lie about thread safety in all contexts. (After all the legacy function doesn't care about const so the compiler will not even complain.)

class A{
   L* impl_;
   A(A const& other) : L{other.duplicate()}{}
   L* duplicate() const{L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

(4) Finally, I can follow the logic and make a copy-constructor that takes a non-const argument.

class A{
   L* impl_;
   A(A const&) = delete;
   A(A& other) : L{other.duplicate()}{}
   L* duplicate(){L* ret; legacy_duplicate(impl_, &ret); return ret;}
};

It turns out that this works in many contexts, because these objects are not usually const.

The question is, it this a valid or common route?

I cannot name them, but I intuitively expect lots of problems down the road of having a non-const copy constructor. Probably it will not qualify as a value-type because of this subtlety.

(5) Finally, although this seems to be an overkill and could have a steep runtime cost, I could add a mutex:

class A{
   L* impl_;
   A(A const& other) : L{other.duplicate_locked()}{}
   L* duplicate(){
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   L* duplicate_locked() const{
      std::lock_guard<std::mutex> lk(mut);
      L* ret; legacy_duplicate(impl_, &ret); return ret;
   }
   mutable std::mutex mut;
};

But being forced to do this looks like pessimization and makes the class bigger. I am not sure. I am currently leaning towards (4), or (5) or a combination of both.

EDIT 1:

Another option:

(6) Forget about all the non-sense of the duplicate member function and simply call legacy_duplicate from the constructor and declare that the copy constructor is not thread safe. (And if necessary make another thread-safe versión of the type, A_mt)

class A{
   L* impl_;
   A(A const& other){legacy_duplicate(other.impl_, &impl_);}
};

EDIT 2:

This could be a good model for what the legacy function does. Note that by touching the input the call is not thread safe with respect to the value represented by the first argument.

void legacy_duplicate(L* in, L** out){
   *out = new L{};
   char tmp = in[0];
   in[0] = tmp;
   std::memcpy(*out, in, sizeof *in); return;
}

EDIT 3:
I lately learned that std::auto_ptr had a similar problem of having a non-const "copy" constructor. The effect was that auto_ptr couldn't be used inside a container. https://www.quantstart.com/articles/STL-Containers-and-Auto_ptrs-Why-They-Dont-Mix/


问:
How to create a simple android browser?
I simply want to create an apk that will take a url, and open a window and simply run like a browser

so far I have:

```<code>public class Browser extends Activity {

    WebView mWebView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.google.com");
    }
}
</code>```

This works fine, except when i open a link it'll take me to the actual browser, I'm having trouble where to place this code to override links opening in a new browser:

```<code>private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
</code>```

答:
Check out my project called FriarFramework, which is an ebook app publisher.

It basically takes a collection of HTML files locally and packages them up into a WebView.

https://github.com/hanchang/Friar-Framework

Title: How to create a simple android browser?

Body:
I simply want to create an apk that will take a url, and open a window and simply run like a browser

so far I have:

public class Browser extends Activity {

    WebView mWebView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.google.com");
    }
}

This works fine, except when i open a link it'll take me to the actual browser, I'm having trouble where to place this code to override links opening in a new browser:

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}


问:
How to create a column for each level of another column in R?
The goal I am trying to achieve is an expanded data frame in which I will have created a new column for each level of a specific column in R. Here is a sample of the initial data frame and the data frame I am trying to achieve:

Original Data Frame:

```<code>record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5
</code>```

Goal Data Frame:

```<code>crop_land.BiocapPerCap     crop_land.Consumption     fishing_ground.BiocapPerCap      fishing_ground.Consumption
1.5                        2.3                       3.4                              0.5
</code>```

答:
Using tidyr is one option.

tidyr::pivot_longer() converts crop_land and fishing_ground to variable-value pairs. tidyr::unite() combines the record and variable to new names.
tidyr::pivot_wider() creates the wide data frame you are after.

```<code>library(tidyr)
library(magrittr) # for %>%

tst <-  data.frame(
  record = c("BiocapPerCap", "Consumption"),
  crop_land = c(1.5, 2.3),
  fishing_ground = c(3.4, 0.5)
)

pivot_longer(tst, -record) %>%
  unite(new_name, record, name, sep = '.') %>%
  pivot_wider(names_from = new_name, values_from = value)

</code>```

Body:
The goal I am trying to achieve is an expanded data frame in which I will have created a new column for each level of a specific column in R. Here is a sample of the initial data frame and the data frame I am trying to achieve:

Original Data Frame:

record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5

Goal Data Frame:

crop_land.BiocapPerCap     crop_land.Consumption     fishing_ground.BiocapPerCap      fishing_ground.Consumption
1.5                        2.3                       3.4                              0.5

Body:
Using tidyr is one option.

tidyr::pivot_longer() converts crop_land and fishing_ground to variable-value pairs. tidyr::unite() combines the record and variable to new names.
tidyr::pivot_wider() creates the wide data frame you are after.

library(tidyr)
library(magrittr) # for %>%

tst <-  data.frame(
  record = c("BiocapPerCap", "Consumption"),
  crop_land = c(1.5, 2.3),
  fishing_ground = c(3.4, 0.5)
)

pivot_longer(tst, -record) %>%
  unite(new_name, record, name, sep = '.') %>%
  pivot_wider(names_from = new_name, values_from = value)


问:
macOS Sierra 10.12 : Homebrew can't brew upgrade Warning: We do not provide support for this pre-release version
Yesterday I upgrade macOS Sierra, When I brew upgade,appeared error:

```<code>     Warning: You are using OS X 10.12.
     We do not provide support for this pre-release version.
     You may encounter build failures or other breakages.
     Please create pull-requests instead of filing issues.
</code>```

I search long time for solve for this problem ,

eg:

```<code>sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
</code>```

or:

```<code> sudo chown $(whoami):admin /usr/local && sudo chown -R $(whoami):admin /usr/local
</code>```

And then reboot OS,there are still this problem.

/usr/local exists already, it can be writed.

So,I don't  use brew upgrade, please help,I have a long time can't use it.

答:
This worked for me :</p>

```<code>sudo xcode-select -r
Edit and set the date of your Mac as October 1st, 2019
sudo xcodebuild -runFirstLaunch
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
brew upgrade
</code>```

Body:
Yesterday I upgrade macOS Sierra, When I brew upgade,appeared error:

     Warning: You are using OS X 10.12.
     We do not provide support for this pre-release version.
     You may encounter build failures or other breakages.
     Please create pull-requests instead of filing issues.

I search long time for solve for this problem ,

eg:

sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

or:

 sudo chown $(whoami):admin /usr/local && sudo chown -R $(whoami):admin /usr/local

And then reboot OS,there are still this problem.

/usr/local exists already, it can be writed.

So,I don't  use brew upgrade, please help,I have a long time can't use it.

Body:
This worked for me :

sudo xcode-select -r
Edit and set the date of your Mac as October 1st, 2019
sudo xcodebuild -runFirstLaunch
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
brew upgrade


问:
React Native Web - Control the html tag generated by View?
I have a react native web project. At one point, I would like my View instead of generating a
 to generate a  element.

Is there a way to control this? I am hoping for some sort of htmlTag attribute that gets ignored if this is not compiling for a browser environment.

答:
There was a component prop but it's removed in favor of accessibilityRole (Remove component prop).

You can use accessibilityRole to specify the label tag and even create a custom element using it:

function Label({ text }) {
  return <View accessibilityRole="label">{text}</View>
}
```

<p>and then use it like this:</p>

<pre class="lang-jsx prettyprint-override"><code>export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <View>
          <Label text="Test input:"/>
          <TextInput name="test-input"/>
        </View>
      </View>
    );
  }
}
</code>```

Check this working Expo snack: https://snack.expo.io/@clytras/change-rn-web-div-tag

Body:
There was a component prop but it's removed in favor of accessibilityRole (Remove component prop).

You can use accessibilityRole to specify the label tag and even create a custom element using it:

function Label({ text }) {
  return <View accessibilityRole="label">{text}</View>
}

and then use it like this:

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <View>
          <Label text="Test input:"/>
          <TextInput name="test-input"/>
        </View>
      </View>
    );
  }
}

Check this working Expo snack: https://snack.expo.io/@clytras/change-rn-web-div-tag


Title: Svg icon shows when viewed locally but doesn't show when deployed

Body:
I have a weird issue. I a musing a sprite for all my SVGs. They all work just fine, and even the one in issue works fine when I run my code locally.
But when I deploy it (firebase), one of the SVGs just doesn't show up. What could be the reason?

Here's the code for two of the SVGs. smile is the one that gives me issues, the other one doesn't.

<symbol id="create" viewBox="0 0 24 24">
<title>create</title>
<path d="M11 6.999c2.395.731 4.27 2.607 4.999 5.001.733-2.395 2.608-4.269 5.001-5-2.393-.731-4.268-2.605-5.001-5-.729 2.394-2.604 4.268-4.999 4.999zm7 7c1.437.438 2.562 1.564 2.999 3.001.44-1.437 1.565-2.562 3.001-3-1.436-.439-2.561-1.563-3.001-3-.437 1.436-1.562 2.561-2.999 2.999zm-6 5.501c1.198.365 2.135 1.303 2.499 2.5.366-1.198 1.304-2.135 2.501-2.5-1.197-.366-2.134-1.302-2.501-2.5-.364 1.197-1.301 2.134-2.499 2.5zm-6.001-12.5c-.875 2.873-3.128 5.125-5.999 6.001 2.876.88 5.124 3.128 6.004 6.004.875-2.874 3.128-5.124 5.996-6.004-2.868-.874-5.121-3.127-6.001-6.001z"/>
</symbol>

<symbol id="smile" viewBox="0 0 24 24">
<title>smile</title>
<path d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm6 14h-12c.331 1.465 2.827 4 6.001 4 3.134 0 5.666-2.521 5.999-4zm0-3.998l-.755.506s-.503-.948-1.746-.948c-1.207 0-1.745.948-1.745.948l-.754-.506c.281-.748 1.205-2.002 2.499-2.002 1.295 0 2.218 1.254 2.501 2.002zm-7 0l-.755.506s-.503-.948-1.746-.948c-1.207 0-1.745.948-1.745.948l-.754-.506c.281-.748 1.205-2.002 2.499-2.002 1.295 0 2.218 1.254 2.501 2.002z"/>
</symbol>

They are both wrapped between these two together with all the other symbols

<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
.....svgs......
</defs>
</svg>

Body:
You can resolve this by changing the <symbol> tag to one of <svg>.

I'm looking through the W3C documentation but I can't find the <symbol> tag, probably you or "firebase" are using some API or something to adjust the code, try something like this:

<svg id="smile" viewBox="0 0 24 24">
 <title>smile</title>
 <path d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm6 14h-12c.331 1.465 2.827 4 6.001 4 3.134 0 5.666-2.521 5.999-4zm0-3.998l-.755.506s-.503-.948-1.746-.948c-1.207 0-1.745.948-1.745.948l-.754-.506c.281-.748 1.205-2.002 2.499-2.002 1.295 0 2.218 1.254 2.501 2.002zm-7 0l-.755.506s-.503-.948-1.746-.948c-1.207 0-1.745.948-1.745.948l-.754-.506c.281-.748 1.205-2.002 2.499-2.002 1.295 0 2.218 1.254 2.501 2.002z"/>
 </svg>

You may be using an API that I think is also practical, which is the fontAwesome API, it is simple to move and fits well with the text.


问:
How i use ArrayList<HashMap> of three String type parameters?
How can I use ArrayList>
three String member?
I want have </p>

```<code>String email = do_id.getString("email");
String phone = do_id.getString("phone");
String age = do_id.getString("age");
map.put("KEY_EMAIL",email);
map.put("KEY_PHONE",phone);
map.put("KEY_age",age);
getDatalist.add(map);
</code>```

答:
You can't.

This's the declaration for Java's HashMap

public class HashMap<K,V> extends AbstractMap<K,V>

As you can see it has two type parameters K and V, you're trying to pass it three which won't work.

You should instead create a data class (POJO) to hold your strings or use a triple (tuple):

```<code>public final class Triple<L, M, R> {

    private final L left;
    private final M middle;
    private final R right;

    public Triple(L left, M middle, R right) {
        this.left= left;
        this.middle= middle;
        this.right= right;
    }

    public L getLeft() {
        return this.left;
    }

    public M getMiddle() {
        return this.middle;
    }

    public R getRight() {
        return this.right;
    }

    // Android Studio should be able to generate hashCode, equals and toString for you
}

final List<Triple<String, String, String>> list = new ArrayList();
list.add(Triple(email, phone, age));
</code>```

Or you can use apache commons' Triple class

Body:
How can I use ArrayList>
three String member?
I want have

String email = do_id.getString("email");
String phone = do_id.getString("phone");
String age = do_id.getString("age");
map.put("KEY_EMAIL",email);
map.put("KEY_PHONE",phone);
map.put("KEY_age",age);
getDatalist.add(map);

Body:
You can't.

This's the declaration for Java's HashMap

public class HashMap<K,V> extends AbstractMap<K,V>

As you can see it has two type parameters K and V, you're trying to pass it three which won't work.

You should instead create a data class (POJO) to hold your strings or use a triple (tuple):

public final class Triple<L, M, R> {

    private final L left;
    private final M middle;
    private final R right;

    public Triple(L left, M middle, R right) {
        this.left= left;
        this.middle= middle;
        this.right= right;
    }

    public L getLeft() {
        return this.left;
    }

    public M getMiddle() {
        return this.middle;
    }

    public R getRight() {
        return this.right;
    }

    // Android Studio should be able to generate hashCode, equals and toString for you
}

final List<Triple<String, String, String>> list = new ArrayList();
list.add(Triple(email, phone, age));

Or you can use apache commons' Triple class


问:
NameError: name 'cap' is not defined
I have defined cap in

```<code>def fingerCursor(device):
    global cap
    global cap_height
    global cap_width
    cap = cv2.VideoCapture(device)
        #cap.set(cv2.cap_PROP_FRAME_HEIGHT,720)
        #cap.set(cv2.cap_PROP_FRAME_WIDTH,1280)
    cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
    cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
        #print(cap_height,cap_width)
</code>```

But still whenever I am running this part of my code, it says cap not defined. It also has the same problem with cap_height and cap_width.

```<code>while(cap.isOpened()):
        ## capture frame-by-frame
        ret, frame_raw = cap.read()
        while not ret:
            ret,frame_raw = cap.read()
        frame_raw = cv2.flip(frame_raw, 1)
        frame = frame_raw[:round(cap_height),:round(cap_width)] # ROI of the image
        cv2.imshow("raw_frame",frame)
</code>```

答:
You do not create the variables in the global scope. And anyway, it is generally a bad idea to use global this way. I suggest changing your function to:

```<code>def fingerCursor(device):
    cap = cv2.VideoCapture(device)
    cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
    cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
    return (cap, cap_height, cap_width)
</code>```

and then using it like this:

```<code>cap, cap_height, cap_width = fingerCursor(whatever)
</code>```

Title: NameError: name 'cap' is not defined

Body:
I have defined cap in

def fingerCursor(device):
    global cap
    global cap_height
    global cap_width
    cap = cv2.VideoCapture(device)
        #cap.set(cv2.cap_PROP_FRAME_HEIGHT,720)
        #cap.set(cv2.cap_PROP_FRAME_WIDTH,1280)
    cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
    cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
        #print(cap_height,cap_width)

But still whenever I am running this part of my code, it says cap not defined. It also has the same problem with cap_height and cap_width.

while(cap.isOpened()):
        ## capture frame-by-frame
        ret, frame_raw = cap.read()
        while not ret:
            ret,frame_raw = cap.read()
        frame_raw = cv2.flip(frame_raw, 1)
        frame = frame_raw[:round(cap_height),:round(cap_width)] # ROI of the image
        cv2.imshow("raw_frame",frame)

Body:
You do not create the variables in the global scope. And anyway, it is generally a bad idea to use global this way. I suggest changing your function to:

def fingerCursor(device):
    cap = cv2.VideoCapture(device)
    cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
    cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
    return (cap, cap_height, cap_width)

and then using it like this:

cap, cap_height, cap_width = fingerCursor(whatever)


问:
algorithm writer of tkinter
I'm writing an algorithm that provides a tkinter program as output (I hope I explained myself) the program works by dragging the combobox, the text ... into a space and memorizing the coordinates.
I decided to do it with pygame, (I took the skeleton of the program from the internet and then modified it).
I have encountered several problems:

I have a problem inserting multiple images (for now I have only
inserted one),

I can't memorize the coordinates, I tried with print (event) but it doesn't work,

I can not insert the image in a specific point of the root.

here is my code:

```<code>import os,sys
import pygame as pg
pg.init()
a=0
b=0
c=200
d=200
event = pg.event.poll()
Sfondo = pg.image.load("Sfondo.jpg")

def DisegnaBackground (a,b):
    Screen.blit(Sfondo,(a,b))

class Character:

    def __init__(self,rect):
        self.rect = pg.Rect(rect)
        self.click = False
        self.image = pg.image.load("ComboBox.png").convert()
        Screen.blit(self.image, (c,d))

    def update(self,surface):
        if self.click:
            self.rect.center = pg.mouse.get_pos()
        surface.blit(self.image,self.rect)

def main(Surface,Player):
    game_event_loop(Player)
    DisegnaBackground (a,b)
    Player.update(Surface)

def game_event_loop(Player):
    for event in pg.event.get():
        if event.type == pg.MOUSEBUTTONDOWN:
            if Player.rect.collidepoint(event.pos):
                Player.click = True
        elif event.type == pg.MOUSEBUTTONUP:
            Player.click = False
        elif event.type == pg.QUIT:
            pg.quit(); sys.exit()

if __name__ == "__main__":

    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pg.init()
    Screen = pg.display.set_mode((1500,800))
    MyClock = pg.time.Clock()
    MyPlayer = Character((0,0,200,24))
    MyPlayer.rect.center = Screen.get_rect().center
    while 1:
        main(Screen,MyPlayer)
        pg.display.update()
        MyClock.tick(60)

        print(event)

</code>```

答:
There are a number of problems. First, try to make sure not to mix global and local variables. Try re-writing the function like this:

```<code>def DisegnaBackground (surface, a, b):
    surface.blit(Sfondo, (a, b))
</code>```

For this to work, you have to update your main too:

```<code>def main(Surface,Player):
    game_event_loop(Player)
    DisegnaBackground (Surface, a, b)
    Player.update(Surface)
</code>```

Finally, you do not need to display your character immediately after the creation, so you can leave the init function as

```<code>    def __init__(self,rect):
        self.rect = pg.Rect(rect)
        self.click = False
        self.image = pg.image.load("ComboBox.png").convert()
</code>```

I hope it helps.

Title: algorithm writer of tkinter

Body:
I'm writing an algorithm that provides a tkinter program as output (I hope I explained myself) the program works by dragging the combobox, the text ... into a space and memorizing the coordinates.
I decided to do it with pygame, (I took the skeleton of the program from the internet and then modified it).
I have encountered several problems:

I have a problem inserting multiple images (for now I have only
inserted one),

I can't memorize the coordinates, I tried with print (event) but it doesn't work,

I can not insert the image in a specific point of the root.

here is my code:

import os,sys
import pygame as pg
pg.init()
a=0
b=0
c=200
d=200
event = pg.event.poll()
Sfondo = pg.image.load("Sfondo.jpg")

def DisegnaBackground (a,b):
    Screen.blit(Sfondo,(a,b))

class Character:

    def __init__(self,rect):
        self.rect = pg.Rect(rect)
        self.click = False
        self.image = pg.image.load("ComboBox.png").convert()
        Screen.blit(self.image, (c,d))

    def update(self,surface):
        if self.click:
            self.rect.center = pg.mouse.get_pos()
        surface.blit(self.image,self.rect)

def main(Surface,Player):
    game_event_loop(Player)
    DisegnaBackground (a,b)
    Player.update(Surface)

def game_event_loop(Player):
    for event in pg.event.get():
        if event.type == pg.MOUSEBUTTONDOWN:
            if Player.rect.collidepoint(event.pos):
                Player.click = True
        elif event.type == pg.MOUSEBUTTONUP:
            Player.click = False
        elif event.type == pg.QUIT:
            pg.quit(); sys.exit()

if __name__ == "__main__":

    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pg.init()
    Screen = pg.display.set_mode((1500,800))
    MyClock = pg.time.Clock()
    MyPlayer = Character((0,0,200,24))
    MyPlayer.rect.center = Screen.get_rect().center
    while 1:
        main(Screen,MyPlayer)
        pg.display.update()
        MyClock.tick(60)

        print(event)

Body:
There are a number of problems. First, try to make sure not to mix global and local variables. Try re-writing the function like this:

def DisegnaBackground (surface, a, b):
    surface.blit(Sfondo, (a, b))

For this to work, you have to update your main too:

def main(Surface,Player):
    game_event_loop(Player)
    DisegnaBackground (Surface, a, b)
    Player.update(Surface)

Finally, you do not need to display your character immediately after the creation, so you can leave the init function as

    def __init__(self,rect):
        self.rect = pg.Rect(rect)
        self.click = False
        self.image = pg.image.load("ComboBox.png").convert()

I hope it helps.