问:
Install CDH 6.0.1 have trouble with install cm-agent
with cloudera install doc step by step I have in trouble with Install Agents
like this:

It said install failed and can not receive signal.
And I find the log like this:

```<code>    [13/Nov/2018 16:44:19 +0000] 4306 MainThread agent        ERROR    Heartbeating to ryze-1.bigdata.com:7182 failed.
Traceback (most recent call last):
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/cmf/agent.py", line 1371, in _send_heartbeat
    response = self.requestor.request('heartbeat', heartbeat_data)
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 141, in request
    return self.issue_request(call_request, message_name, request_datum)
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 254, in issue_request
    call_response = self.transceiver.transceive(call_request)
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 483, in transceive
    result = self.read_framed_message()
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 489, in read_framed_message
    framed_message = response_reader.read_framed_message()
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 417, in read_framed_message
    raise ConnectionClosedException("Reader read 0 bytes.")
ConnectionClosedException: Reader read 0 bytes.
</code>```

I try to solve it with google I already check these setting.

/etc/cloudera-scm-agent/config.ini the port set 7182 and server_host set ryze-1.bigdata.com.

iptable altready shutdown with sudo service iptables stop

ryze-1.bigdata.com is reachable. and telnet ryze-1.bigdata.com 7183 can succeed.

OS: Centos7.4
Platform: AliCloud

So what can I do? Any one can help me ?

答:
I closed the ssl option.
Everything is fine now.......</p>

Body:
with cloudera install doc step by step I have in trouble with Install Agents
like this:

It said install failed and can not receive signal.
And I find the log like this:

    [13/Nov/2018 16:44:19 +0000] 4306 MainThread agent        ERROR    Heartbeating to ryze-1.bigdata.com:7182 failed.
Traceback (most recent call last):
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/cmf/agent.py", line 1371, in _send_heartbeat
    response = self.requestor.request('heartbeat', heartbeat_data)
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 141, in request
    return self.issue_request(call_request, message_name, request_datum)
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 254, in issue_request
    call_response = self.transceiver.transceive(call_request)
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 483, in transceive
    result = self.read_framed_message()
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 489, in read_framed_message
    framed_message = response_reader.read_framed_message()
  File "/opt/cloudera/cm-agent/lib/python2.7/site-packages/avro/ipc.py", line 417, in read_framed_message
    raise ConnectionClosedException("Reader read 0 bytes.")
ConnectionClosedException: Reader read 0 bytes.

I try to solve it with google I already check these setting.

/etc/cloudera-scm-agent/config.ini the port set 7182 and server_host set ryze-1.bigdata.com.

iptable altready shutdown with sudo service iptables stop

ryze-1.bigdata.com is reachable. and telnet ryze-1.bigdata.com 7183 can succeed.

OS: Centos7.4
Platform: AliCloud

So what can I do? Any one can help me ?


来源: stackexchange

问:
Replace values in a dataframe with values from another dataframe - Regex
I have input data like as shown below. Here 'gender' and 'ethderived' are two columns. I would like to replace their values like 1,2,3 etc with categorical values. Ex - 1 with Male, 2 with Female

The mapping file looks like as shown below - sample 2 columns

Input data looks like as shown below

I expect my output dataframe to look like this

I have tried to do this using the below code. Though the code works fine, I don't see any replace happening. Can you please help me with this?

```<code>mapp = pd.read_csv('file2.csv')
data = pd.read_csv('file1.csv')
for col in mapp:
    if col in data.columns:
        print(col)
        s = list(mapp.loc[(mapp[col].str.contains('^\d')==True)].index)
        print("s is",s)
        for i in s:
           print("i is",i)
            try:
               value = mapp[col][i].split('. ')
               print("value 0 is",value[0])
               print("value 1 is",value[1])
               if value[0] in data[col].values:
               data.replace({col:{value[0]:value[1]}})
            except:
                print("column not present")
   else:
       print("No")
</code>```

Please note that I have shown only two columns but in real time there might more than 600 columns. Any elegant approach/suggestions to make it simple is helpful. As I have two separate csv files, any suggestions on merge/join etc will also be helpful but please note that my mapping file contains values as "1. Male", "2. Female". hence I used regex

Also note that, several other column values can also have mapping values that start with 1. ex: 1. Single, 2. Married, 3. Divorced etc

Looking forward to your help

答:
Use DataFrame.replace with nested dictionaries - first key define colum name for replace and another values for replace created by function Series.str.extract:

```<code>df = pd.DataFrame({'Gender':['1.Male','2.Female', np.nan],
                   'Ethnicity':['1.Chinese','2.Indian','3.Malay']})
print (df)
     Gender  Ethnicity
0    1.Male  1.Chinese
1  2.Female   2.Indian
2       NaN    3.Malay

d={x:df[x].str.extract(r'(\d+)\.(.+)').dropna().set_index(0)[1].to_dict() for x in df.columns}
print (d)
{'Gender': {'1': 'Male', '2': 'Female'},
 'Ethnicity': {'1': 'Chinese', '2': 'Indian', '3': 'Malay'}}

df1 = pd.DataFrame({'Gender':[2,1,2,1],
                   'Ethnicity':[1,2,3,1]})
print (df1)
   Gender  Ethnicity
0       2          1
1       1          2
2       2          3
3       1          1

#convert to strings before replace
df2 = df1.astype(str).replace(d)
print (df2)
   Gender Ethnicity
0  Female   Chinese
1    Male    Indian
2  Female     Malay
3    Male   Chinese
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have input data like as shown below. Here 'gender' and 'ethderived' are two columns. I would like to replace their values like 1,2,3 etc with categorical values. Ex - 1 with Male, 2 with Female

The mapping file looks like as shown below - sample 2 columns

Input data looks like as shown below

I expect my output dataframe to look like this

I have tried to do this using the below code. Though the code works fine, I don't see any replace happening. Can you please help me with this?

mapp = pd.read_csv('file2.csv')
data = pd.read_csv('file1.csv')
for col in mapp:
    if col in data.columns:
        print(col)
        s = list(mapp.loc[(mapp[col].str.contains('^\d')==True)].index)
        print("s is",s)
        for i in s:
           print("i is",i)
            try:
               value = mapp[col][i].split('. ')
               print("value 0 is",value[0])
               print("value 1 is",value[1])
               if value[0] in data[col].values:
               data.replace({col:{value[0]:value[1]}})
            except:
                print("column not present")
   else:
       print("No")

Please note that I have shown only two columns but in real time there might more than 600 columns. Any elegant approach/suggestions to make it simple is helpful. As I have two separate csv files, any suggestions on merge/join etc will also be helpful but please note that my mapping file contains values as "1. Male", "2. Female". hence I used regex

Also note that, several other column values can also have mapping values that start with 1. ex: 1. Single, 2. Married, 3. Divorced etc

Looking forward to your help

Body:
Use DataFrame.replace with nested dictionaries - first key define colum name for replace and another values for replace created by function Series.str.extract:

df = pd.DataFrame({'Gender':['1.Male','2.Female', np.nan],
                   'Ethnicity':['1.Chinese','2.Indian','3.Malay']})
print (df)
     Gender  Ethnicity
0    1.Male  1.Chinese
1  2.Female   2.Indian
2       NaN    3.Malay

d={x:df[x].str.extract(r'(\d+)\.(.+)').dropna().set_index(0)[1].to_dict() for x in df.columns}
print (d)
{'Gender': {'1': 'Male', '2': 'Female'},
 'Ethnicity': {'1': 'Chinese', '2': 'Indian', '3': 'Malay'}}

df1 = pd.DataFrame({'Gender':[2,1,2,1],
                   'Ethnicity':[1,2,3,1]})
print (df1)
   Gender  Ethnicity
0       2          1
1       1          2
2       2          3
3       1          1

#convert to strings before replace
df2 = df1.astype(str).replace(d)
print (df2)
   Gender Ethnicity
0  Female   Chinese
1    Male    Indian
2  Female     Malay
3    Male   Chinese


问:
Compute sum of values in array using PHP
I'm trying to combine the scores of employee for my program. My sample is one employee is evaluated more than one. So basically, if employee 1 have scored of 87 and 90 the total should be 177. After computation, I need to return the result with the highest score.
Here so far my sample code (I simplified my code for this question because it is too long to post the original code):

```<code>$scores = array(
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
);

print_r($scores);

get_topemployee($scores);

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    foreach($scores as $key) {
        for($i=0; count($scores) <= $i; $i++) {
            if($key[0] == $key[0][$i]) {
                $total_score += $key[1];
            }
            $combined_score[] = array($key[0], $key[1], $total_score);
        }
    }

    $employee = ""; // employee with highest score
    $compare_score = 0;
    foreach($combined_score as $value) {
        $compare_score = $value[1];
        if($value[1] >= $compare_score) {
            $employee = $value[0];
        }
    }

    return $employee;
}
</code>```

The result does not return the employee with highest score and not sure which in my code is incorrect. thanks for help

do this:- https://3v4l.org/WhVaN

答:
You can use array_reduce to convert your scores array into an array of total scores indexed by employee:

```<code>$scores = array_reduce($scores, function ($c, $v) {
    $name = $v[1];
    if (isset($c[$name])) {
        $c[$name] += $v[2];
    }
    else {
        $c[$name] = $v[2];
    }
    return $c;
}, array());
</code>```

You can then use arsort to sort the array in reverse order while maintaining the key association. You can then use key to get the key of the first element, which will be the name of the employee with the highest score:

```<code>arsort($scores);
echo key($scores);
</code>```

Output:

```<code>allan
</code>```

Demo on 3v4l.org

To print out all the scores, you can simply print_r($scores):

```<code>Array (
  [allan] => 267
  [mark] => 265
  [jason] => 178
)
</code>```

Alternatively to print just the highest score, change echo key($scores); to echo key($scores) . ' ' . current($scores);:

```<code>allan 267
</code>```

Updated demo.

Body:
I'm trying to combine the scores of employee for my program. My sample is one employee is evaluated more than one. So basically, if employee 1 have scored of 87 and 90 the total should be 177. After computation, I need to return the result with the highest score.
Here so far my sample code (I simplified my code for this question because it is too long to post the original code):

$scores = array(
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
);

print_r($scores);

get_topemployee($scores);

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    foreach($scores as $key) {
        for($i=0; count($scores) <= $i; $i++) {
            if($key[0] == $key[0][$i]) {
                $total_score += $key[1];
            }
            $combined_score[] = array($key[0], $key[1], $total_score);
        }
    }

    $employee = ""; // employee with highest score
    $compare_score = 0;
    foreach($combined_score as $value) {
        $compare_score = $value[1];
        if($value[1] >= $compare_score) {
            $employee = $value[0];
        }
    }

    return $employee;
}

The result does not return the employee with highest score and not sure which in my code is incorrect. thanks for help

do this:- https://3v4l.org/WhVaN

Body:
You can use array_reduce to convert your scores array into an array of total scores indexed by employee:

$scores = array_reduce($scores, function ($c, $v) {
    $name = $v[1];
    if (isset($c[$name])) {
        $c[$name] += $v[2];
    }
    else {
        $c[$name] = $v[2];
    }
    return $c;
}, array());

You can then use arsort to sort the array in reverse order while maintaining the key association. You can then use key to get the key of the first element, which will be the name of the employee with the highest score:

arsort($scores);
echo key($scores);

Output:

allan

Demo on 3v4l.org

To print out all the scores, you can simply print_r($scores):

Array (
  [allan] => 267
  [mark] => 265
  [jason] => 178
)

Alternatively to print just the highest score, change echo key($scores); to echo key($scores) . ' ' . current($scores);:

allan 267

Updated demo.


答:
If the entries are always in order(1.XXX,2.XXX...), use:

```<code>m=df1.apply(lambda x: x.str[2:])
n=df2.sub(1).replace(m)
print(n)
</code>```

```<code>   gender ethderived
0  Female    Chinese
1    Male     Indian
2    Male      Malay
3  Female    Chinese
4    Male    Chinese
5  Female     Indian
</code>```

Title: Replace values in a dataframe with values from another dataframe - Regex

Body:
If the entries are always in order(1.XXX,2.XXX...), use:

m=df1.apply(lambda x: x.str[2:])
n=df2.sub(1).replace(m)
print(n)

   gender ethderived
0  Female    Chinese
1    Male     Indian
2    Male      Malay
3  Female    Chinese
4    Male    Chinese
5  Female     Indian


问:
How do you get the default insets of NSViews and NSControls?
I'm writing some custom layout code to align some NSViews. I loop through all the views and set their frame.origin.x to the same value (left alignment), but the views don't look like they're aligned properly. I looked at left aligned views in Interface Builder, and each different class of view has a different frame.origin.x value.

For example, to left align an NSPopUpButton with an NSTextField, the frame.origin.x value of the NSPopUpButton has to be 3 pixels less than that of the NSTextField.

I found a method ibLayoutInset in InterfaceBuilderKit.framework that appears to be what I want, but none of the AppKit views implement the method.

Does anyone know how to get these inset values programmatically?

答: Aside from measuring yourself and building your own table of offsets, you can’t.  This is rather annoying, and it’s probably best to file a bug report, here: http://bugreport.apple.com</p>

ContentLicense: CC BY-SA 3.0


问:
Update the Suite Name at RunTime
Is there any workaround to set the SuiteName at the time of test execution,
 same as we can achieve for Test Name using ITest Interface.</p>

答:
This works perhaps. I have not tested it yet.

Reporter.getCurrentTestResult().getTestClass().getXmlClass().setName("NewName");

Title: Update the Suite Name at RunTime


问:
How do I run a simple 'hello world' program under QNX?
Background: I have the QNX license key and have installed the VMWare target image from the QNX website into the VMWare. I have the QNX target RTOS running as a VM and my host machine has a QNX momentics IDE that can recognize the QNX target OS.

Problem: I have the license for the latest QNX SDP 7 and the only VMWare compatible image I could find on the QNX website is an older QNX 6.5(?). A simple 'hello world' program (the demo program that ships with the Momentics IDE) will not run on the QNX target OS because it is missing certain libraries.

I need to either:

Acquire the methodology to boot the latest version of QNX RTOS on VMWare. I have searched and searched in vain but this procedure is not described. The QNX SDP should have a way to create a bootable QNX RTOS for VMWare but the procedure is not listed anywhere (I have searched for days now!)

OR

Find a way to use the Momentics IDE 7.0 with the older version of QNX RTOS that I have.

Questions:

How do create a bootable QNX RTOS ISO and load it into VMWare using the QNX SDP 7.0?

Make simple C/C++ programs created with QNX Momentics 7.0 run on the older version of QNX RTOS I have?

Addendum

These are the instructions they provide on how to acquire the latest QNX RTOS VMWare image. They say:

We provide a VMware image that's compatible with VMware Workstation Pro 12.0 or later, VMware Workstation Player 12.0 or later, and VMware Fusion Pro 8.0 or later. This image is a minimal QNX Neutrino system. You can download a VMware image from the QNX Software Center by choosing the Available tab, expanding the Reference Images list, expanding the Tools list, and then choosing the appropriate virtual machine.

However, there's no 'reference images' or 'tools' or 'available tab' or anything like that in the software center (see images).

答: If you open the QNX software center coming with QNX installation, and activate your license in that all the supported features which is available for you to download will be listed. in that the QNX VM image for v 7.0 is listed. you can download it directly from there.


问:
How to fix the error 'API call to bigquery.jobs.query failed with error: Encountered " "FROM" "from "" at .... Was expecting: ")"'
I am trying to run a bigquery api call using the query string(attached in the code) from appscript; The query runs perfectly fine in bigquery UI

I have tried the following with no success:

1. include parentheses in orders.creation_date in the query string

2. replace orders with the actual table table i.e [my-project:theservices.theservice_order_item]

```<code>/**
 * Runs a BigQuery query and logs the results in a spreadsheet.
 */
function runQuery() {

  var projectId = 'my-project';

  var request = {
    query:
    "SELECT  extract(date from orders.creation_date) as the_date \n FROM [my-project:theservices.theservice_order_item] AS orders LIMIT 10;"
  };

};
</code>```

Following is the error I get:

API call to bigquery.jobs.query failed with error: Encountered " "FROM" "from "" at line 1, column 22. Was expecting: ")" ... (line 23, file "Code")

答:
Quoting App Script BigQuery Standard SQL insert or update statement:

You need to set the useLegacySql flag/parameter to false, to indicate that you want to use standard SQL, like so:

```<code>var job = {
configuration: {
  query: {
    query: 'SELECT ....',
    useLegacySql: false
    }
</code>```

Additionally, when a table looks like this - that's #legacySQL:

```<code>FROM [my-project:theservices.theservice_order_item]
</code>```

In #standardSQL the table should be enclosed in tilde '`' and has a '.' between the project and dataset name:

```<code>FROM `my-project.theservices.theservice_order_item`
</code>```

Body:
I am trying to run a bigquery api call using the query string(attached in the code) from appscript; The query runs perfectly fine in bigquery UI

I have tried the following with no success:

1. include parentheses in orders.creation_date in the query string

2. replace orders with the actual table table i.e [my-project:theservices.theservice_order_item]

/**
 * Runs a BigQuery query and logs the results in a spreadsheet.
 */
function runQuery() {

  var projectId = 'my-project';

  var request = {
    query:
    "SELECT  extract(date from orders.creation_date) as the_date \n FROM [my-project:theservices.theservice_order_item] AS orders LIMIT 10;"
  };

};

Following is the error I get:

API call to bigquery.jobs.query failed with error: Encountered " "FROM" "from "" at line 1, column 22. Was expecting: ")" ... (line 23, file "Code")

Body:
Quoting App Script BigQuery Standard SQL insert or update statement:

You need to set the useLegacySql flag/parameter to false, to indicate that you want to use standard SQL, like so:

var job = {
configuration: {
  query: {
    query: 'SELECT ....',
    useLegacySql: false
    }

Additionally, when a table looks like this - that's #legacySQL:

FROM [my-project:theservices.theservice_order_item]

In #standardSQL the table should be enclosed in tilde '`' and has a '.' between the project and dataset name:

FROM `my-project.theservices.theservice_order_item`


问:
Get fullcalendar JSON from JSP page
I'm working with the fullcalendar jQuery plugin and I'm trying to populate my events by creating a JSON object on a jsp page.

Here is what I have for my fullcalendar code...

```<code>$('#mycalendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    defaultView: 'agendaDay',
    editable: false,
    slotMinutes: 5,
    allDaySlot: true,
    lazyFetching: true,
    eventSources: [
        '/servlet/TEST?action=calendarData'
    ],
    eventClick: function(event) {
        if (event.url) {
            window.location.href = event.url;
            return false;
        }
    }
});
</code>```

I know a lot of my parameters are set as the default, but I only have them set that way for debugging and they will be changed.

The request is going through and is returning what I'm expecting but the event is not getting displayed, which leads me to believe that I'm expecting the wrong thing. Which will probably be evident in my jsp page.

```<code><%@ page contentType="application/json;" pageEncoding="UTF-8"%>
{
    title: "test",
    start: new Date(2011, 3, 12),
    allDay: true
}
</code>```

I'm just trying to hardcode a JSON object to the page so I can better understand what I will need to dynamically create for the real data. I'm expecting this to create an all day event for today. Firebug can read it as a JSON object... but the event is not displaying.

答:
eventSources expects valid JSON. The code that's in your page is not valid JSON. All keys must be double-quoted, and Dates are not valid values as per the JSON grammar.

Try this:

```<code><%@ page contentType="application/json;" pageEncoding="UTF-8"%>
{
    "title": "test",
    "start": "2011-04-12",
    "allDay": true
}
</code>```

Title: Get fullcalendar JSON from JSP page

Body:
I'm working with the fullcalendar jQuery plugin and I'm trying to populate my events by creating a JSON object on a jsp page.

Here is what I have for my fullcalendar code...

$('#mycalendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    defaultView: 'agendaDay',
    editable: false,
    slotMinutes: 5,
    allDaySlot: true,
    lazyFetching: true,
    eventSources: [
        '/servlet/TEST?action=calendarData'
    ],
    eventClick: function(event) {
        if (event.url) {
            window.location.href = event.url;
            return false;
        }
    }
});

I know a lot of my parameters are set as the default, but I only have them set that way for debugging and they will be changed.

The request is going through and is returning what I'm expecting but the event is not getting displayed, which leads me to believe that I'm expecting the wrong thing. Which will probably be evident in my jsp page.

<%@ page contentType="application/json;" pageEncoding="UTF-8"%>
{
    title: "test",
    start: new Date(2011, 3, 12),
    allDay: true
}

I'm just trying to hardcode a JSON object to the page so I can better understand what I will need to dynamically create for the real data. I'm expecting this to create an all day event for today. Firebug can read it as a JSON object... but the event is not displaying.

Body:
eventSources expects valid JSON. The code that's in your page is not valid JSON. All keys must be double-quoted, and Dates are not valid values as per the JSON grammar.

Try this:

<%@ page contentType="application/json;" pageEncoding="UTF-8"%>
{
    "title": "test",
    "start": "2011-04-12",
    "allDay": true
}


问:
disable click after clicking on $('body').on('click') event
hi  I want to disable click after the user clicked  on an element

the elements loaded after my script (elements built by javascript) and I can't use these code

```<code>     $('.disableClick').click(
            function (e) {
                e.stopPropagation();
                return false;
            }
        )
</code>```

and I use these code to do work on the element by click

```<code>    $('body').on('click','.disableClick',
                function (e) {
                    if(!is_valid)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                }
            );
</code>```

I think disabling click codes like e.stopPropagation()  don't support for

$('body').on('click')
  event

答:
You need to use unbind I guess.
Try </p>

```<code>    if(!is_valid){
    $('selector').unbind("click")
    }
</code>```

Body:
hi  I want to disable click after the user clicked  on an element

the elements loaded after my script (elements built by javascript) and I can't use these code

     $('.disableClick').click(
            function (e) {
                e.stopPropagation();
                return false;
            }
        )

and I use these code to do work on the element by click

    $('body').on('click','.disableClick',
                function (e) {
                    if(!is_valid)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                }
            );

I think disabling click codes like e.stopPropagation()  don't support for

$('body').on('click')
  event

Body:
You need to use unbind I guess.
Try

    if(!is_valid){
    $('selector').unbind("click")
    }


问:
Lost Crypt key of magento 2
I lost crypt key from my magento2 setup and now I am having issues with the PayPal and other configurations. Can somebody help me how I can recover crypt key via server?</p>

答:
On your server navigate to app/etc and open env.php file.

in env.php file you can find crypt key.

```<code>'crypt' =>
 array (
   'key' => '5b581cc9b27c0c114ed642a27d50c18c',
 )
</code>```

Title: Lost Crypt key of magento 2

Body:
On your server navigate to app/etc and open env.php file.

in env.php file you can find crypt key.

'crypt' =>
 array (
   'key' => '5b581cc9b27c0c114ed642a27d50c18c',
 )


问:
Grouping of data fetched from firestore using Angularfire2
Functionality:

I have a Angular project for which I have to generate a graph showing invoiceDate vs saleAmount. The data is fetched from the invoice collection.

```<code>var invoiceRef = this.afs.collection<Invoice>('invoices',
    ref=> ref.orderBy('creationDate','desc'));
</code>```

Here I am getting the saleAmount and invoiceDate for each invoice.

Issue

How to count the saleAmount for each invoice Date?

In traditional SQL you would write something like

```<code>SELECT COUNT(saleAmount) FROM invoice GROUP BY invoiceDate;
</code>```

How to do the same using angularfire queries for  firestore?

答:
Not sure it can be done directly from a firestore query, but you can implement a function that does this after you get the data (or before, with cloud functions).

It could look like this:

```<code>const groupedInovices = {};
invocies.forEach((inovice) => {
      groupedInovices[invoice.date] = groupedInovices[invoice.date] ? groupedInovices[invoice.date]++ : 1;
    });
</code>```

You will end up with an object that looks like this:

```<code>{
  "05/30/2019": 20
  "05/29/2019: 13
}
</code>```

Body:
Functionality:

I have a Angular project for which I have to generate a graph showing invoiceDate vs saleAmount. The data is fetched from the invoice collection.

var invoiceRef = this.afs.collection<Invoice>('invoices',
    ref=> ref.orderBy('creationDate','desc'));

Here I am getting the saleAmount and invoiceDate for each invoice.

Issue

How to count the saleAmount for each invoice Date?

In traditional SQL you would write something like

SELECT COUNT(saleAmount) FROM invoice GROUP BY invoiceDate;

How to do the same using angularfire queries for  firestore?

Body:
Not sure it can be done directly from a firestore query, but you can implement a function that does this after you get the data (or before, with cloud functions).

It could look like this:

const groupedInovices = {};
invocies.forEach((inovice) => {
      groupedInovices[invoice.date] = groupedInovices[invoice.date] ? groupedInovices[invoice.date]++ : 1;
    });

You will end up with an object that looks like this:

{
  "05/30/2019": 20
  "05/29/2019: 13
}


问:
Laravel vue js mixins not getting function response
I am using laravel 5.8 with vue js. I have created a generalized function for post/get requests. The problem is, i am not getting the mixins function response. Here is my code :

TestComponent.vue

```<code>import GeneralMixin from '../mixins.js';
export default {
    mixins: [ GeneralMixin ],
    methods:{
        login: function (e) {
            let response;
            response = this.testMixin();
            console.log(response);
        }
    }
}
</code>```

mixin.js

```<code>export default {
    methods: {
        testMixin: function () {
            url = '/test';
            axios.post(url).then(function(response, status, request) {
                return response;
            });
        }
    }
}
</code>```

The console result is undefined

I am not getting response of function testMixin() . Can anyone help please

答:
If you want to return the response from the mixin then you're going to need to wrap that axios request in a promise:

```<code>return new Promise((resolve, reject) => {
  axios.post(url).then(function(response, status, request) {
     return resolve(response)
  })
})
</code>```

And if you want the result of that from another function:

```<code>login: function (e) {
  this.textMixin().then((response) => {
    console.log(response)
  })
}
</code>```

But really it's an anti pattern to return only the response from the promise. The way you've created this mixin serves as a psuedo-API for you to consume internally, so instead just return the axios request:

```<code>return axios.post(url)
</code>```

Now you can handle this yourself:

```<code>login: function(e) {
    this.testMixin().then((response) => {
       console.log(response)
    }).catch((error) => {
       console.log(error.response.data)
    })
}
</code>```

Body:
I am using laravel 5.8 with vue js. I have created a generalized function for post/get requests. The problem is, i am not getting the mixins function response. Here is my code :

TestComponent.vue

import GeneralMixin from '../mixins.js';
export default {
    mixins: [ GeneralMixin ],
    methods:{
        login: function (e) {
            let response;
            response = this.testMixin();
            console.log(response);
        }
    }
}

mixin.js

export default {
    methods: {
        testMixin: function () {
            url = '/test';
            axios.post(url).then(function(response, status, request) {
                return response;
            });
        }
    }
}

The console result is undefined

I am not getting response of function testMixin() . Can anyone help please

Body:
If you want to return the response from the mixin then you're going to need to wrap that axios request in a promise:

return new Promise((resolve, reject) => {
  axios.post(url).then(function(response, status, request) {
     return resolve(response)
  })
})

And if you want the result of that from another function:

login: function (e) {
  this.textMixin().then((response) => {
    console.log(response)
  })
}

But really it's an anti pattern to return only the response from the promise. The way you've created this mixin serves as a psuedo-API for you to consume internally, so instead just return the axios request:

return axios.post(url)

Now you can handle this yourself:

login: function(e) {
    this.testMixin().then((response) => {
       console.log(response)
    }).catch((error) => {
       console.log(error.response.data)
    })
}


问:
Django context value for home page
I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against.
I get this error NoReverseMatch at /home/
I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file.

I tried context_processors but it gives me this error at the home.view
int() argument must be a string or a number, not builtin_function_or_method

I have two functions in context_processors, each has it's own characteristics.

Here is the code

settings.py

TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'projectfiles.context_processors.emp_base_context',
                'projectfiles.context_processors.lev_base_context',
            ],},},]

```

<p><strong>models.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)

    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

class Leave(models.Model):
    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)
    leave_status = models.CharField(max_length=10, default="Pending")

</code>```

context_processors.py

from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)

    return {
        'emp_base_context': emp_base_context}

```

<p><strong>urls.py</strong></p>

<pre class="lang-py prettyprint-override"><code>urlpatterns = [
    url(r'^(?i)Home/$', views.home, name='Home-Page'),
    url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request
</code>```

views.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(id=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")
```

<p><strong>base.html</strong></p>

<pre class="lang-html prettyprint-override"><code><nav id="mynav" class="navbar navbar-expand-sm bg-dark">
                  class="glyphicon glyphicon-folder-close"></span> Leave Management System</a>
            </h4>
          </div>
          <div class="panel-collapse collapse panel-scroll" id="accordion">
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-folder-close"></span> Home
                </h4>
              </div>
              <div id="collapseOne" class="panel-collapse collapse">
                <div class="panel-body">
                  <table class="table">
                    <tbody>
                      <tr>
                        <td>

                       The request page   **<span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave**
                        </td>
                      </tr>
                      <tr>
                        <td>
                        <span class="glyphicon glyphicon-pencil text-primary"></span> Notifications
                        </td>
                      </tr>
                      <td>
                        <span class="glyphicon glyphicon-file text-info"></span> About
                      </td>
                      </tr>

                    </tbody>
                  </table>
                </div>
              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-user"></span> {{user.username}}
                </h4>
              </div>
              <div id="collapseThree" class="panel-collapse collapse ">
                <div class="panel-body">

                </div>
              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading">
                <h4 class="panel-title">
                  <span
                      class="glyphicon glyphicon-th"></span>Remaining Leaves
                </h4>
              </div>
              <div id="collapseTwo" class="panel-collapse collapse ">
                <div class="panel-body">
                  <table class="table">
                    <tbody>
                      <tr>
                        <td>
                          Annual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Emergency<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Sick<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                      <tr>
                        <td>
                          Casual<span class="label label-success"><font color='red'><br><small>Remaining leaves</small></font></span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
              </div>
            </div>
          </div>
        </div>

      </div>

    </div>
  </div>
</div>
<div id="push"></div>
</code>```

errors

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.11.20
Python Version: 2.7.16
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'projectfiles',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in home
  25.     return render(request, "projectfiles/HomePage.html")

File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  205.                 with context.bind_template(self):

File "C:\Python27\lib\contextlib.py" in __enter__
  17.             return self.gen.next()

File "C:\Python27\lib\site-packages\django\template\context.py" in bind_template
  263.             updates.update(processor(self.request))

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\context_processors.py" in emp_base_context
  7.     emp_data = Employee.objects.get(id=id)

File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
  371.         clone = self.filter(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  787.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  805.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1210.             condition = self.build_lookup(lookups, col, value)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_lookup
  1104.                 return final_lookup(lhs, rhs)

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup
  74.             return self.lhs.output_field.get_prep_value(self.rhs)

File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: TypeError at /home/
Exception Value: int() argument must be a string or a number, not 'builtin_function_or_method'

</code>```

error 2.0

```<code>Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /home/
Exception Value: home() takes exactly 2 arguments (1 given)

</code>```

UPDATED

```<code>url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),

<a href="{% url "Leave-Page" request.user.id %}"><span class="glyphicon glyphicon-pencil text-primary"></span> Request Leave</>

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

using context_processor was passing the id to the entire view, I just needed to use it for request and by comparing the user id with the employee name worked for me.

</code>```

I expect, when the user is allowed by the admin from the back end then the user is able to access the request page and apply, otherwise the view redirects the user to a different page.

答:
The error is in emp_data = Employee.objects.get(id=id)

in the function

```<code>def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)
    return {
        'emp_base_context': emp_data}
</code>```

where is the id coming from? Since you didn't give any id here, it's taking the python in-built id function. You might watch to fetching the id form request.

Title: Django context value for home page

Body:
I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against.
I get this error NoReverseMatch at /home/
I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file.

I tried context_processors but it gives me this error at the home.view
int() argument must be a string or a number, not builtin_function_or_method

I have two functions in context_processors, each has it's own characteristics.

Here is the code

settings.py

TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'projectfiles.context_processors.emp_base_context',
                'projectfiles.context_processors.lev_base_context',
            ],},},]

models.py

class Employee(models.Model):

    allowed = models.BooleanField(default=True)
    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 5)
    employee_department = models.CharField(max_length = 5)

    Annual_leave = models.PositiveSmallIntegerField(default=5)
    Sick_leave = models.PositiveSmallIntegerField(default=5)
    Casual_leave = models.PositiveSmallIntegerField(default=5)
    Half_pay = models.PositiveSmallIntegerField(default=5)
    Emergency_leave = models.PositiveSmallIntegerField(default=5)

class Leave(models.Model):
    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)
    leave_status = models.CharField(max_length=10, default="Pending")

context_processors.py

from .models import Employee, Leave

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)

    return {
        'emp_base_context': emp_base_context}

urls.py

urlpatterns = [
    url(r'^(?i)Home/$', views.home, name='Home-Page'),
    url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),  # leave request

views.py

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(id=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

base.html

                  class="glyphicon glyphicon-folder-close"> Leave Management System

                   Home

                       The request page   ** Request Leave**

                         Notifications

                         About

                   {{user.username}}

                  Remaining Leaves

                          Annual
Remaining leaves

                          Emergency
Remaining leaves

                          Sick
Remaining leaves

                          Casual
Remaining leaves

errors

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Django Version: 1.11.20
Python Version: 2.7.16
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'projectfiles',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\views.py" in home
  25.     return render(request, "projectfiles/HomePage.html")

File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Python27\lib\site-packages\django\template\base.py" in render
  205.                 with context.bind_template(self):

File "C:\Python27\lib\contextlib.py" in __enter__
  17.             return self.gen.next()

File "C:\Python27\lib\site-packages\django\template\context.py" in bind_template
  263.             updates.update(processor(self.request))

File "C:\Users\Bitswits 3\Desktop\Intern Work\LMS\LMS\projectfiles\context_processors.py" in emp_base_context
  7.     emp_data = Employee.objects.get(id=id)

File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
  371.         clone = self.filter(*args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in filter
  787.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  805.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1210.             condition = self.build_lookup(lookups, col, value)

File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in build_lookup
  1104.                 return final_lookup(lhs, rhs)

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Python27\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup
  74.             return self.lhs.output_field.get_prep_value(self.rhs)

File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: TypeError at /home/
Exception Value: int() argument must be a string or a number, not 'builtin_function_or_method'

error 2.0

Request Method: GET
Request URL: http://127.0.0.1:8000/home/

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /home/
Exception Value: home() takes exactly 2 arguments (1 given)

UPDATED

url(r'^(?i)request/(?P<emp_id>\d+)$', views.request_leave,
        name='Leave-Page'),

 Request Leave</>

def request_leave(request, emp_id):  # Requesting leave
    employee = Employee.objects.get(employee_name=emp_id)
    if employee.allowed == True:
        form = Leave_Form(request.POST)
        if form.is_valid():
            abc = form.save(commit=False)
            abc.employee_leaves = request.user.employee
            abc.save()
        form = Leave_Form
        context = {'employee': employee, 'form': form}
        # context = {'form': form}
        return render(request, 'projectfiles/reqleave.html', context)
    else:
        return render(request, "projectfiles/banned.html")

using context_processor was passing the id to the entire view, I just needed to use it for request and by comparing the user id with the employee name worked for me.

I expect, when the user is allowed by the admin from the back end then the user is able to access the request page and apply, otherwise the view redirects the user to a different page.

Body:
The error is in emp_data = Employee.objects.get(id=id)

in the function

def emp_base_context(request):
    emp_data = Employee.objects.get(id=id)
    return {
        'emp_base_context': emp_data}

where is the id coming from? Since you didn't give any id here, it's taking the python in-built id function. You might watch to fetching the id form request.


问:
Using Primefaces 5, should I be able to *dynamically* build a simple p:menu containing only menuitems? ...i.e., without submenu(s)?
QUESTION: Using Primefaces 5, can I dynamically build a simple p:menu containing only menuitems - i.e., without submenu(s)?

For example,  I am able to successfully implement this static menu...

```<code>    -
    -
    -
    <h3>Static p:menu  (i.e., no submenus) - WORKING </h3>
    <p:menu id="menustatic">
        <p:menuitem value="operation1"  action="#{breadCrumb.navigate('page0')}" />
        <p:menuitem value="operation2"  action="#{breadCrumb.navigate('page1')}" />
        <p:menuitem value="operation3"  action="#{breadCrumb.navigate('page2')}" />
    </p:menu>
    -
    -
    -
</code>```

But, when I attempt to implement the above menu dyamically from the managed bean, it is not working... i.e.,

the controller method

```<code>    -
    -
    -
    private DynamicMenuModel menuModel;
    public MenuModel getMenuModel()
    {
        menuModel = new DynamicMenuModel();

        DefaultMenuItem item = new DefaultMenuItem();
        item.setIcon("ui-icon ui-icon-newwin");
        item.setValue("operation1a");
        item.setCommand("#{breadCrumb.navigate('page0')}");
        menuModel.addElement(item);

        item = new DefaultMenuItem();
        item.setIcon("ui-icon ui-icon-newwin");
        item.setValue("operation1b");
        item.setCommand("#{breadCrumb.navigate('page1')}");
        menuModel.addElement(item);

        item = new DefaultMenuItem();
        item.setIcon("ui-icon ui-icon-newwin");
        item.setValue("operation1c");
        item.setCommand("#{breadCrumb.navigate('page2')}");
        menuModel.addElement(item);

        return menuModel;
    }
    -
    -
    -
</code>```

the page/tag

```<code>    <h3>Dyamic p:menu  (i.e., no submenus) -  NOT WORKING </h3>
    <p:menu id="menudynamic" model="#{menuController.menuModel}" />
</code>```

When I click on the "dynamically" built menu's menuitems I receive this error on my console...

```<code>    <Jul 17, 2014 1:12:52 PM EDT> <Warning> <javax.enterprise.resource.webcontainer.jsf.lifecycle> <BEA-000000> <For input string: "null"
    java.lang.NumberFormatException: For input string: "null"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
        at java.lang.Integer.parseInt(Integer.java:449)
        at java.lang.Integer.parseInt(Integer.java:499)
        at org.primefaces.component.menu.BaseMenuRenderer.findMenuitem(BaseMenuRenderer.java:83)
        at org.primefaces.component.menu.BaseMenuRenderer.decode(BaseMenuRenderer.java:61)
        Truncated. see log file for complete stacktrace
    >
</code>```

Is the problem that I am simply misusing the "p:menu" tag in the first place, when I build the static version?...
- Is this why my attempting to build a dynamic version of the same menu does not work as I would expect?

Thanks for any help!

:)

答: You should call generateUniqueIds() on your MenuModel after all MenuElements are added.

Body:
QUESTION: Using Primefaces 5, can I dynamically build a simple p:menu containing only menuitems - i.e., without submenu(s)?

For example,  I am able to successfully implement this static menu...

    -
    -
    -

Static p:menu  (i.e., no submenus) - WORKING

    -
    -
    -

But, when I attempt to implement the above menu dyamically from the managed bean, it is not working... i.e.,

the controller method

    -
    -
    -
    private DynamicMenuModel menuModel;
    public MenuModel getMenuModel()
    {
        menuModel = new DynamicMenuModel();

        DefaultMenuItem item = new DefaultMenuItem();
        item.setIcon("ui-icon ui-icon-newwin");
        item.setValue("operation1a");
        item.setCommand("#{breadCrumb.navigate('page0')}");
        menuModel.addElement(item);

        item = new DefaultMenuItem();
        item.setIcon("ui-icon ui-icon-newwin");
        item.setValue("operation1b");
        item.setCommand("#{breadCrumb.navigate('page1')}");
        menuModel.addElement(item);

        item = new DefaultMenuItem();
        item.setIcon("ui-icon ui-icon-newwin");
        item.setValue("operation1c");
        item.setCommand("#{breadCrumb.navigate('page2')}");
        menuModel.addElement(item);

        return menuModel;
    }
    -
    -
    -

the page/tag

Dyamic p:menu  (i.e., no submenus) -  NOT WORKING

When I click on the "dynamically" built menu's menuitems I receive this error on my console...

    <Jul 17, 2014 1:12:52 PM EDT> <Warning> <javax.enterprise.resource.webcontainer.jsf.lifecycle> <BEA-000000> <For input string: "null"
    java.lang.NumberFormatException: For input string: "null"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
        at java.lang.Integer.parseInt(Integer.java:449)
        at java.lang.Integer.parseInt(Integer.java:499)
        at org.primefaces.component.menu.BaseMenuRenderer.findMenuitem(BaseMenuRenderer.java:83)
        at org.primefaces.component.menu.BaseMenuRenderer.decode(BaseMenuRenderer.java:61)
        Truncated. see log file for complete stacktrace
    >

Is the problem that I am simply misusing the "p:menu" tag in the first place, when I build the static version?...
- Is this why my attempting to build a dynamic version of the same menu does not work as I would expect?

Thanks for any help!

:)


问:
How do I send bytes to a serial device in C#?
I have a device that uses serial (via a USB adaptor) to interface with my PC. I'm having real difficulty getting it to play nicely in C#. I know that it works properly because the vendor-supplied software behaves as expected. I also know that I am able to receive data using my code thanks to a test mode which repeatedly sends "OK".

Here's my code:

```<code>    private SerialPort port;

    public SerialConnection()
    {
        this.port = new SerialPort("COM3", 38400, Parity.None, 8, StopBits.One);
        this.port.WriteTimeout = 2000; port.ReadTimeout = 2000;

        this.port.Open();

        this.port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    }

    public void SendCommand(byte[] command)
    {
        this.port.Write(command,0,command.Length);
        string chars = "";
        foreach (byte charbyte in command) chars += (char)charbyte;
        Console.WriteLine(" -> " + chars);
    }

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string data = this.port.ReadLine();
        Console.WriteLine(" <- " + data);
    }
</code>```

At the moment I'm using another test mode which is supposed to echo back whatever it receives. Accordingly, I'm calling SendCommand with the following bytes:

```<code>byte[] {
    0x50,
    0x69,
    0x6E,
    0x67
}
</code>```

But nothing ever seems to get sent back.

I've no idea what to try next. Anyone got any suggestions?

For a subsidiary question I've posted some PortMon logs. I think they might be useful here too, so here they are:

Vendors software - with all the IOCTL_SERIAL_GET_COMMSTATUS entries filtered out

My toe-dip attempt

答:
Tom  ,

I have had similar problems,

I am going to place my bet on the fact that ReadLine() only returns once it has received a \r\n or something that .NET believes is a new line.

In your logs, i dont see Winbird reporting any new line characters, i believe that APP is reading byte by byte, and not waiting for newlines.

So you can send many bytes of data to it, and it will keep on blocking until it receives the correct new line characters.

So give SerialPort.Read a try, by reading 1 byte at a time for starters,

```<code>public int Read (
byte[] buffer,
int offset,
int count
</code>```

)

If this doesnt fix it, you might want to consider the following

Some of my problems were fixed with adding a few Thread.Sleep()'s because i realized the PC's UARTs are not fast enough to electrically transmit the data over the RS232/RS485 ports correctly, also wait a few milliseconds after opening the port.

I would also advise you to rather create a separate thread to handle the serial comms, instead of using SerialDataReceivedEventHandler, create a send buffer, which is sent in the correct increments without blocking your app, also read the data and append bytes received to buffer until you have received enough data.

You are also going to need a second serial device to capture your data to make sure your C# app is transmitting the correct data.

To elimate the issue of handshaking, test by only having PIN 2,3 + PIN 5 (GND) connected.

Hope this helps

Body:
I have a device that uses serial (via a USB adaptor) to interface with my PC. I'm having real difficulty getting it to play nicely in C#. I know that it works properly because the vendor-supplied software behaves as expected. I also know that I am able to receive data using my code thanks to a test mode which repeatedly sends "OK".

Here's my code:

    private SerialPort port;

    public SerialConnection()
    {
        this.port = new SerialPort("COM3", 38400, Parity.None, 8, StopBits.One);
        this.port.WriteTimeout = 2000; port.ReadTimeout = 2000;

        this.port.Open();

        this.port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    }

    public void SendCommand(byte[] command)
    {
        this.port.Write(command,0,command.Length);
        string chars = "";
        foreach (byte charbyte in command) chars += (char)charbyte;
        Console.WriteLine(" -> " + chars);
    }

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string data = this.port.ReadLine();
        Console.WriteLine(" <- " + data);
    }

At the moment I'm using another test mode which is supposed to echo back whatever it receives. Accordingly, I'm calling SendCommand with the following bytes:

byte[] {
    0x50,
    0x69,
    0x6E,
    0x67
}

But nothing ever seems to get sent back.

I've no idea what to try next. Anyone got any suggestions?

For a subsidiary question I've posted some PortMon logs. I think they might be useful here too, so here they are:

Vendors software - with all the IOCTL_SERIAL_GET_COMMSTATUS entries filtered out

My toe-dip attempt

Body:
Tom  ,

I have had similar problems,

I am going to place my bet on the fact that ReadLine() only returns once it has received a \r\n or something that .NET believes is a new line.

In your logs, i dont see Winbird reporting any new line characters, i believe that APP is reading byte by byte, and not waiting for newlines.

So you can send many bytes of data to it, and it will keep on blocking until it receives the correct new line characters.

So give SerialPort.Read a try, by reading 1 byte at a time for starters,

public int Read (
byte[] buffer,
int offset,
int count

)

If this doesnt fix it, you might want to consider the following

Some of my problems were fixed with adding a few Thread.Sleep()'s because i realized the PC's UARTs are not fast enough to electrically transmit the data over the RS232/RS485 ports correctly, also wait a few milliseconds after opening the port.

I would also advise you to rather create a separate thread to handle the serial comms, instead of using SerialDataReceivedEventHandler, create a send buffer, which is sent in the correct increments without blocking your app, also read the data and append bytes received to buffer until you have received enough data.

You are also going to need a second serial device to capture your data to make sure your C# app is transmitting the correct data.

To elimate the issue of handshaking, test by only having PIN 2,3 + PIN 5 (GND) connected.

Hope this helps


问:
How to update data in Laravel - there is array value in data
There is field affiliated_facility which is in array and I am trying to update my values:

My controller code:

```<code><?php
$affiliated_facility = implode(",", $userProfile['affiliated_facility']);
$userBasicInfoId = UserBasicInfo::where('user_id', $userProfile['id'])->value('id')->update([

    'work_phone' => $userProfile['work_phone'],
    'fax' => $userProfile['fax'],
    'extension' => $userProfile['extension'],
    'primary_facility' => $userProfile['primary_facility'],
    'employed_by' => $userProfile['employed_by'],
    'emergency_phone' => $userProfile['emergency_phone'],
    'designation' => $userProfile['designation'],
    'department' => $userProfile['department'],
    'employment_type' => $userProfile['employment_type'],
    'biography' => $userProfile['biography'],
    'hiring_date' => $userProfile['hiring_date'],
    'from' => $userProfile['from'],
    'to' => $userProfile['to'],
    'affiliated_facility' => $affiliated_facility]);   // this is in array so I used implode in top of this code

if ($userBasicInfoId) {
    $userBasicInfo = $this->userBasicInfo->find($userBasicInfoId);
    $userBasicInfo->fill($userProfile)->save();
} else {
    $userBasicInfo = $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
}
?>
</code>```

But when  I hit my request it says

Call to a member function update() on integer

There is some mistakes in my code. I want to update my record and there is one field coming which is in array:

```<code>"affiliated_facility": [1,2]
</code>```

How can I modify this code?

答:
UserBasicInfo::where('user_id', $userProfile['id']) is a Builder instance. you should get Model instance to update it. So, try:

```<code> UserBasicInfo::where('user_id', $userProfile['id'])->first()->update([...]);
</code>```

Body:
There is field affiliated_facility which is in array and I am trying to update my values:

My controller code:

<?php
$affiliated_facility = implode(",", $userProfile['affiliated_facility']);
$userBasicInfoId = UserBasicInfo::where('user_id', $userProfile['id'])->value('id')->update([

    'work_phone' => $userProfile['work_phone'],
    'fax' => $userProfile['fax'],
    'extension' => $userProfile['extension'],
    'primary_facility' => $userProfile['primary_facility'],
    'employed_by' => $userProfile['employed_by'],
    'emergency_phone' => $userProfile['emergency_phone'],
    'designation' => $userProfile['designation'],
    'department' => $userProfile['department'],
    'employment_type' => $userProfile['employment_type'],
    'biography' => $userProfile['biography'],
    'hiring_date' => $userProfile['hiring_date'],
    'from' => $userProfile['from'],
    'to' => $userProfile['to'],
    'affiliated_facility' => $affiliated_facility]);   // this is in array so I used implode in top of this code

if ($userBasicInfoId) {
    $userBasicInfo = $this->userBasicInfo->find($userBasicInfoId);
    $userBasicInfo->fill($userProfile)->save();
} else {
    $userBasicInfo = $this->userBasicInfo->create($request->only($this->userBasicInfo->getModel()->fillable));
}
?>

But when  I hit my request it says

Call to a member function update() on integer

There is some mistakes in my code. I want to update my record and there is one field coming which is in array:

"affiliated_facility": [1,2]

How can I modify this code?

Body:
UserBasicInfo::where('user_id', $userProfile['id']) is a Builder instance. you should get Model instance to update it. So, try:

 UserBasicInfo::where('user_id', $userProfile['id'])->first()->update([...]);


问:
Importing typescript files in preload script using Electron
I currently have a preload.js script that basically adds variables to the window object for a webview. What I want to do is import a typescript file inside the preload script. The preload only supports commonjs syntax.

Is there any way I can achieve this?

I tried to transpile the file and access the webpack output but it didn't work.

答:
So, the best solution I found was using an external package. First I did publishing it to npm and now I'm using yarn workspaces and simply requiring my package inside preload.js

const = { MyClass } = require('my-workspace-package')

and then I can use it freely inside the file (and also inject it into my window object for instance)


问:
Can I resolve a Promise inside another resolved Promise?
I'm writing a method to iterate through a series of items to find either the next incomplete or the last one that returns a promise.

The item status is fetched by another method that also returns a promise and I'm trying to resolve/reject within the resolve callback of this method.

Simplified version of my attempt below:

```<code>export const findNextEntry = (i) => {
  let length = entries.length
  let entry = entries[i]
  entry.isLastEntry = i + 1 >= length

  return new Promise((resolve, reject) => {
    getEntryStatus(i).then(() => {
      if (entry.status.complete) {
        if ((i + 1) < length) {
          findNextEntry(i + 1)
        } else {
          reject('no more entries')
        }
      } else {
        resolve('entry set')
      }
    })
  })
</code>```

And then I call the method:

```<code>findNextEntry(entry.number).then((resolve) => {
   console.log(resolve)
}, (reject) => {
   console.log(reject)
})
</code>```

The resolve/reject callbacks don't seem to be firing, and I get an error Uncaught (in promise) no more entries.

答:
Probebly you must call reject/resolve for nested iterations

```<code>export const findNextEntry = (i) => {
  let length = entries.length
  let entry = entries[i]
  entry.isLastEntry = i + 1 >= length

  return new Promise((resolve, reject) => {
    getEntryStatus(i).then(() => {
      if (entry.status.complete) {
        if ((i + 1) < length) {
          findNextEntry(i + 1).then(resolve).catch(reject)
        } else {
          reject('no more entries')
        }
      } else {
        resolve('entry set')
      }
    })
  })
</code>```

Similar but more simple code

```<code>function test(i = 0) {
    console.log(i);
    return new Promise((resolve, reject) => {
        if (i < 10) test(i + 1).then(resolve).catch(reject);
        else resolve('done');
    });
}

test();
</code>```

Body:
I'm writing a method to iterate through a series of items to find either the next incomplete or the last one that returns a promise.

The item status is fetched by another method that also returns a promise and I'm trying to resolve/reject within the resolve callback of this method.

Simplified version of my attempt below:

export const findNextEntry = (i) => {
  let length = entries.length
  let entry = entries[i]
  entry.isLastEntry = i + 1 >= length

  return new Promise((resolve, reject) => {
    getEntryStatus(i).then(() => {
      if (entry.status.complete) {
        if ((i + 1) < length) {
          findNextEntry(i + 1)
        } else {
          reject('no more entries')
        }
      } else {
        resolve('entry set')
      }
    })
  })

And then I call the method:

findNextEntry(entry.number).then((resolve) => {
   console.log(resolve)
}, (reject) => {
   console.log(reject)
})

The resolve/reject callbacks don't seem to be firing, and I get an error Uncaught (in promise) no more entries.

Body:
Probebly you must call reject/resolve for nested iterations

export const findNextEntry = (i) => {
  let length = entries.length
  let entry = entries[i]
  entry.isLastEntry = i + 1 >= length

  return new Promise((resolve, reject) => {
    getEntryStatus(i).then(() => {
      if (entry.status.complete) {
        if ((i + 1) < length) {
          findNextEntry(i + 1).then(resolve).catch(reject)
        } else {
          reject('no more entries')
        }
      } else {
        resolve('entry set')
      }
    })
  })

Similar but more simple code

function test(i = 0) {
    console.log(i);
    return new Promise((resolve, reject) => {
        if (i < 10) test(i + 1).then(resolve).catch(reject);
        else resolve('done');
    });
}

test();


问:
Dismissing dialog and showing new one shortly shows underlying fragment before opening new dialog
I currently have one fragment that shows dialogfragment, and when I press the button on dialogfragment, I want to show another dialogfragment. In my first dialog fragment I have following method:

```<code> fun showSecondDialog() {
    dismiss()
    SecondDialog().showDialog(targetFragment!!)
}
</code>```

showDialog() looks like this:

```<code>    fun showDialog(fragment: Fragment) {
    val fragmentManager = fragment.fragmentManager
    val ft = fragmentManager!!.beginTransaction()
    val prev = fragmentManager.findFragmentByTag(getName())
    if (prev != null) {
        ft.remove(prev)
    }
    ft.addToBackStack(null)

    setTargetFragment(fragment, 0)
    show(ft, getName())
}
</code>```

The problem is, that dismissing dialog works immediately, but before the new dialog is shown there is a gap, where my underlying fragment is fully visible and this causes an undesirable flicker.

How to show second dialog immediately, or how to know when it's opened, so I could close the first one?

答: Google recommends all the fragment inflate, replace, dismiss...should be done in the parent activity and no fragment should know anything about any other fragment. That way fragments can be reused like they were initially designed to. </p>

Body:
I currently have one fragment that shows dialogfragment, and when I press the button on dialogfragment, I want to show another dialogfragment. In my first dialog fragment I have following method:

 fun showSecondDialog() {
    dismiss()
    SecondDialog().showDialog(targetFragment!!)
}

showDialog() looks like this:

    fun showDialog(fragment: Fragment) {
    val fragmentManager = fragment.fragmentManager
    val ft = fragmentManager!!.beginTransaction()
    val prev = fragmentManager.findFragmentByTag(getName())
    if (prev != null) {
        ft.remove(prev)
    }
    ft.addToBackStack(null)

    setTargetFragment(fragment, 0)
    show(ft, getName())
}

The problem is, that dismissing dialog works immediately, but before the new dialog is shown there is a gap, where my underlying fragment is fully visible and this causes an undesirable flicker.

How to show second dialog immediately, or how to know when it's opened, so I could close the first one?


问:
Conditional If Statement applied to dataframe
I am trying to iterate in a pythonic way (i.e. without a loop) through a dataframe in order to create a new columns based on whether the condition was met. In particular, given a dataframe of daily returns, I would like to create a new column that tells me whether either an upper limit or lower limit was crossed (limit is symmetric, but stock specific, so each row might have a different limit, called std in the df below) , something like this:

```<code>import pandas as pd
dict = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'ge', 'date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'}
]
df = pd.DataFrame(dict)
df['date']      = pd.to_datetime(df1['date'])
df=df.set_index(['date','ticker'], drop=True)
</code>```

That should be transformed, such that I obtain a new column which contains the respective day's return, if the upper/lower threshold was crossed, if it wasn't crossed, it should just contain the last day's return (so returns2).

```<code>dict2 = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.05','returns2': '-0.3','std': '0.1','sl': '-0.3'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'}
]
df2 = pd.DataFrame(dict2)
df2['date']      = pd.to_datetime(df2['date'])
df2=df2.set_index(['date','ticker'], drop=False)
</code>```

I am trying to keep this flexible (so it works for more than just 2 columns with returns) and efficient (so that it works on very large dfs.

Can anyone suggest an approach?

答:
Working on df2.

```<code># Make columns numeric
df2[["returns", "returns2", "std"]] = df2[["returns", "returns2", "std"]].astype(float)

# Create new column using returns2 (we'll overwrite it in . moment)
df2["output"] = df2["returns2"]
# Mask whether returns crosses std
m = df2["returns"].abs() > df2["std"]
# Overwrite that mask onto new column
df2.loc[m, "output"] = df2.loc[m, "returns"]
</code>```

If you want to extend this to more than 2 columns then we'd need to understand the criteria for which column to select but the process would be the same: you build a mask that matches your criteria and you apply it.

Body:
I am trying to iterate in a pythonic way (i.e. without a loop) through a dataframe in order to create a new columns based on whether the condition was met. In particular, given a dataframe of daily returns, I would like to create a new column that tells me whether either an upper limit or lower limit was crossed (limit is symmetric, but stock specific, so each row might have a different limit, called std in the df below) , something like this:

import pandas as pd
dict = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{ 'ticker':'ge','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-28','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'ge', 'date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'aapl','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'},
{'ticker':'amzn','date': '2016-11-29','returns': '0.2','returns2': '0.3','std': '0.1'}
]
df = pd.DataFrame(dict)
df['date']      = pd.to_datetime(df1['date'])
df=df.set_index(['date','ticker'], drop=True)

That should be transformed, such that I obtain a new column which contains the respective day's return, if the upper/lower threshold was crossed, if it wasn't crossed, it should just contain the last day's return (so returns2).

dict2 = [
        {'ticker':'jpm','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{ 'ticker':'ge','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb', 'date': '2016-11-28','returns': '0.05','returns2': '-0.3','std': '0.1','sl': '-0.3'},
{'ticker':'aapl', 'date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-28','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-28','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'jpm','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'ge', 'date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'fb','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'aapl','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'},
{'ticker':'msft','date': '2016-11-29','returns': '0.2','returns2': '-0.3','std': '0.1','sl': '0.2'},
{'ticker':'amzn','date': '2016-11-29','returns': '-0.2','returns2': '0.3','std': '0.1','sl': '-0.2'}
]
df2 = pd.DataFrame(dict2)
df2['date']      = pd.to_datetime(df2['date'])
df2=df2.set_index(['date','ticker'], drop=False)

I am trying to keep this flexible (so it works for more than just 2 columns with returns) and efficient (so that it works on very large dfs.

Can anyone suggest an approach?

Body:
Working on df2.

# Make columns numeric
df2[["returns", "returns2", "std"]] = df2[["returns", "returns2", "std"]].astype(float)

# Create new column using returns2 (we'll overwrite it in . moment)
df2["output"] = df2["returns2"]
# Mask whether returns crosses std
m = df2["returns"].abs() > df2["std"]
# Overwrite that mask onto new column
df2.loc[m, "output"] = df2.loc[m, "returns"]

If you want to extend this to more than 2 columns then we'd need to understand the criteria for which column to select but the process would be the same: you build a mask that matches your criteria and you apply it.


问:
Setting NSUnderlineStyle causes unrecogognized selector exception
I am trying to underline a string with NSAttributed string. For some reason, my lines cause the exception:

```<code>-[_SwiftValue _getValue:forType:]: unrecognized selector sent to instance
</code>```

The result is supposed to be used for a UILabel within a UITableView and is created as needed.

This is the code:

```<code>attributedString = NSMutableAttributedString(string: message)

if let actor = event.actor {
   let attributes = [NSUnderlineStyleAttributeName:NSUnderlineStyle.styleSingle]
   var attributedActorString = NSMutableAttributedString(string: actor.shirtName, attributes: attributes)
   attributedActorString.insert(NSAttributedString(string: " "), at: 0)
   attributedActorString.append(NSAttributedString(string: ". "))                               attributedActorString.append(attributedImageStringForUrl(event.actor!.portraitImageUrl, indexPath: indexPath))
   attributedString.append(attributedActorString)
}
</code>```

答:
Swift 5 version of Vlad Khambir answer,

```<code>let attributes = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue]
</code>```

Body:
I am trying to underline a string with NSAttributed string. For some reason, my lines cause the exception:

-[_SwiftValue _getValue:forType:]: unrecognized selector sent to instance

The result is supposed to be used for a UILabel within a UITableView and is created as needed.

This is the code:

attributedString = NSMutableAttributedString(string: message)

if let actor = event.actor {
   let attributes = [NSUnderlineStyleAttributeName:NSUnderlineStyle.styleSingle]
   var attributedActorString = NSMutableAttributedString(string: actor.shirtName, attributes: attributes)
   attributedActorString.insert(NSAttributedString(string: " "), at: 0)
   attributedActorString.append(NSAttributedString(string: ". "))                               attributedActorString.append(attributedImageStringForUrl(event.actor!.portraitImageUrl, indexPath: indexPath))
   attributedString.append(attributedActorString)
}

Body:
Swift 5 version of Vlad Khambir answer,

let attributes = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue]


问:
How to create a tree hierarchy in Haskell?
How do I achieve the same result shown in this question using Haskell and non-binary trees, such as Data.Tree? Considering the record NodeData { nodeID :: String , parentID :: String, value :: a } to store data, and Data.Tree for the tree type, a tree would be:

```<code>Node $ NodeData "id" "parent" (value :: a) (children :: Forest (NodeData a)) :: Tree (NodeData a)
</code>```

Now how could I update value based on the node's children's value and its own? The input table would be a list [NodeData]. NodeData and the ids could be made an instance of Eq, but not Ord.

答:
I see no particularly clever single-pass solution to this. You simply have to bite the bullet and do two passes: one pass creates an index of the form Map Id [Node], listing all the children of each node. Then a second pass consumes this index and reconstitutes it into a Forest a. Note it's not a Tree a, because there's no value to put at the root, and also because for all we know there are multiple roots.

```<code>import qualified Data.Map.Lazy as M
import qualified Data.Tree as T

newtype Id = Id Int deriving (Eq, Show, Ord)
data Node a = Node {id, parent :: Id, value :: a} deriving Show

input :: [Node String]
input = [ Node (Id 1) (Id 0) "1"
        , Node (Id 2) (Id 1) "1.1"
        , Node (Id 3) (Id 0) "2"
        , Node (Id 4) (Id 2) "1.1.1"
        , Node (Id 5) (Id 3) "2.1"
        , Node (Id 6) (Id 1) "1.2"
        ]

index :: [Node a] -> M.Map Id [Node a]
index m = M.fromListWith (++) $ do
  n@(Node this parent v) <- m
  pure (parent, [n])

recombine :: M.Map Id [Node a] -> T.Forest a
recombine m = go (Id 0) -- Implied root, but a more thorough solution would be explicit
  where go root = [ T.Node v (go idx)
                  | Node idx p v <- M.findWithDefault [] root m
                  ]
</code>```

After this, we have the tree we wanted:

```<code>> putStr . T.drawForest . recombine . index $ input
2
|
`- 2.1

1
|
+- 1.2
|
`- 1.1
   |
   `- 1.1.1
</code>```

Body:
How do I achieve the same result shown in this question using Haskell and non-binary trees, such as Data.Tree? Considering the record NodeData { nodeID :: String , parentID :: String, value :: a } to store data, and Data.Tree for the tree type, a tree would be:

Node $ NodeData "id" "parent" (value :: a) (children :: Forest (NodeData a)) :: Tree (NodeData a)

Now how could I update value based on the node's children's value and its own? The input table would be a list [NodeData]. NodeData and the ids could be made an instance of Eq, but not Ord.

Body:
I see no particularly clever single-pass solution to this. You simply have to bite the bullet and do two passes: one pass creates an index of the form Map Id [Node], listing all the children of each node. Then a second pass consumes this index and reconstitutes it into a Forest a. Note it's not a Tree a, because there's no value to put at the root, and also because for all we know there are multiple roots.

import qualified Data.Map.Lazy as M
import qualified Data.Tree as T

newtype Id = Id Int deriving (Eq, Show, Ord)
data Node a = Node {id, parent :: Id, value :: a} deriving Show

input :: [Node String]
input = [ Node (Id 1) (Id 0) "1"
        , Node (Id 2) (Id 1) "1.1"
        , Node (Id 3) (Id 0) "2"
        , Node (Id 4) (Id 2) "1.1.1"
        , Node (Id 5) (Id 3) "2.1"
        , Node (Id 6) (Id 1) "1.2"
        ]

index :: [Node a] -> M.Map Id [Node a]
index m = M.fromListWith (++) $ do
  n@(Node this parent v) <- m
  pure (parent, [n])

recombine :: M.Map Id [Node a] -> T.Forest a
recombine m = go (Id 0) -- Implied root, but a more thorough solution would be explicit
  where go root = [ T.Node v (go idx)
                  | Node idx p v <- M.findWithDefault [] root m
                  ]

After this, we have the tree we wanted:

> putStr . T.drawForest . recombine . index $ input
2
|
`- 2.1

1
|
+- 1.2
|
`- 1.1
   |
   `- 1.1.1


问:
How does Parquet file size changes with the count in Spark Dataset
I came across a scenario where I had spark dataset with 24 columns, of which I was grouping by First 22 columns and summing up last two columns.

I removed the group by from the query and I have all 24 columns selected now.
Initial count of the dataset was 79,304.

After I removed group by the count has increased to 138,204 which is understood because I have removed the group by.

But I was not clear with the behavior that The initial size of parquet file was 2.3MB but later it got reduced to 1.5MB . Can anyone please help me understand this.

Also not every time the size reduces,
I had a similar scenario for 22 columns
count before was 35,298,226 and after removing group by was 59,874,208
and here the size has increased from 466.5MB to 509.8MB

答:
When dealing with parquet sizes it's not about the number of rows it's about the data it self.
Parquet is columnar oriented format and therefore it store data column wise and compress the data column wise. Therefore it's not about the number of rows but rather the diversity of it's columns.

Parquet will do better compression as the diversity of the most diverse column in the table. So if you have one column dataframe it will be compress good as the distance between the values of the column.


问:
Temparory Table update
I âm creating some temporary table in mysql
updating this table but get error

```<code>`CREATE TEMPORARY TABLE test (id varchar(50), name varchar(50));
INSERT INTO test (id, name) VALUES (1, 'LF/2019/0001');
SELECT name FROM test;
UPDATE test SET name = (SELECT name FROM test ORDER BY id DESC) + 1 WHERE id = 1;`
</code>```

```<code>Error show :

MySQL said: Documentation

#1137 - Can't reopen table: 'test'
</code>```

Please help,
Thanks,

答:
If you want to update that particular column for once then you can use following script</p>

```<code>CREATE TEMPORARY TABLE test (id varchar(50), name varchar(50));
INSERT INTO test (id, name) VALUES (1, 'LF/2019/0001');
SELECT name FROM test;
UPDATE test SET name = concat('LF/2019/000',cast((cast(SELECT substring(name,9) FROM test ORDER BY id DESC) as unsigned integer) + 1) as char) WHERE id = '1';

drop table test
</code>```

Title: Temparory Table update

Body:
I âm creating some temporary table in mysql
updating this table but get error

`CREATE TEMPORARY TABLE test (id varchar(50), name varchar(50));
INSERT INTO test (id, name) VALUES (1, 'LF/2019/0001');
SELECT name FROM test;
UPDATE test SET name = (SELECT name FROM test ORDER BY id DESC) + 1 WHERE id = 1;`

Error show :

MySQL said: Documentation

#1137 - Can't reopen table: 'test'

Please help,
Thanks,

Body:
If you want to update that particular column for once then you can use following script

CREATE TEMPORARY TABLE test (id varchar(50), name varchar(50));
INSERT INTO test (id, name) VALUES (1, 'LF/2019/0001');
SELECT name FROM test;
UPDATE test SET name = concat('LF/2019/000',cast((cast(SELECT substring(name,9) FROM test ORDER BY id DESC) as unsigned integer) + 1) as char) WHERE id = '1';

drop table test