text:
Q: How to calculate difference between non-consecutive rows in Python DataFrame? I have following pandas DataFrame and trying to create a new "Value_Diff" column where it calculates the difference between current "value" if lable=0 with the previous value where label=1. If label=1 it sets the "Value_Diff" equals to 0. This process needs to be repeated for each group and if first label in the group is equal to 0 it should leave the "Value_Diff" equal to 0 until it reaches first label=1 and then follow the same logic ( group C in this example)
I can write a for loop and if statement for each individual group to do this, however was wondering if there is a better way to do this with using groupby, lambda or any other function.
here is the input:
 group  Date         Value   label
 A     2020-03-01   -117    1
 A     2020-03-02   -121    0
 A     2020-03-03   -122    0
 A     2020-03-04   -122    1
 B     2020-03-05   -118    1
 B     2020-03-06   -122    0
 B     2020-03-07   -124    0
 B     2020-03-08   -126    0
 B     2020-03-09   -126    1
 C     2020-03-10   -130    0
 C     2020-03-11   -140    0
 C     2020-03-12   -150    1
 C     2020-03-13   -160    0

Answer should look like this:
 group  Date        Value  label   Value_Diff
 A     2020-03-01   -117    1         0
 A     2020-03-02   -121    0         4 (-117-(-121)=4)
 A     2020-03-03   -122    0         1
 A     2020-03-04   -122    1         0
 B     2020-03-05   -118    1         0
 B     2020-03-06   -122    0         4
 B     2020-03-07   -124    0         2
 B     2020-03-08   -126    0         2
 B     2020-03-09   -126    1         0
 C     2020-03-10   -130    0         0
 C     2020-03-11   -140    0         0
 C     2020-03-12   -150    1         0
 C     2020-03-13   -160    0         10

Sorry my first output didn't actually reflect what I wanted, because @BENY provided the solution to this output I'll leave this here to help others with the same question.
Here is how the actual output should look like.
 group  Date        Value  label   Value_Diff
 A     2020-03-01   -117    1         0
 A     2020-03-02   -121    0         4 (-117-(-121)=4)
 A     2020-03-03   -122    0         5 (-117-(-122)=5)
 A     2020-03-04   -122    1         0
 B     2020-03-05   -118    1         0
 B     2020-03-06   -122    0         4 (-122-(-118)=4)
 B     2020-03-07   -124    0         6 (-124-(-118)=6)
 B     2020-03-08   -126    0         8 (-126-(-118)=8)
 B     2020-03-09   -126    1         0
 C     2020-03-10   -130    0         0
 C     2020-03-11   -140    0         0
 C     2020-03-12   -150    1         0
 C     2020-03-13   -160    0         10 (-150-(-160)=10)

A: We can try with cummax create the 1st condition, then use groupby with diff
s = df.groupby('group').label.cummax()
df['new'] = -df.groupby('group').Value.diff().fillna(0).where(s==1 & df.label.ne(1),0)
df
Out[135]:
   group        Date  Value  label   new
0      A  2020-03-01   -117      1  -0.0
1      A  2020-03-02   -121      0   4.0
2      A  2020-03-03   -122      0   1.0
3      A  2020-03-04   -122      1  -0.0
4      B  2020-03-05   -118      1  -0.0
5      B  2020-03-06   -122      0   4.0
6      B  2020-03-07   -124      0   2.0
7      B  2020-03-08   -126      0   2.0
8      B  2020-03-09   -126      1  -0.0
9      C  2020-03-10   -130      0  -0.0
10     C  2020-03-11   -140      0  -0.0
11     C  2020-03-12   -150      1  -0.0
12     C  2020-03-13   -160      0  10.0

A: I find it's best to do these things one step at a time.  I think this does (the second version) of what you want:
df['Value_Last'] = np.nan
df.loc[df.label == 1, 'Value_Last'] = df.loc[df.label == 1, 'Value']
df_grouped = df.groupby('group')
df['Value_Last'] = df_grouped['Value_Last'].ffill()
df['Value_Diff'] = (df['Value_Last'] - df['Value']).fillna(0)

   group        Date  Value  label  Value_Last  Value_Diff
0      A  2020-03-01   -117      1      -117.0         0.0
1      A  2020-03-02   -121      0      -117.0         4.0
2      A  2020-03-03   -122      0      -117.0         5.0
3      A  2020-03-04   -122      1      -122.0         0.0
4      B  2020-03-05   -118      1      -118.0         0.0
5      B  2020-03-06   -122      0      -118.0         4.0
6      B  2020-03-07   -124      0      -118.0         6.0
7      B  2020-03-08   -126      0      -118.0         8.0
8      B  2020-03-09   -126      1      -126.0         0.0
9      C  2020-03-10   -130      0         NaN         0.0
10     C  2020-03-11   -140      0         NaN         0.0
11     C  2020-03-12   -150      1      -150.0         0.0
12     C  2020-03-13   -160      0      -150.0        10.0

PS: If the 'Value' column contains only integers then you can use .astype(int) on the end of the last line to convert 'Value_Diff' back to integers.


text:
Q: Domain-Driven Design with different roles I am new to DDD. I want to build an application implementing DDD, but I have a problem with the Roles.
The application has many roles like customer, admin, etc. The admin can create, edit, and delete post. The customer can only comment on the post.
Base on that description, I think the post should have different methods in those 2 different contexts. Should I create 2 directories for those 2 roles and duplicate the post in each directory?
Thanks a lot!

A: There are different domains and there are different bounded contexts.
Your core domain that effects business state changes is only concerned with how to implement those mutations.  It is not terribly concerned about security or access control.
Your application/integration layer is the gatekeeper and decides who gets to call what on the domain.  For that you may even use another Identity and Access Management (IAM) bounded context which manages the authorisation.
As an example I like to use a physical calculator to represent my domain.  I can access absolutely any and all functions on the calculator.  Something outside of the calculator would need to determine which buttons I can press.  I hope that makes sense.

A: I'm not sure you would need to distinguish between posts in different roles.  Off the top of my head, it seems potentially practical to:

*

*include the role as an argument with the operations on posts, so that a post can reject an attempt by a customer to edit/delete a post.

*route the operation through the user, which validates that its role allows the operation.
Those can be elaborated on and could be combined.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Web scraping google search page with nodejs and cheerio I am having problems scraping a google search page. I can scrape a normal web page but the same code does not work on a search page
I am using nodejs with cheerio api. The search page is for the "restaurants near me". Here is the code
var request = require('request');
var cheerio = require('cheerio');

request('https://www.google.com/search?rlz=1C1CHBF_enUS795US795&q=restaurants+near+me&npsic=0&rflfq=1&rlha=0&rllag=43556429,-83953443,247&tbm=lcl&ved=2ahUKEwikkKDVhvPcAhUEmuAKHekOBl4QjGp6BAgDEE8&tbs=lrf:!2m1!1e2!2m1!1e5!2m1!1e1!2m1!1e3!3sIAE,lf:1,lf_ui:9&rldoc=1#rlfi=hd:;si:;mv:!1m3!1d37687.821017182374!2d-83.91493835!3d43.58986!2m3!1f0!2f0!3f0!3m2!1i324!2i313!4f13.1;tbs:lrf:!2m1!1e2!2m1!1e5!2m1!1e1!2m1!1e3!3sIAE,lf:1,lf_ui:9',(error,response,html)=>{
  if(!error && response.statusCode==200){
    const $= cheerio.load(html)

    $(".dbg0pd").each(function(i, element){
      var a = $(this);
      console.log('This is from inside the loop')
      console.log(a.text());
    });

  }
})

In the web page, running inspect element shows that the class dbg0pd contains the div element which contains the name of the restaurant. However the .each() jquery loop does not even fire as my test console.log statement does not print This is from inside the loop
Running node scrape.js does not print anything.


text:
Q: Excel VBA - Convert date to display as text in the form MMM YYYY I would like to convert Column A or Range A from date format to display as text format MMM YYYY.
Here is the worksheet layout:

However, no changes occur as I run the code:
Sub CONVERT_DATE()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Workbooks.Open ("MyWorkbook.xlsx")
Workbooks("MyWorkbook.xlsx").Activate

Dim ws As Worksheet
Set ws = Workbooks("MyWorkbook.xlsx").Sheets("MyWorkSheet")

Dim wsLastRow As Long
wsLastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

'Convert date to display as text in the format mmm yyyy

ws.Range("A2:A" & wsLastRow).Text = Format(ws.Range("A2:A" & wsLastRow).Text, "mmm yyyy")

Workbooks("MyWorkbook.xlsx").Close SaveChanges:=True

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

Can anyone spot the issue(s)?
Many thanks!

A: Use NumberFormat instead of trying to set the Text
Sub CONVERT_DATE()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Workbooks.Open ("MyWorkbook.xlsx")
Workbooks("MyWorkbook.xlsx").Activate

Dim ws As Worksheet
Set ws = Workbooks("MyWorkbook.xlsx").Sheets("MyWorkSheet")

Dim wsLastRow As Long
wsLastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

'Convert date to display as text in the format mmm yyyy

' change this line
ws.Range("A2:A" & wsLastRow).NumberFormat = "mmm yyyy"

Workbooks("MyWorkbook.xlsx").Close SaveChanges:=True

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

A: Instead of this line
ws.Range("A2:A" & wsLastRow).Text = Format(ws.Range("A2:A" & wsLastRow).Text, "mmm yyyy")

Use NumberFormat to change the format of your range
ws.Range("A2:A" & wsLastRow).NumberFormat = "mmm yyyy"


text:
Q: Interaction of python with pypy via subprocess I'm writing a pygtk application in Python 2.7.5 that requires some heavy mathematical calculations, so I need to do these calculations in an external pypy (that don't support gtk) for efficiency and plot the results in the main program as they are produced.
Since the ouput of the calculations is potentially infinite and I want to show it as it is produced, I cannot use subprocess.Popen.communicate(input).
I am able to do non-blocking reads of the output (via fcntl), but I am not able to effectively send the input (or anyway something else that I don't see is going wrong). For ex, the following code:
import subprocess

# start pypy subprocess
pypy = subprocess.Popen(['pypy', '-u'], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

# send input to pypy
pypy.stdin.write('import sys\nprint "hello"\nsys.stdout.flush()\n')
pypy.stdin.flush()

# read output from pypy
pypy.stdout.flush()
print pypy.stdout.readline()

Will get stuck on the last line. What is weird to me is that if I substitute 'pypy' with 'cat' it will work, and if I substitute the input-output lines with
print pypy.communicate(input='import sys\nprint "hello"\nsys.stdout.flush()\n')[0]

it will also work (but it does not fit with what I want to do). I thought it was a problem of buffering, but I tried several ways of avoiding it (including writing to stderr and so) with no luck. I also tried sending to pypy the command to print in a while True loop, also with no luck (that makes me think that is not a problem with output buffering but maybe with input buffering).


text:
Q: which ppa or repo has libgmime-2.0-2a? where can I download this package?  I've found it in hardy, but it seems to be unavailable.
I'm trying to install dbmail from http://debian.nfgd.net/debian :
thufir@dur:~$
thufir@dur:~$ sudo aptitude install dbmail -v
The following NEW packages will be installed:
  dbmail{b}
The following packages are SUGGESTED but will NOT be installed:
  dbmail-mysql dbmail-pgsql
0 packages upgraded, 1 newly installed, 0 to remove and 5 not upgraded.
Need to get 315 kB of archives. After unpacking 1,053 kB will be used.
The following packages have unmet dependencies:
  dbmail: Depends: libgmime-2.0-2a which is a virtual package.
The following actions will resolve these dependencies:

     Keep the following packages at their current version:
1)     dbmail [Not Installed]

Accept this solution? [Y/n/q/?] Y
No packages will be installed, upgraded, or removed.
0 packages upgraded, 0 newly installed, 0 to remove and 5 not upgraded.
Need to get 0 B of archives. After unpacking 0 B will be used.

Current status: 0 broken [+0], 5 updates [+0], 27 new [+0].
thufir@dur:~$
thufir@dur:~$ aptitude search libgmime
i   libgmime-2.4-2                        - MIME message parser and creator library - runtim
i   libgmime-2.4-dev                      - MIME message parser and creator library - develo
p   libgmime-2.4-doc                      - MIME message parser and creator library - docume
i   libgmime2.4-cil                       - CLI binding for the GMime library
p   libgmime2.4-cil-dev                   - CLI binding for the GMime library
thufir@dur:~$
thufir@dur:~$ tail /etc/apt/sources.list

## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu oneiric main
# deb-src http://extras.ubuntu.com/ubuntu oneiric main
deb http://archive.ubuntu.com/ubuntu oneiric multiverse restricted universe main

deb http://debian.nfgd.net/debian unstable main
thufir@dur:~$

I upgraded to 12.04

A: You likely won't find a PPA with such an old version of libgmime for a new release (the current version appears to be 2.6 (libgmime-2.6-0)). Possible solutions include:

*

*Contact the upstream developer of the software and see if a newer version would work instead.

*Compile the libgmime version you need from source.

*Install the Natty version of libgmime-2.0-2a


text:
Q: Apple Push Notifications System Not Receving Message! (PHP) This is the code I wrote to send apple push notifications.
in the device_tokens i'm sending an array with all of the tokens I want to send message to.
For some reason, I stopped recieving messages from this system.
and it used to work before!
private function send_iphone_notification($device_tokens, $message)
{
    define("PRODUCTION_MODE", true);

    $apnsPort = 2195;

    // Choose dev or production apns host and certificate
    if(PRODUCTION_MODE) {
        $apnsHost = 'gateway.push.apple.com';
        $apnsCert = $_SERVER['DOCUMENT_ROOT'].'/ant/www/apns/PushIphone.pem';
    } else {
        $apnsHost = 'gateway.sandbox.push.apple.com';
        $apnsCert = $_SERVER['DOCUMENT_ROOT'].'/ant/www/apns/CertificatesDev.pem';
    }
    // Notification content
    $payload = json_encode(array('notification_from_panel' => 1, 'aps' => array('alert' => $message, 'badge' => 1, 'sound' => 'default')));

    $streamContext = stream_context_create();
    stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
    stream_context_set_option($streamContext, 'ssl', 'passphrase', "");

    // loop all devices tokens
    foreach ($device_tokens as $device_token)
    {
        try {
            $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
        } catch(Exception $e) {
            echo $e->getMessage();
            continue;
        }
        $deviceToken = str_replace(" ","",substr($device_token,1,-1));
        //echo $deviceToken;
        $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(mb_strlen($payload)) . $payload;
        fwrite($apns, $apnsMessage);

        //socket_close($apns);
        fclose($apns);
    }

}

A: I have some experience with Apple's push service and i have to say that apple seems to have soem restrictions in place.
First of all you dont need to close and open the socket connection for every message. That will save you a lot of time. On the other hand you have to check if the connection is broken before you send the next message.
Anyway, it seemed that apple does not like it much when you connect a hundred times a second and send messages. Apples has blocked me for that as well in the passed.
But when you send the message with a already established connection, and at some point the connection is returning an error/ is disconnected, you dont know at what message he stopped. But you can define a identifier for each message and check the error returned when the connection is broken.
I noticed that apples server returns the error with a couple of seconds delay. That makes it hard do deal with it the easy way.
I have written a class to handle all of that but did not jet have time to publish it! If you are interested in it, check the github project for it at https://github.com/tinned-software/PHP-Tinned-MobilePush
I hope to finish the documentation soon.


text:
Q: Safari (iPad iOS) makes me log in every time, regardless of settings Example of the problem: I log into Salesforce via my Safari mobile browser. Once logged in I select the "Home" tab in my org and click "Open in New Tab." Even though I'm opening from an existing, authenticated Salesforce tab I get the login screen again.
This happens regardless of whether or not I have Salesforce1 downloaded or whether or not I have "Salesforce1 User" checkbox selected.
I think my boss might want to have his cake and eat it too: ideally he wants to not use the downloadable app (so he can switch back and forth between SF1 and "Full Site") BUT he of course doesn't want to have to login every time he tries to open a new Salesforce tab.
Suggestions? Or is this all expected behavior and I can't really do what I'm trying to do?
Thanks in advance!

A: Having private browsing turned on will stop sessions from being shared across tabs.


text:
Q: removing encyrpted number from xml string with PHP I am trying to parse a order export xml in PHP but I am having an issue when the xml has cardnumbers in it as they are encrypted. Below is a snippet of the xml and the error I am receiving. I am using $xml = new SimpleXMLElement($ox->xml); to parse the xml $ox->xml is the xml as a string pulled from an API. Is there a way to remove the cardnum from the string before passing it to SimpleXML?
XML Snippet (You will notice not all orders have a cardnum):
<?xml version = "1.0" encoding="Windows-1252" standalone="yes"?>
<VFPDataSet>
<sqlresult>
<orderno>1001</orderno>
<custnum>1000</custnum>
<cl_key>WEBF12</cl_key>
<odr_date>2012-07-25T00:00:00</odr_date>
<hold_type/>
<perm_hold>false</perm_hold>
<sys_hold>false</sys_hold>
<ship_date>2012-07-25T00:00:00</ship_date>
<ccheck>G</ccheck>
<paymethod>CK</paymethod>
<cashonly>false</cashonly>
<cardnum>ÈòMh»ÚKj›Õ›Ïzs鄸"®ôLý[0¡ZÍ</cardnum>
<cardtype>VI</cardtype>
...
<edi>false</edi>
</sqlresult>
<sqlresult>
<orderno>1005</orderno>
<custnum>1001</custnum>
<cl_key>NEWCUST</cl_key>
<odr_date>2012-07-26T00:00:00</odr_date>
<hold_type/>
<perm_hold>false</perm_hold>
<sys_hold>false</sys_hold>
<ccheck/>
<paymethod>CK</paymethod>
<cashonly>false</cashonly>
<cardnum/>
<cardtype/>
...
<edi>false</edi>
</sqlresult>
</VFPDataSet>

Error:
Warning: SimpleXMLElement::__construct(): input conversion failed due to input error, bytes 0x90 0x03 0x51 0x3B in C:\inetpub\wwwroot\automa
te\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): input conversion failed due to input error, bytes 0x90 0x03 0x51 0x3B in C:\inetpub\wwwroot\automa
te\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): encoder errorEntity: line 1202: parser error : PCDATA invalid Char value 30 in C:\inetpub\wwwroot\
automate\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): <cardnum>╦å{├╛▲├Ü┬«↓-├┐v┬▒ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on lin
e 43

Warning: SimpleXMLElement::__construct(): ^ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): Entity: line 1202: parser error : PCDATA invalid Char value 25 in C:\inetpub\wwwroot\automate\expo
rtOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): <cardnum>╦å{├╛▲├Ü┬«↓-├┐v┬▒ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on lin
e 43

Warning: SimpleXMLElement::__construct(): ^ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): Entity: line 1202: parser error : PCDATA invalid Char value 7 in C:\inetpub\wwwroot\automate\expor
tOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): <cardnum>╦å{├╛▲├Ü┬«↓-├┐v┬▒ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on lin
e 43

Warning: SimpleXMLElement::__construct(): ^ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): Entity: line 1202: parser error : Premature end of data in tag cardnum line 1202 in C:\inetpub\www
root\automate\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): <cardnum>╦å{├╛▲├Ü┬«↓-├┐v┬▒ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on lin
e 43

Warning: SimpleXMLElement::__construct(): ^ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on l
ine 43

Warning: SimpleXMLElement::__construct(): Entity: line 1202: parser error : Premature end of data in tag sqlresult line 1191 in C:\inetpub\w
wwroot\automate\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): <cardnum>╦å{├╛▲├Ü┬«↓-├┐v┬▒ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on lin
e 43

Warning: SimpleXMLElement::__construct(): ^ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on l
ine 43

Warning: SimpleXMLElement::__construct(): Entity: line 1202: parser error : Premature end of data in tag VFPDataSet line 2 in C:\inetpub\www
root\automate\exportOrdHeader.php on line 43

Warning: SimpleXMLElement::__construct(): <cardnum>╦å{├╛▲├Ü┬«↓-├┐v┬▒ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on lin
e 43

Warning: SimpleXMLElement::__construct(): ^ in C:\inetpub\wwwroot\automate\exportOrdHeader.php on l
ine 43

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:\inetpub\wwwroot\automate\exportOrdHeader.
php:43
Stack trace:
#0 C:\inetpub\wwwroot\automate\exportOrdHeader.php(43 ): SimpleXMLElement->__construct('<?xml version =...')
#1 {main}
thrown in C:\inetpub\wwwroot\automate\exportOrdHeader.php on line 43

A: The simplest solution for this specific case is to remove it by regular expression:
$xml = preg_replace('/<cardnum>.*?<\/cardnum>/s', '<cardnum>REMOVED</cardnum>', $xml);


text:
Q: Conditional vertical scrolling in datatables embedded in a shiny app Actual questions
I have a DataTable interfaced/created via DT::datatable and rendered via DT::renderDataTable.

*

*How do I conditionally enable vertical scrolling by basing the decision on the value of shiny::checkboxInput?

*How do I control the height of my datatable when vertical scrolling is enabled?
I'm a bit at loss with exactly understanding the implications of options scrollY and scrollCollapse and their interaction with other options of DT::renderDataTable or the app itself (e.g. vertical scrolling of the "app windows" itself).
Example
In the following example, I tried to make the value of option scrollY of DT::renderDataTable dependent on a checkbox input (input$action_enable_scrolling) as well as an input that defines the height in pixels (input$scrolling_y_limit).
Problem:
The resulting rendered table does not reactively reflect the choice being made. It seems like once the initial value of input$action_enable_scrolling and input$scrolling_y_limit are considered, they cannot be reactively changed anymore
You'll see that by changing the default values the datatable part behaves differently:

*

*DFLT_action_enable_scrolling <- TRUE

*DFLT_scrolling_y_limit <- 400
Globals
# Packages ----------------------------------------------------------------

library(shiny)

# Variables ----------------------------------------------------------------

DFLT_action_enable_scrolling <- FALSE
DFLT_scrolling_y_limit <- 800

# Functions ---------------------------------------------------------------

createRecord <- function(input, db) {
  db$data <- rbind(
    db$data,
    data.frame(
      task = input$task,
      time = input$time,
      time_unit = "hour",
      stringsAsFactors = FALSE
    )
  )
}
updateRecord <- function(input, db, selection) {
  db$data[selection,] <- data.frame(
    task = input$task,
    time = input$time,
    time_unit = "hour",
    stringsAsFactors = FALSE
  )
}
deleteRecord <- function(db, selection) {
  db$data <- db$data[-selection,]
}
niceNames <- function(x) {
  s <- strsplit(x, " |_|\\.", perl = TRUE)[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
    sep = "", collapse = " ")
}

UI
ui <- fluidPage(
  div(
    style = "display:inline-block",
    p(),
    actionButton("action_trigger", "Create")
  ),
  tabsetPanel(
    tabPanel(
      title = "Scrolling options",
        checkboxInput("action_enable_scrolling", "Enable Y-scrolling",
          value = DFLT_action_enable_scrolling),
        numericInput("scrolling_y_limit", "Height limit for Y-scrolling (in px)",
          value = DFLT_scrolling_y_limit)
    )
  ),
  hr(),
  uiOutput("ui_input"),
  hr(),
  h3("Database"),
  DT::dataTableOutput("dt")
)

Server
server <- function(input, output, session) {
  ## Initialize DB //
  db <- reactiveValues(data = data.frame(
    task = character(),
    time = numeric(),
    time_unit = character()
  )[-1,])

  ## UI control //
  ui_control <- reactiveValues(
    case = c("hide", "create", "update")[1],
    selection = NULL,
    refresh = TRUE
  )
  observeEvent(input$action_trigger, {
    ui_control$case <- "create"
  })

  ## Render UI //
  output$ui_input <- renderUI({
    case <- ui_control$case
    if (case == "hide")
      return()

    ## Case dependent input //
    if (case == "create") {
      task <- ifelse(is.null(tmp <- isolate(input$task)), "", tmp)
      time <- ifelse(is.null(tmp <- isolate(input$time)), "", tmp)

      buttons <- div(
        style = "display:inline-block",
        actionButton("action_create", "Create"),
        actionButton("action_cancel", "Cancel")
      )
      updateTextInput(session, "first")
    } else if (case == "update") {
      task <- db$data[ui_control$selection, "task"]
      time <- db$data[ui_control$selection, "time"]
      buttons <- div(
        style = "display:inline-block",
        actionButton("action_update", "Update"),
        actionButton("action_cancel", "Cancel"),
        p(),
        actionButton(
          "action_delete",
          "Delete",
          icon = icon("exclamation-triangle")
        )
      )
    } else {
      stop(sprintf("Invalid case: %s", case))
    }

    tagList(
      textInput("task", "Task", task),
      numericInput("time", "Time", time),
      buttons
    )
  })

  ## CRUD operations //
  observeEvent(input$action_create, {
    createRecord(input, db = db)
    ui_control$case <- "hide"
  })
  observeEvent(input$action_update, {
    updateRecord(input, db = db, selection = ui_control$selection)
    ui_control$refresh <- NULL
    ui_control$refresh <- TRUE
    # ui_control$case <- "hide"
  })
  observeEvent(input$action_delete, {
    deleteRecord(db = db, selection = ui_control$selection)
    tmp <- ui_control$selection[1] - 1
    if (tmp == 0) tmp <- NULL
    ui_control$selection <- tmp
    ui_control$refresh <- NULL
    ui_control$refresh <- TRUE
    # ui_control$case <- "hide"
  })
  observeEvent(input$action_cancel, {
    ui_control$case <- "hide"
  })

  ## Selection //
  observe({
    idx <- input$dt_rows_selected
    ui_control$selection <- idx
  })
  observe({
    idx <- ui_control$selection
    if (!is.null(idx)) {
      ui_control$case <- "update"
    } else {
      ui_control$case <- "hide"
    }
  })

  ## Render table: preparations //
  observeEvent(input$action_enable_scrolling, {
    ui_control$refresh <- NULL
    ui_control$refresh <- TRUE
  })
  observeEvent(input$scrolling_y_limit, {
    ui_control$refresh <- NULL
    ui_control$refresh <- TRUE
  })
  dt_options = reactive({
    scroll <- input$action_enable_scrolling
    list(
      dom = "ltipr",
      autoWidth = TRUE,
      scrollX = TRUE,
      scrollY = if (scroll) {
        sprintf("%spx", input$scrolling_y_limit * 1)
      },
      scrollCollapse = if (scroll) {
        TRUE
      },
      lengthMenu = list(
        c(3, 5, -1),
        c(3, 5, "All")
      ),
      iDisplayLength = 3
    )
  })

  # Render table: DT //
  output$dt <- DT::renderDataTable({
    if (!ui_control$refresh) {
      return()
    }
    ## Note:
    ## Not really necessary for this example use case as `db$data` already
    ## introduces a reactive dependency.
    ## However, that might not always be the case for data I/O when an
    ## actual database is involved. In this case, this part will most likely
    ## have to be informed about required re-rendering by an explicit reactive
    ## value that other parts update upon I/O operations

    tmp <- db$data
    names(tmp) <- sapply(names(tmp), niceNames)
    tmp
  }, selection = "single", options = dt_options())

  # DT proxy //
  proxy <- DT::dataTableProxy("dt")

  ## Keep/restory previous selection //
  observe({
    ui_control$refresh
    DT::selectRows(proxy, as.numeric(ui_control$selection))
  })

  ## Resets //
  observe({
    if (ui_control$case == "create") {
      updateTextInput(session, "task", value = sprintf("Test %s", Sys.time()))
      updateTextInput(session, "time", value = 1)
    }
  })
}

Run
shinyApp(ui, server)

Reference app on Gist
The sections used above are also contained in my reference app which bundles some stuff/learnings that's related to datable functionality in case you're interested:
shiny::runGist("https://gist.github.com/rappster/d48916fbf8e8d0456ae2")


text:
Q: js button click not detected I have created a div that when clicked, a messi box pop up, with button "Yes" and "NO".:
 var Abutton = document.createElement("div");
                Abutton.className = "Abutton";
                Abutton.onclick = function () {
                    new Messi(
                        'Are you sure you want to close your job?',
                        {
                            title: 'Are you sure?',
                            buttons: [
                                {id: 0, label: 'Yes', val:'Y' , class: 'deleteJob'},
                                {id: 1, label: 'No', val: 'N', class: 'cancelAction'}

                            ]
                        }
                    );
                };
                Abutton.title = "Closed?";
                Abutton.appendChild(document.createTextNode("Close Job"));
                li.appendChild(Abutton);

The "yes " button is tied to this function below . But when I click, nothing happens. The log statement is also not shown.
  $(".deleteJob").click(function(){
           deleteJob();
           console.log("heelo");
    });

Why is it not working?

A: Not sure based on just this code but the deleteJob button is being added dynamically and probably doesn't exist at the time you are adding the click event.  You should probably use event delegation on the parent element instead.  Based on your code this is the li element.  If it is part of a <ul> maybe put the click event on it like so:
$(function(){
  $('ul').on('click','.deleteJob', function(){
    deleteJob();
    console.log('hello');
  });
});

Again, not 100% sure without seeing the rest of the code.  But either way, Event Delegation is the way to go.


text:
Q: Redirecting uppercase urls to lowercase urls using htaccess. I have tried below code, its redirecting but effecting my css and js files. So I want to ignore all the folders. How it can be done? I tried using RewriteCond %{REQUEST_FILENAME} !-d but doesn't work.
RewriteEngine On
RewriteBase /
# If there are caps, set HASCAPS to true and skip next rule
RewriteRule [A-Z] - [E=HASCAPS:TRUE,S=1]
# Skip this entire section if no uppercase letters in requested URL
RewriteRule ![A-Z] - [S=28]
# Replace single occurance of CAP with cap, then process next Rule.
RewriteRule ^([^A]*)A(.*)$ $1a$2
RewriteRule ^([^B]*)B(.*)$ $1b$2
RewriteRule ^([^C]*)C(.*)$ $1c$2
RewriteRule ^([^D]*)D(.*)$ $1d$2
RewriteRule ^([^E]*)E(.*)$ $1e$2
RewriteRule ^([^F]*)F(.*)$ $1f$2
RewriteRule ^([^G]*)G(.*)$ $1g$2
RewriteRule ^([^H]*)H(.*)$ $1h$2
RewriteRule ^([^I]*)I(.*)$ $1i$2
RewriteRule ^([^J]*)J(.*)$ $1j$2
RewriteRule ^([^K]*)K(.*)$ $1k$2
RewriteRule ^([^L]*)L(.*)$ $1l$2
RewriteRule ^([^M]*)M(.*)$ $1m$2
RewriteRule ^([^N]*)N(.*)$ $1n$2
RewriteRule ^([^O]*)O(.*)$ $1o$2
RewriteRule ^([^P]*)P(.*)$ $1p$2
RewriteRule ^([^Q]*)Q(.*)$ $1q$2
RewriteRule ^([^R]*)R(.*)$ $1r$2
RewriteRule ^([^S]*)S(.*)$ $1s$2
RewriteRule ^([^T]*)T(.*)$ $1t$2
RewriteRule ^([^U]*)U(.*)$ $1u$2
RewriteRule ^([^V]*)V(.*)$ $1v$2
RewriteRule ^([^W]*)W(.*)$ $1w$2
RewriteRule ^([^X]*)X(.*)$ $1x$2
RewriteRule ^([^Y]*)Y(.*)$ $1y$2
RewriteRule ^([^Z]*)Z(.*)$ $1z$2
# If there are any uppercase letters, restart at very first RewriteRule in file.
RewriteRule [A-Z] - [N]
RewriteCond %{ENV:HASCAPS} TRUE
RewriteRule ^/?(.*) /$1 [R=301,L]


text:
Q: series in series Let $\sum_{n=1}^\infty a_n<\infty$ be a complex convergent series
is the series $\sum_{n=1}^\infty (a_n \cdot \sum_{m=n+1}^\infty a_m)$ calculable ?
thanks for any suggestion

A: This is not convergent in general.

*

*If your series is absolutely convergent, then indeed your new series will be absolutely convergent as well, by comparison (this is straightforward).

*Otherwise, it may not be. Consider for instance the alternating series given by the general term $a_n \stackrel{\rm def}{=} \frac{(-1)^n}{\sqrt{n}}$ for $n\geq 1$. We have that $\sum_{n=1}^\infty a_n$ converges, but
$$
\sum_{k=n+1}^\infty a_k = \frac{(-1)^{n+1}}{2\sqrt{n}} + o\left(\frac{1}{\sqrt{n}}\right)
$$
(if I am not mistaken); from which you get
$$
\sum_{n=1}^\infty \sum_{k=n+1}^\infty a_n a_k =
-\frac{1}{2} \sum_{n=1}^\infty \frac{1}{n} \xrightarrow[n\to\infty]{} -\infty
$$
by comparison.

A: Assuming that both the following series are convergent
$$ \sum_{n\geq 1}a_n,\qquad \sum_{n\geq 1}a_n^2 $$
we have the following symmetry trick:
$$ \sum_{n\geq 1}a_n\sum_{m>n}a_m = \sum_{1\leq n < m}a_n a_m = \sum_{1\leq m < n}a_n a_m = \frac{1}{2}\left[\left(\sum_{n\geq 1}a_n\right)^2-\sum_{n\geq 1}a_n^2\right]. $$


text:
Q: Persistance XSS attack during OutputStream.write() I have been working over the security issue regarding the persistent-XSS attack and i was able to analyze the issue using fortify.
sends unvalidated data to a web browser , which can result in the browser executing malicious code.
Code is in Java.
void output(OutputStream out){
  out.write(byteData);  //byteData is a data member of the class of type byte[].
}

At line (2) in above snippet i am getting the notification of xss attack.
So how can i validate it?

A: You have to validate your data before sending it to your OutputStream
void output(OutputStream out) {
    // Validate byteData code here
    out.write(byteData);
}

Validation means checking if the code abides by the rules that you want to set for it. For example, if you want to send only numbers, you can make sure that your byteData contains only numbers before sending it.


text:
Q: Error in PL SQL set serveroutput on;
set define off;
exec dbms_output.enable(20000);
set pagesize 2000;

declare
Test_Date1 Date;
test_date2 DATE;
Day_Of_Week Varchar2(3);
Years_Ahead Number := 0;
New_Var Number := 0;
New_Var1 Number := 0;
New_Var2 Number := 0;
Dd1 Number := 0;
Dd2 Number := 0;
Mm1 Number := 0;
mm2 Number := 0;

Begin
    test_date1 := TO_DATE('01/12/2017 00:00:00','DD/MM/YYYY HH24:MI:SS');
    test_date2 := To_Date('01/12/2017 08:00:00','DD/MM/YYYY HH24:MI:SS');
    dd1 :=(test_date1,'dd');
    dd2 :=(test_date2,'dd');
    mm1 :=(test_date1,'mm');
    mm2 :=(Test_Date2,'mm');
    For Years_Ahead In Dd1..Dd2 Loop
            Select Count(User_Id) Into New_Var From Lg_Usage_Statistics Where Timestamp Between Test_Date1 And Test_Date1;
            Select Count(User_Id) Into New_Var1 From Lg_Usage_Statistics Where Timestamp Between To_Date('01/12/2017 00:00:00','DD/MM/YYYY HH24:MI:SS') And To_Date('02/12/2017 23:59:00','DD/MM/YYYY HH24:MI:SS');
            Select COUNT(User_Id) into New_Var2 From Lg_Usage_Statistics Where Timestamp Between To_Date('01/12/2017 00:00:00','DD/MM/YYYY HH24:MI:SS') And To_Date('02/12/2017 23:59:00','DD/MM/YYYY HH24:MI:SS');
End Loop;
END;
/

I am trying to get the count of users into variable but getting these errors
Error:
Error starting at line 6 in command:
declare
Test_Date1 Date;
test_date2 DATE;
Day_Of_Week Varchar2(3);
Years_Ahead Number := 0;
New_Var Number := 0;
New_Var1 Number := 0;
New_Var2 Number := 0;
Dd1 Number := 0;
Dd2 Number := 0;
Mm1 Number := 0;
mm2 Number := 0;

Begin
    test_date1 := TO_DATE('01/12/2017 00:00:00','DD/MM/YYYY HH24:MI:SS');
    test_date2 := To_Date('01/12/2017 08:00:00','DD/MM/YYYY HH24:MI:SS');
    dd1 :=(test_date1,'dd');
    dd2 :=(test_date2,'dd');
    mm1 :=(test_date1,'mm');
    mm2 :=(Test_Date2,'mm');
    For Years_Ahead In Dd1..Dd2 Loop
        Select Count(User_Id) Into New_Var From Lg_Usage_Statistics Where Timestamp Between Test_Date1 And Test_Date1;
        Select Count(User_Id) Into New_Var1 From Lg_Usage_Statistics Where Timestamp Between To_Date('01/12/2017 00:00:00','DD/MM/YYYY HH24:MI:SS') And To_Date('02/12/2017 23:59:00','DD/MM/YYYY HH24:MI:SS');
        Select COUNT(User_Id) into New_Var2 From Lg_Usage_Statistics Where Timestamp Between To_Date('01/12/2017 00:00:00','DD/MM/YYYY HH24:MI:SS') And To_Date('02/12/2017 23:59:00','DD/MM/YYYY HH24:MI:SS');
    End Loop;
END;
Error report:
ORA-06550: line 17, column 8:
PLS-00382: expression is of wrong type
ORA-06550: line 17, column 2:
PL/SQL: Statement ignored
ORA-06550: line 18, column 8:
PLS-00382: expression is of wrong type
ORA-06550: line 18, column 2:
PL/SQL: Statement ignored
ORA-06550: line 19, column 8:
PLS-00382: expression is of wrong type
ORA-06550: line 19, column 2:
PL/SQL: Statement ignored
ORA-06550: line 20, column 8:
PLS-00382: expression is of wrong type
ORA-06550: line 20, column 2:
PL/SQL: Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

A:  dd1 :=(test_date1,'dd');
 dd2 :=(test_date2,'dd');
 mm1 :=(test_date1,'mm');
 mm2 :=(Test_Date2,'mm');

What do you want to accomplish here? This isn't valid plsql.
I'm guessing you want to use one of following functions:
TO_CHAR(test_date1, 'dd');
TRUNC(test_date1, 'dd');

A: The problem stems from non-sense assignments like dd1 :=(test_date1,'dd') and so on .. to numeric variables at lines 17 through 20.
the variables dd1, dd2, mm1 and mm2 are defined as number, so you may apply first to_char, and then to_number conversion to get the valid values for these variables.
dd1 :=to_number(to_char(test_date1,'dd'));
dd2 :=to_number(to_char(test_date2,'dd'));
mm1 :=to_number(to_char(test_date1,'mm'));
mm2 :=to_number(to_char(Test_Date2,'mm'));


text:
Q: How to get keycodes for xmodmap? I'm trying to use xmodmap to remap Alt / Super keys on Dell L100 keyboard, and have trouble getting the keycodes.
For instance, using xev doesn't give me keycode for Alt
FocusOut event, serial 36, synthetic NO, window 0x4a00001,
    mode NotifyGrab, detail NotifyAncestor

FocusIn event, serial 36, synthetic NO, window 0x4a00001,
    mode NotifyUngrab, detail NotifyAncestor

KeymapNotify event, serial 36, synthetic NO, window 0x0,
    keys:  122 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
           0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

For Right Super key, xev and showkey give different keycodes -- 134 and 126 respectively.
What's going on with these keycodes?
I tried getting keycodes from showkey -k, and using xmodmap file below, but that gave a weird map which remapped b key:
clear Mod1
clear Control
keycode 125 = Meta_L
keycode 126 = Meta_R
keycode 58 = Control_L
keycode 56 = Control_L
keycode 100 = Control_R
add Control = Control_L Control_R
add Mod1 = Meta_L Meta_R

A: There are a lot of players between your keyboard and the process that finally handles the keyboard event. Among the major pieces of the landscape are the fact that the X system has its own keyboard-handling layer, and X associates different "keycodes" with keys than your Linux base system does. The showkey command is showing you the keycodes in Linux-base-system lingo. For xmodmap you need the X keycodes, which are what xev is displaying. So long as you're planning to work in X and do your key rebinding with xmodmap, then, ignore showkeys and just listen to what xev says.
What you want to look for in your xev output are blocks like this:

KeyPress event, serial 27, synthetic NO, window 0x1200001,
    root 0x101, subw 0x0, time 6417361, (340,373), root:(342,393),
    state 0x0, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 27, synthetic NO, window 0x1200001,
    root 0x101, subw 0x0, time 6417474, (340,373), root:(342,393),
    state 0x8, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

xev tends to generate a lot of output, especially when you move your mouse. You may have to scroll back a while to find the output you're looking for. In the previous output, we see that the keysym Alt_L is associated with the X keycode 64.

A: I had the same problem with Alt_L disappearing in XUbuntu 14.04 (Alt_R was fine).  After a lot of playing, I observed that showkey recorded the keystroke, but xev didn't --- it had to be something in the window system.  I scoured all the "Window Manager" and "Window Manager Tweaks" settings, and didn't find anything.  Finally, I found a stray Alt_L in the list of keyboard shortcuts (xfce4-keyboard-shortcuts) in the "Settings Editor".  I "reset" that, and I have my Alt_L back!  The stray Alt_L shortcut didn't show up anywhere else except in the "Settings Editor".

A: xev should work
Odd, my xev gives a KeyPress and KeyRelease event for alt (and for the Windows key, here called "super"):
KeyPress event, serial 40, synthetic NO, window 0xae00001,
    root 0x2ca, subw 0x0, time 595467354, (98,77), root:(102,443),
    state 0x10, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 40, synthetic NO, window 0xae00001,
    root 0x2ca, subw 0x0, time 595467453, (98,77), root:(102,443),
    state 0x18, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

And the right-hand one:
KeyPress event, serial 40, synthetic NO, window 0xae00001,
    root 0x2ca, subw 0x0, time 595572876, (75,33), root:(79,399),
    state 0x10, keycode 108 (keysym 0xffea, Alt_R), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 40, synthetic NO, window 0xae00001,
    root 0x2ca, subw 0x0, time 595572972, (75,33), root:(79,399),
    state 0x18, keycode 108 (keysym 0xffea, Alt_R), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

I can see two possibilities:

*

*Something else is completely eating the keypress, or defocusing the window upon you pressing alt. Try running xev in an otherwise empty X server (e.g., just run xinit -- :1, which should get you a X server with only an xterm—there won't even be a window manager running. Exiting the xterm will close the session).

*You just missed the two events in the bulk that xev spews out.

An easy way, if you know the key name
Another possibility: just get the keycodes from xmodmap:
anthony@Zia:~$ xmodmap -pk | grep -i alt
     64         0xffe9 (Alt_L)  0xffe7 (Meta_L) 0xffe9 (Alt_L)  0xffe7 (Meta_L)
    108         0xffea (Alt_R)  0xffe8 (Meta_R) 0xffea (Alt_R)  0xffe8 (Meta_R)
    204         0x0000 (NoSymbol)       0xffe9 (Alt_L)  0x0000 (NoSymbol)       0xffe9 (Alt_L)
anthony@Zia:~$ xmodmap -pk | grep -i super
    133         0xffeb (Super_L)        0x0000 (NoSymbol)       0xffeb (Super_L)
    134         0xffec (Super_R)        0x0000 (NoSymbol)       0xffec (Super_R)
    206         0x0000 (NoSymbol)       0xffeb (Super_L)        0x0000 (NoSymbol)       0xffeb (Super_L)

There is the 64 and 108 again. xmodmap -pm will show you just the modifier map, which also gives you the numbers (though, this time, in hex).

A: I "detect" three issues in your question:

*

*Why do xev and showkey report different keycodes for a key?

*Why does xev not show Alt being pressed properly?

*How to swap Alt and Win?
Regarding the first question: these days, where the keyboard "driver" in X does not really drive the hardware, it could just pass-through the keycodes from the kernel to the X core, but it doesn't. It adds 8 to the keycode before passing it on.
Second: Something in your X session is grabbing the Alt event. The other answers cover this already. (I.e. xev doesn't get the event you would like to see). The culprit might be related to your window manager. Try a more naked X session.
Third: Don't use xmodmap. It has been outdated for a decade. The new guys are XKB and its tool setxkbmap.
$ setxkbmap -query
rules:      evdev
model:      pc105
layout:     us
variant:    altgr-intl
options:    caps:backspace

For swapping Alt and Win there is already an option prepared in XKB. Just add it:
$ setxkbmap -option altwin:swap_alt_win
$ setxkbmap -query
rules:      evdev
model:      pc105
layout:     us
variant:    altgr-intl
options:    altwin:swap_alt_win,caps:backspace

A: As root, run:
showkey -s

...to see what the scancode is for your mystery key. I got something like this:
# showkey -s
kb mode was RAW
[ if you are trying this under X, it might not work
since the X server is also reading /dev/console ]

press any key (program terminates 10s after last keypress)...

0xc6
0x46 0xc6
0xc6
0x46 0xc6
0x46

Not sure why it appears that one key generates two scancodes.  It's not a keydown/keyup thing, as near as I could tell from the pattern.  Note the warning, so you may want to run this in single user mode.
I guessed that 0x46 was my scancode.
Next, find an unused keycode with:
xmodmap -pke | less

Here you can see keycode 97 is unused on my system:
keycode  94 = less greater less greater bar brokenbar
keycode  95 = F11 XF86Switch_VT_11 F11 XF86Switch_VT_11
keycode  96 = F12 XF86Switch_VT_12 F12 XF86Switch_VT_12
keycode  97 =
keycode  98 = Katakana NoSymbol Katakana
keycode  99 = Hiragana NoSymbol Hiragana

The keycode X uses and the keycode the kernel uses are OFF BY 8 for "historical reasons".  So take 97 - 8 = 89 and use 89 with the setkeycodes command (again as root):
# setkeycodes 46 89

And you should be set.  Confirm with xev that you're getting a Keypress Event with the keycode of 97.  (though once I told the Fluxbox keys file to use that keycode I didn't get KeyPress events anymore - maybe because Fluxbox swallows them when it uses them?)
Note that the 'setkeycodes' won't survive a reboot, so you'll have to add it to your init scripts (eg. in /etc/rc.local)

A: I was trying to solve this for myself and I just figured it out.
The main problem is that you aren't getting the event for the keypress.  Looking at the log you posted the reason is apparent.
FocusOut event, serial 36, synthetic NO, window 0x4a00001,
    mode NotifyGrab, detail NotifyAncestor

FocusIn event, serial 36, synthetic NO, window 0x4a00001,
    mode NotifyUngrab, detail NotifyAncestor

KeymapNotify event, serial 36, synthetic NO, window 0x0,
    keys:  122 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
           0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

You can see the the Focus{In,Out} events have a mode of Notify{Grab,Ungrab}.  This indicates that a key was handled by another process (probably a shortcut/keybinding application).
In my case it was xbindkeys, but if you are using a desktop environment they probably have a keybinding system.  In order to see these events is xev you will need to stop/disable the other program.
If you can't determine what program is stealing the key events the best solution is to start another X session without it running.  Run the following command to start another X session on display :1, if that is already taken just increase the number at the end.  You can of course change the terminal to whatever you prefer or have installed on your system.
xinit /usr/bin/xterm -- :1

Then run xev again.  That should give you the result without it being captured by other programs.  Note that the window manager that gets started is hover-focus, so you will have to place your cursor above the xev window in order for the keys to be captured.

As was said in this excellent answer by dubiousjim, the keycode is different because there are a lot of layers between xev and the kernel.


text:
Q: Rails 3 , Jquery.load with no layout My Ajax call is almost working, but i can't figure why my layout is still rendered?  here is the context:
I have a contact page on my site that use the linkedIn API.  I want to load the LinkedIn info from an ajax call when my page is loaded.  This work fine.
But the result of my .load() is rendered with the layout of my site.  I only want to render the html in my ajax_contact.html.erb..
contact.js
 $(document).ready(function() {

   $(".info_perso").load( '/contact/ajax_contact', {name:"benoit"}, function(data){  $(".info_perso").html( data );})

 });

ajax_contact.html.erb:
<%if !@profile.nil?%>

                <%=image_tag(@profile.picture_url)%>

                <%=@profile.first_name %> <%=@profile.last_name %>

                <%=@profile.headline%>

                <%=@profile.industry%>

                <%=@profile.summary%>

                Education

                <% @profile.educations.all.each {|edu| %>

                    Degre : <%=edu.degree%>

                    Années : <%=edu.start_date.year%> - <%=edu.end_date.year%>

                    Concentration : <%=edu.field_of_study%>

                    Universite : <%=edu.school_name%>

                <%}%>
                Experience

                <% @profile.positions.all.each {|pos| %>
                     Company: <%=pos.company.name%>

                    Titre : <%=pos.title%>

                    Années : <%=pos.start_date.month%>/<%=pos.start_date.year%> - <%=  pos.end_date? ? pos.end_date.month.to_s + "/" + pos.end_date.year.to_s : "now"%>

                    Description : <%=pos.summary%>

                <%}%>

            <%else%>
                <%=link_to "Activer linkedIn", :controller=>"linkedinAuth", :action=>"benoit", :name=>"benoit", :callback=>"/linkedinauth/callbackbenoit"%>
            <%end%>

contact_controller.rb:
  def ajax_contact
name = params[:name]
linkedinInfo = LinkedinApiInfo.find(1)
linkedinCred = LinkedinCredential.find_by_name(name)
if !linkedinCred.nil?
  client = LinkedIn::Client.new(linkedinInfo.apiKey, linkedinInfo.secretKey)
  client.authorize_from_access(linkedinCred.acctoken, linkedinCred.accsecret)
  # Pick some fields
  fields = ['first-name', 'last-name', 'headline', 'industry', 'num-connections','educations', 'num-recommenders','recommendations-received', 'summary', 'positions','picture-url']

  @profile = client.profile :fields => fields
  @profile.recommendations_received.all.each {|rec| puts rec.recommendation_text}

  puts @profile

end
 rescue SocketError
  puts "Unable to connect"

  render "ajax_content", :content_type=>"text/html", :layout=>false

   end

Even with the :layout=>false, my layout is still showned!!!  anyone can see the problem?

A: add
render 'ajax_contact', :layout=>false
to your action, at the end, also partial views name should start with _, so your view should be named '_ajax_contact'


text:
Q: time complexity of some specific system of $(n-3)/2$ linear equations with $(n-3)/2$ unknowns. let take n a odd integer greater than 3
if I have to solve this system of $(n-3)/2$ linear equations with $(n-3)/2$  unknowns to find some propriety about the number n,
here is formula for every equations in the system:
$(m^{2m-1}+m^0)x_1 + ... + (m^{2m-i}+m^{i-1})x_i + ... + (m^{2m-(n-3)/2}+m^{((n-3)/2)-1})x_{(n-3)/2}=\frac{(m+1)^n-m^n-nm^{n-1}-nm-1}{m^2}$
(the first equation is when m=1,the second when m=2 and so on until m=$\frac{n-3}{2}$)
the system will look something like this for a given n:
\begin{cases} x_1 + x_2 + ... + x_{(n-3)/2} = 2^{n-1}-n-1\\ .\\.\\.\\(m^{2m-1}+m^0)x_1 + (m^{2m-2}+m^1)x_2 + ... + (m^{2m-i}+m^{i-1})x_i + ... + (m^{2m-(n-3)/2}+m^{((n-3)/2)-1})x_{(n-3)/2}=\frac{(m+1)^n-m^n-nm^{n-1}-nm-1}{m^2}\\.\\.\\.\\(\frac{n-3}{2}^{(2\frac{n-3}{2}-1)}+\frac{n-3}{2}^0)x_1 + (\frac{n-3}{2}^{(2\frac{n-3}{2}-2)}+\frac{n-3}{2}^1)x_2 + ... + (\frac{n-3}{2}^{(2\frac{n-3}{2}-i)}+\frac{n-3}{2}^{(i-1)})x_i + ... + (\frac{n-3}{2}^{(2\frac{n-3}{2}-\frac{n-3}{2})}+\frac{n-3}{2}^{(\frac{n-3}{2}-1)})x_{(n-3)/2}=\frac{(\frac{n-3}{2}+1)^n-\frac{n-3}{2}^n-n\frac{n-3}{2}^{n-1}-n\frac{n-3}{2}-1}{\frac{n-3}{2}^2}\end{cases}
Here is my main question:
What is the time complexity of this algorithm and what way can be use to find it?
Thank you very mutch.


text:
Q: Entropy - can we express number of microstates as a function parameterized by degrees of freedom? In some of the answers and comments from this question people contended (not in so many words) that because entropy is parameterized by number of microstates $\Omega$, and the definition of $\Omega$ is up to the person doing the calculation, entropy is subjective. Such an argument might go thus:
"Consider a box containing $n$ particles. Suppose the particles do not interact and can be crammed as many as you like into as little space as you like. Subdivide the box into $m$ smaller boxes of equal dimensions. Then the number of box-contents microstates is $Ω=m^n$. $n$ is an observable, but whoever choses $m$ chooses $Ω$, and $S=k_blog(Ω)$, therefore whoever subdivides the box sets the entropy."
It seems to me that $\Omega$ (and hence $S$) isn't subjective, it's simply parameterized by degrees of freedom per particle. I couldn't suggest a formula, but as far as I can tell the relationship is such that if you use all the degrees of freedom each particle can have, you get $d S = 0$ and $S = 0$, and if you use only some of the degrees of freedom, you get $dS \ge \delta Q / T$ and $S = k_b log(\Omega)$ as normal.
(Of course if you introduce quantum mechanics you can't actually fully specify all the states of each particle, because you can't express a state in which the particle's momentum and position are both known to arbitrary precision, but I think that's not directly relevant to my question.)
It also seems to me that most if not all observables have a "degree of freedom" parameterization, so entropy is not a special case, it's just that most quantities' degree of freedom parameterization is obvious and implicit, whereas entropy's emerges from difficult math.
Consider quantities velocity and length and the parameter mass. If we give the rocket in free space a mass degree of freedom, the rocket accelerates and stays the same length. If we don't give the rocket a mass degree of freedom, the rocket stays at one velocity and gets longer (the expelled fuel still counts as part of the rocket). Length and velocity are hardly subjective, and yet they're parameterized by the mass degree of freedom of the rocket.
Is this right? If so, is there a mathematical expression for the parameterization of $\Omega$ as a function of particle degrees of freedom?

An addition:
Going back to our box of n particles: we can make reference to spatial degrees of freedom from this by starting by subdividing parallel to the xy plane, then further subdividing along the xz plane, and along the yz plane. If we make equal subidivisions for each dimension, we multiply m by the number of dimensions.
We can add additional complexity by gradating other variables than position (for instance, momentum) and asking what the average in each subdivision is closest to.
So perhaps our $\Omega$ might be something like,
$\Omega = f(n, m_1, ...m_i, D_1, ...., D_i) = (D_1m_1)^n \times (D_2m_2)^n\times ...\times (D_im_i)^n$
where $m_i$ is the number of subdivisions per dimension per observable and $D_i$ is the number of corresponding dimensions. This would seem to contradict my intuition that $S=0$ if you perfectly specify every possible parameter, since $S$ would trend in the opposite direction as you add parameters and precision.

Another addition:
Wikipedia suggests going around the question by applying H theorem or (if I understand correctly) by using quantum eigenstates as your "boxes" and then applying the thermodynamical limit to reduce first to a countable infinity and then to a finite number of maximum microstates, to the limits of the system's uncertainty. This probably is directly relevant since (I think) it implies that an appropriately chosen variable captures all the existent information, allowing the problem to be reduced to counting the number of microstates of that single variable. Is that a correct inference?


text:
Q: Home directory navigation in bash script I need a simple bash script function for .bashrc file to navigate to my home directory.
We use hg for all our work purpose in the directory and contains many streams.
/home/<username>/RelStream1/
/home/<username>/RelStream2/
/home/<username>/RelStream3/
/home/<username>/RelStream4/

For namesake i call this /home//RelStream1/ path as repo home.
Now for work purpose, i need to navigate to sub folders from my repo home path.
/home/<username>/RelStream1/pkgdir/appsdir/moduledir/submoduledir/....
After finishing work, i need to come back to home repo directory for compilation.
I have added alias like this, but still its painful to remember the path back.
    alias ..="cd .."
    alias ..2="cd ../.."
    alias ..3="cd ../../.."
    alias ..4="cd ../../../.."
    alias ..5="cd ../../../../.."

Please note many repo home directories would be used at any point of time and hence setting aliases as alias rhome='cd /home/<username>/RelStreamX/' will have little use.
I just need a simple bash function to get back to repo home directory (current repo).
It has to get the current path and navigate my directory back to home repo directory
    Ex1:
    From: /home/<username>/RelStream1/pkgdir/appsdir/moduledir/submoduledir/
    To: /home/<username>/RelStream1/

    Ex2:
    From: /home/<username>/RelStream3/pkgdir/appsdir/moduledir/submoduledir/micromodule/
    To: /home/<username>/RelStream3/

    Ex3:
    From: /home/<username>/RelStream4/pkgdir/appsdir/
    To: /home/<username>/RelStream4/

I have tried some methods in bash(beginner), but does not give expected results.
code:
    repohome_func()
    {
    cwd=$(pwd)
    echo "CurrPath:${cwd}"
    sep="/"

    //My plan is to search the cur path with "/" char up to 4 times,
    //cut the front string and then execute that cmd.

    }alias rhome=repohome_func

A: This should work for you:
function repohome() {
    local repodir=${PWD/$HOME\/}
    cd "$HOME/${repodir%%/*}"
}

A: This should make:
alias rhome="cd $(pwd | sed 's~/[^/]*~~4g')"

It gets the current path with pwd and replaces it to what is needed. As this is within $() then we cd there.
You need to remove all current path but the first three blocks. With this sed, we do that.
See an example with a file:
$ cat a
/home/myuser/myrepo1/asld/as/asdf/asdf/asdf
/home/myuser/myrepo2/asdf
/home/myuser/myrepo3/asld/as/asdf/f/asdf
/home/myuser/myrepo4/asld/as/asdf/
$ sed 's~/[^/]*~~4g' a
/home/myuser/myrepo1
/home/myuser/myrepo2
/home/myuser/myrepo3
/home/myuser/myrepo4

From what was commented below, it seems like that the solution was not working as an alias, but it does as a function. The hypothesis is that there must be some alias in either cd, pwd or sed that makes them work differently.
As aliases are bypassed by functions, using it that way mades it. Otherwise, it could also work by using \ before any command, so the command alias gets bypassed as well.
alias rhome="\cd $(\pwd | \sed 's~/[^/]*~~4g')"

More info:

*

*Temporarily disabling an alias / quoting a word with a backslash

*\curl … | bash … what's the slash for?.

A: If you add your home directory to the front of CDPATH, for example,
CDPATH=/home/<username>:.

then any relative path used with cd will be looked up first in your home directory before the current working directory. Then
cd Relstream1

will take you to /home/<username>/Relstream1 before ./Relstream1.

A: You might want to try the builtin commands pushd and popd. If you use pushd <dir> instead of cd <dir>, you can then use popd to return to the previous working directory.


text:
Q: How to obtain user input in Python? I would like to learn how to code this.
Here is how I want it to look
Do you want strawberry ice cream? (y:n) n
Do you want chocolate ice cream?  (y:n) y
Do you want mint ice cream? (y:n) n
Do you want vanilla ice cream? (y:n) y

then the output would be: Here is your ice cream. or if you put N to all, You did not say yes to any.
Or with the else statement: I didn't get that, try again.
Any help is very much appreciated, thank you.
My test script:
def kind(chosenIce):
      chosenIce=input("Do you want a ice cream (y:n) ")
      if chosenIce1 == 'y':
          ice1 = print("message")
      if chosenIce2 == 'y':
          ice2 = print("message")
      if chosenIce1 == 'n':
          ice1 = 0
      if chosenIce2 == 'n':
          ice2 = 0
      else:
         print("Sorry, I did not get that. Try again.")
kind(chosenIce)

A: Regarding only what you want in this problem, you will use the function input. The way to use it is this:
strawberryIceCream=input('Do you want strawberry ice cream? (y/n)')

and so on, so forth with the other options as well. Remember to store each option in either a different variable or, better IMHO, in a set or tuple.
Further info on input
However, the comments' on your question are accurate and on point. This is why I mentioned that this answer will answer only your question. Nothing more, nothing less.

A: As some fellows said, you have to use input and loop (i.e for loop or while loop) to achieve your goal. By reading your post and the comments, it seems you are really a newbie in Python. So, below, I give you a basic workflow that does something like your needs. There are many ways to achieve your goals. You can look at my workflow for inspiration.
Here is the code:
def kind(ices_cream):
    choices = []
    for ice in ices_cream:
        chosenIce = input('Do you want "{}" ice cream (y:n) '.format(ice))
        if chosenIce == 'y':
            choices.append(ice)
        elif chosenIce == 'n':
            print("You refuse ", ice)
        else:
            print("Sorry, I did not get that. Try again.")

    if len(choices):
        print("\n", "You buy", ' and '.join(choices))
    else:
        print("\n", "You buy nothing!")

if __name__ == "__main__":
    ices_cream = ["Chocolate", "Strawberry", "Mint", "Vanilla"]
    kind(ices_cream)

Outputs: It is an example

Do you want "Chocolate" ice cream (y:n) y
Do you want "Strawberry" ice cream (y:n) n
You refuse  Strawberry
Do you want "Mint" ice cream (y:n) y
Do you want "Vanilla" ice cream (y:n) n
You refuse  Vanilla

 You buy Chocolate and Mint

NB: You can add a loop while to force the user to input the characters y or n. Also, you can add exception handling if you want to do a good job.

A: listQue=["Do you want strawberry ice cream?","Do you want chocolate ice cream?","Do
you want mint ice cream?","Do you want vanilla ice cream?"]

flag=False
for que in listQue:
    ans=input(que)
    if(ans=='Y'):
        res=que.split()
        print("Here is your"," ".join(res[3:6]).rstrip('?'))
        flag=True
   else:
        pass

if(flag==False):
    print("Ohhh sorry you didn't choose anything")

A: In python 3 you can use input() (examples here) and in python 2 raw_input() (examples here). You need to code the rest yourself using for-loops... etc.
Example:
choices = []

x1 = input('Do you want strawberry ice cream? (y/n)')

choices.append(x1)  # store the choice for each question here so you can use it later for
                # selection criteria process. Store x2 at choices[1], etc.

for choice in choices:
    if choice in ['y', 'Y', 'yes', YES']:
        print ('User does like an iscream')
    else:
        print ('User no fan of the cold treat')


text:
Q: Error TS7053 when accessing any index of the target of a React.FormEvent Basically I'm following this tutorial, converting it to React and TypeScript
Here's the code I've written for the onSubmit event
const signUp = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();

  // Problematic lines of code
  const email = event.target[0].value;
  const password = event.target[1].value;
};

And the basic signup form
  return (

      <form id="signUp" onSubmit={signUp}>

Sign up

        Email
        <input type="email" name="email" />
        Password
        <input type="password" name="password" />

        <input type="submit"></input>
      </form>

  )

The full error:
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'EventTarget'.
  Property '0' does not exist on type 'EventTarget'.  TS7053

A: You seem to be getting it incorrectly. onSubmit event will not contain any input values. To access the input values, I'd suggest you store them in a state and bind it using onChange so that when the form is submitted you can validate using the state values.
Short answer to get this working:
Add an id attribute to the input tags to access the values on submit.
<input type="email" name="email" id="email" />
<input type="password" name="password" id="password" />

const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

Example: https://codesandbox.io/s/form-submit-demo-fjls0


text:
Q: Override ScriptControl or BaseValidator for an async ASP.NET validator control? I'm planning to develop an ASP.NET server control to provide asynchronous username availability validation for new user registrations.  The control will allow a developer to point it at a "username" TextBox and it will provide an indication of whether or not the username is available.  Like this example, but without the clunky UpdatePanel.
One design decision that's giving me headaches is whether to inherit from ScriptControl or BaseValidator.
By implementing it as a ScriptControl, I can make the client side portion easier to deal with and easily localize it with a resx.
However, I want to make sure that the validator functions properly with respect to Page.IsValid.  The only way I know to do this is to override BaseValidator and implement EvaluateIsValid().
So, my question is, how would you suggest structuring this control?  Is inheriting from BaseValidator the best (only) way to get the validator part right, or can I do that in some other way?

A: You should be able to do both if you implement the IScriptControl interface while also deriving from BaseValidator:
public class YourControl : IScriptControl, BaseValidator

To implement the IScriptControl interface means your control will also have to have the GetScriptReferences and GetScriptDescriptors methods.


text:
Q: Yahoo Fantasy Sports API not authenticating I am at the beginning stages of fiddling with Yahoo's Fantasy Sports API as described here.  https://developer.yahoo.com/fantasysports/guide/  However on literally the first step, I it is not working.
I have the PHP Sample Code in a file to ensure everything is connected to Yahoo and working, but it does not work.  I get the following error.
Couldn't open /tmp/oauth_data_token_storage_\comsumerkey\.out, assuming we need to get a new request token. Better try to get a new access token. Invalid auth/bad request (got a 411, expected HTTP/1.1 20X or a redirect) Full OAuth Flow without Libraries ¶ If the PHP library described above doesn't fit your needs, you may feel like implementing the flow yourself. It's mildly tricky and you may run into common issues like not sorting the parameters correctly, or not encoding the various parts of the URL at the right time. The following script is an example of doing absolutely everything from scratch, and may be a useful guide for you. Could not retrieve request token data
My app has been created on the developer.yahoo.com site and where in the code above \comsumerkey\ is where my consumer key is located at.
Why am I getting a 411 response.  Sounds like there is something outdated with the code from this guide.

A: You are receiving the HTTP 411 status code because the server expects the Content-Length header in your request. Yahoo definitely uses the 411 code in this way, indicated in this document for their Social API.
The sample code you are using simply is not sending the header. You will need to do so yourself by calculating the length of your content manually and sending it using the header function, or alternatively by finding a script that performs the authentication correctly for you.


text:
Q: The conditions under which a stress tensor $T^{\mu\nu}$ exists I used to believe that the existence of the stress tensor in a QFT has to do with translation invariance: "If a theory is translation invariant, then one can construct a conserved $T^{\mu\nu}$ by Noether theorem". But it has been pointed to me that the existence of a conserved $T^{\mu\nu}$ is related to the locality of the theory. How can we show this? and is there some counterexamples?

A: Translation invariance guarantees only the existence of conserved charges: $P_i$ and the Hamiltonian $H$ itself. It is an extra assumption that those charges can be written in terms of local currents: $P_\mu = \int T_{0\mu}(x) d^{d-1}x$. Theories given by an action which is written in terms of local Lagrangian densities will possess a conserved EMT (provided they are translation invariant).

A: Indeed, nonlocal CFT's like the scaling limit of long-range Ising models will typically lack a local stress tensor. In Euclidean signature, the kinetic term is $\phi (-\Delta)^{\alpha}\phi$ which is still unitary if $0<\alpha<1$.
Some references on this:

*

*Paulos, M. F., Rychkov, S., van Rees, B. C., & Zan, B. (2016). Conformal invariance in the long-range Ising model. Nuclear Physics B, 902, 246-291.

*Behan, C., Rastelli, L., Rychkov, S., & Zan, B. (2017). Long-range critical exponents near the short-range crossover. Physical Review Letters, 118(24), 241601.

*Behan, C., Rastelli, L., Rychkov, S., & Zan, B. (2017). A scaling theory for the long-range to short-range crossover and an infrared duality. Journal of Physics A: Mathematical and Theoretical, 50(35), 354002.

*Behan, C. (2019). Bootstrapping the long-range Ising model in three dimensions. Journal of Physics A: Mathematical and Theoretical, 52(7), 075401.


text:
Q: Equality case in elementary form of Holder's Inequality A well known elementary formulation of Holder's Inequality can be stated as follows:
Let $a_{ij}$ for $i = 1, 2, \dots, k; j = 1, 2, \dots, n$ be positive real numbers, and let $p_1, p_2, \dots, p_k$ be positive real numbers such that $\sum_{i=1}^{k} \frac{1}{p_i} = 1$.  Then we have
$$\sum_{j = 1}^{n} \prod_{i = 1}^{k} a_{ij} \leq \prod_{i=1}^{k} \left ( \sum_{j = 1}^{n} a_{ij}^{p_i} \right )^{\frac{1}{p_i}}.$$
Does anyone know when equality occurs in this inequality?  Any insights on the equality case and/or a proof would be appreciated.

I have seen several proofs of the two sequence case.  Here is one, from Cvetkovski's Inequalities:

Perhaps this argument can be generalized to prove the above result.  Thanks in advance!

A: Since the usual proof of generalized Holder's proceeds by induction from the usual Holder's inequality, the equality case is precisely the same. In other words, if $v_j$ denotes the vector with components $a_{ij}^p$, then equality occurs iff all the vectors $v_j$ are parallel.


text:
Q: git commit error: large file detected Hi I'm developing an application xcode for ios 8.1 I have used googleMaps framework for autocomplete feature. when I try to push my project in Git I was getting large file detection error. later have tried with git lfs and tracked the file detected by git (i.e., GoogleMaps) then I tries push still showing the same error.
iSpire-Solution-1:productionPreFinal 2$ git push -u origin master
Counting objects: 762, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (693/693), done.
Writing objects: 100% (762/762), 83.82 MiB | 4.14 MiB/s, done.
Total 762 (delta 179), reused 0 (delta 0)
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
remote: error: Trace: e7a6ab16d31c340cad67b08ee53ee032
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File Pods/GoogleMaps/Frameworks/GoogleMaps.framework/Versions/A/GoogleMaps is 113.56 MB; this exceeds GitHub's file size limit of 100.00 MB
To https://github.com/ispire123/AutoM8.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/ispire123/AutoM8.git'
iSpire-Solution-1:productionPreFinal 2$ git lfs track
Listing tracked paths
    Pods/GoogleMaps/Frameworks/GoogleMaps.framework/Versions/A/GoogleMaps (.gitattributes)

Please suggest me how can i Manage git lfs. and is there any option reduce the file size of googleMaps frameworks in iOS.
Thanks.

A: Assuming you're using CocoaPods as a dependency manager for your Xcode project, consider following this advice and only committing the Podfile as the pods can be regenerated from the Podfile.
This means that you're not committing over Github's file limit and you're keeping your repository streamlined.
To ensure you don't commit any Pods to your repo, just add the pods/ directory to your/a .gitignore file.


text:
Q: Is it possible to generate an unspoofable Hardware ID or a very difficult to spoof hardware ID? (i.e. buy a new PC part?) I'm using C++ and working on my own game that uses mssql as a database (so yes I can store the generated hardware id somewhere). but thats not the point. Is it possible to generate a hardware id that cannot be spoofed, or to spoof the hardware id, it would require a whole new "motherboard" or "video card" for example.
Thanks so much pardon my ignorance I'm a new programmer. :)
example:
Say I make it generate a GUID when the user creates an account, I store it in my database. Simple. I then make that GUID not able to login to the game (Say they got caught hacking for example). They then create a new account. Will this new account generate the same GUID, meaning, well, they're still banned? (This is the outcome I'm looking for.)
I need to generate an ID that is tied to a users computer. I need it so it cannot be spoofed or will be difficult. The purpose of the ID is to block access to creating an account or logging into their already created account. I just want to know if I can generate an ID from someones PC, save it, and that they cannot change it.

A: I think what you're looking for is a GUID. GUIDs are numbers that are practically guaranteed to be unique.
Have a read of this. There's plenty of GUID generators out there if it is indeed what you need.


text:
Q: imbalanced clustering by optimizing normalized cut I have been studying spectral graph partitioning and I found that this algorithm optimize normalized cut by taking equal size cluster, which might not be a real world scenario. Is there any algorithm that optimize normalized cut but not necessarily taking equal size cluster?

A: A better approach is to find an affinity matrix $\bf A$, for example:
   $${\bf A}_{ij} = \exp(-|{\bf D}_{ij}|)$$
where $\bf D$ is a distance matrix, for example:
   $${\bf D}_{ij} = |{\bf d}_i-{\bf d}_j|$$
Where $\bf d$ is your data vector ( assuming it 1 dimensional for simplicity ).
If you do this, then you can search for the second largest eigenvalue of your affinity matrix, and corresponding eigenvector, and your two directions for cut are positive real and negative real. So 0 as element in your eigenvector is the cut decision boundary. This will find cuts where the relation of the sizes of your clusters can be arbitrary.
To find one of the largest eigenvalues and corresponding eigenvectors, popular methods include power iteration and Krylov subspace methods such as Lanczos iterations.

EDIT To solve the issue you face you may want to remove the mean value of your eigenvector. Otherwise 0 won't be the cut decision boundary as i claimed above.


text:
Q: My react typescript app always show a Firebase Welcome screen I am implementing an application with react typecript.
I try to upload my application to Firebase hosting but a "Welcome to Firebase Hosting" screen always appears. The problem I have is that now when I run npm run build locally it doesn't generate my application anymore, it always generates the index.html with the Firebase screen.
How could I fix this problem?


text:
Q: GUI for PHP/MySQL -- Create, Read, Update, Delete Looking for a fast, simple way to roll-out a application layer for an existing database. Realize this is a very open end question, so if it is, then the question is what factors should I account for when compare options provided vs. implementation requirements; for example, ORMs supported, js-frameworks supported, etc.
Questions, feedback, comments -- just comment, thanks!

A: phpMyAdmin

A: Adminer
It is much more light-weight than PhpMyAdmin and IMO provides better interface (though fewer advanced features). And is easier to get rolling - it is only a single PHP file.
I'm not entiery sure what you mean by "ORMs supported". Adminer supports MySQL, PostgreSQL, SQLite, MS SQL and Oracle database systems, if that's what you mean.


text:
Q: Oscilloscope and mains voltage In the country were I live the mains electricity voltage is 230Vac. When I measure the mains voltage using an Uni-t UT52 multimeter, the multimeter measures about 247Vac.
It is safe to power the oscilloscope (model GDS 1052 U) at this voltage (247Vac)?
In the manual it is wrote that it can be powered at up to maximum 240Vac. Also in the manual it says "the power supply voltage should not fluctuate more than 10%".
It is safe to use the scope at 247Vac without any damage?
The oscilloscope could be damaged in time (after a few years or months of use) because of the high mains voltage?

A: That should be absolutely fine to use. Most of the time, a cheap digital multimeter will never give you great readings on AC voltage, but as the scope says it can fluctuate up to 10%, then you really shouldn't worry, it will be able to handle AC voltage up to 264V.


text:
Q: Change tuples in a tuple to lists in a list I'm trying to remove tuples from a list, but I have no idea what to do.
I want to change this:
((1947, '23:53'), (1949, '23:57'))

into this:
[[1947, '23:53'], [1949, '23:57']]

What should I do?

A: List comprehensions to the rescue! You're basically just spinning through the list of tuples and casting them to a list, creating a new list while doing so.
list_of_tuples = [(1,2), (3,4)]
list_of_lists = [list(my_tuple) for my_tuple in list_of_tuples]


text:
Q: How can I fix module 'discord' has no attribute 'Bot' Or code a Slash Snipe bot correctly? I've just started learning how to code and I'm super new to everything. I usually watch YouTube videos that kinda of teach me everything but I've been having trouble with coding my /snipe bot as it always says "error: module 'discord' has no attribute 'Bot'"
I'm not sure what I'm doing wrong but this is the code so far, not including the snipe code commands
    import discord

bot = discord.bot(intents = discord.intents.default())

servers = []

@bot.event
async def on_ready():
  print(f"We have logged in as {bot.user}.")

bot.run('token')

Any way I can fix this? or would there better another better way to code a /snipe bot

A: As like in the comment from 3nws. First you should determine client that make it equal to bot
bot = commands.Bot(command_prefix=[your prefix here])

Then you can go using bot instead client. It just like nicknames when you are calling your friend
@bot.event()
async def on_ready():
    print(f"We have logged in as {bot.user}.")


text:
Q: Dynamic / parsing of Json Objects In the following snippet I do not understand the difference between the code underneath the "//this fails", and the code under "//this works" (which is provided as boilerplate code when creating an Azure function.) NOTE: I realize that the cast to object isn't necessary, BUT ReadAsAsync returns object....
public static class FunctionTest
{
    [FunctionName("TestFunction")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");

        // parse query parameter
        string name = req.GetQueryNameValuePairs()
          .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
          .Value;

        //if nothing in the query parameter - lets' look into the body
        if (name == null)
        {
            //this fails
            dynamic abc = (object) @"{""name"":""test""}";
            string test = abc?.name;

            // this works
            dynamic data = await req.Content.ReadAsAsync<object>();
            name = data?.name;
        }

        return name == null
          ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
          : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }
}

A: The first line:
dynamic abc = (object) @"{""name"":""test""}";

will take a string value and cast it into an object. That doesn't mean that it will treat the string as JSON and make a new dynamic object with a name property. It's still a string and the contents don't matter.
The second line however:
dynamic data = await req.Content.ReadAsAsync<object>();

calls the ReadAsAsync method with a generic type of object. This actually gives you a JObject cast as an object with various properties meaning that you could do this:
name = data["name"];

And because it is dynamic, that effectively translates your code into the above. However, almost every time I see dynamic, it's a code smell and this is no difference. Instead make a concrete class with the right properties and use that. That way you will have compile time type checking instead of relying on the dynamic object. For example:
public class Foo    {
    public string Name { get; set; }
}

And use it like this:
Foo data = await req.Content.ReadAsAsync<Foo>();


text:
Q: c3867'sf::Time::as seconds':non-standard syntax ;use '&'to create a pointer to a member #include<SFML/Graphics.hpp>
#include<iostream>

int main() {
sf::RenderWindow Window;
Window.create(sf::VideoMode(800, 600), "Game Engine");
sf::Time time = sf::seconds(2);
std::cout << time.asSeconds << std::endl;
while (Window.isOpen()) {
    sf::Event Event;
    while (Window.pollEvent(Event))     {
        if (Event.type ==  sf::Event::Closed) {
            Window.close();
        }

        Window.display();

    }

    {

    }
}

}

1>------ Build started: Project: SFML-2.0, Configuration: Debug Win32 ------
  1>  Main.cpp
  1>c:\users\paribeshpc\documents\visual studio 2015\projects\sfml-2.0\sfml-2.0\main.cpp(11): error C3867: 'sf::Time::asSeconds': non-standard syntax; use '&' to create a pointer to member
  ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Please help me, I keep getting this error. I was learning sfml from this dued and I copied this code from him but its not working.   The link to the video

A: sf::Time::asSeconds is a function, you need to call it:
std::cout << time.asSeconds() << std::endl;
//                         ^^
//      Note parentheses here

What happens right now is that the compiler thinks you want a pointer to the function, which is why it tells you to use the address-of operator &.


text:
Q: Taking the category of sheaves is symmetric monoidal Let $M$ and $N$ be topological spaces.
Let $\operatorname{Sh}(M)$ denote the presentable $\infty$-category of space-valued sheaves on $M$.
It seems to me that the equivalence
$$\operatorname{Sh}(M) \otimes \operatorname{Sh}(N) = \operatorname{Sh}(M \times N)$$
where $\otimes$ is the standard symmetric monoidal structure of $\operatorname{Pr^L}$, the $\infty$-category of presentable categories with left adjoints, is well-known.
However, I cannot find a proof in the literature.
My question is if there is a standard reference for this statement? Or if there is a "simple proof" of it by assuming some well-known results?
By the way, I believe that I was once told that it's in Lurie but I've failed to find it in either Higher Topos Theory or Higher Algebra.

A: *

*Provided at least one of $M$ and $N$ is locally compact, the $\infty$-topos $\mathrm{Sh}(M \times N)$ is the product of $\mathrm{Sh}(M)$ and $\mathrm{Sh}(N)$ in $\mathrm{RTop}$. This is HTT 7.3.1.11.

*Products in $\mathrm{RTop}$ can be computed as tensor products in $\mathrm{Pr^L}$. This is HA Example 4.8.1.19.
HA doesn't include a complete proof of the latter, but the case where one of the factors is of the form $\mathrm{Sh}(M)$ is essentially HTT 7.3.3.9, up to the matter of identifying $\mathrm{Sh}(M; \mathrm{Sh}(N))$ with the tensor product $\mathrm{Sh}(M) \otimes \mathrm{Sh}(N)$, for which HA 4.8.1.17 should be useful.


text:
Q: Jquery no conflict magento Need help on this javascript i tried to add noconflict but nothing happen
<script type="text/javascript">
            jQuery.noConflict();
            jQuery('.carousel').iosSlider({
                desktopClickDrag: true,
                snapToChildren: true,
                infiniteSlider: false,
                navNextSelector: '.new-arrow.next',
                navPrevSelector: '.new-arrow.prev'
            });
        </script>

Any help is appreciated.

A: Store jquery in a variable, then when code must reference the stored version use the variable.  Also make sure you have the jquery script above your noconflict code.
<!-- Old Jquery Version -->
<script type="text/javascript" src="jquery-1.7.js"></script>
<script type="text/javascript">
   var j = jQuery.noConflict();
   j('.carousel').iosSlider({
      desktopClickDrag: true,
      snapToChildren: true,
      infiniteSlider: false,
      navNextSelector: '.new-arrow.next',
      navPrevSelector: '.new-arrow.prev'
    });
 </script>
 <!--Latest Jquery Version -->
 <script type="text/javascript" src="jquery.js"></script>


text:
Q: why I am getting this error Unknown provider in angularJS? I trying to do a simple application that displays the list of products in a table.
I am using angularJS v1.4 in a Spring boot application.
produitService.js:
var app = angular.module('MyApp', []);
app.service('serviceProduit', ['$resource', function($resource) {
    this.getProduits = function() {
        return $resource("http://localhost:8080/produits",null,{'get':{method:'GET'}});
    }
}]);

produitController.js:
var app = angular.module('MyApp', []);
app.controller(
    'produitController', [ '$scope', '$rootScope', 'serviceProduit',
        function($scope, $rootScope, serviceProduit) {
            $scope.getProduits = function() {
                serviceProduit.getProduits().get().$promise
                    .then(function(response) {
                        $scope.produits = response.result;
                        console.log(response);
                    }, function(response) {
                        console.log(response);
                    });
            };
            $scope.getProducts ();
        } ]);

index.html:

                ID
                Designation
                Prix
                Quantite

                {{p.id}}
                {{p.designation}}
                {{p.prix}}
                {{p.quantite}}

When I inspect the browser console, I am getting this error:

Error: [$injector:unpr] Unknown provider: serviceProduitProvider <-
  serviceProduit <- produitController
  http://errors.angularjs.org/1.4.7/$injector/unpr?p0=serviceProduitProvider%20%3C-%20serviceProduit%20%3C-%20produitController
      at angular.js:68
      at angular.js:4289
      at Object.getService [as get] (angular.js:4437)
      at angular.js:4294
      at getService (angular.js:4437)
      at Object.invoke (angular.js:4469)
      at extend.instance (angular.js:9136)
      at nodeLinkFn (angular.js:8248)
      at compositeLinkFn (angular.js:7680)
      at publicLinkFn (angular.js:7555)

How to solve Unknown provider error?

A: Remove declaring the module again in the produitController.js ,
//remove this line var app = angular.module('MyApp', []);
app.controller(
    'produitController', [ '$scope', '$rootScope', 'serviceProduit',
        function($scope, $rootScope, serviceProduit) {

Also you need to inject ngResource to your app since you are using $resource
var app = angular.module('MyApp', ['ngResource']);
app.service('serviceProduit', ['$resource', function($resource) {

make sure to add the reference in your html too


text:
Q: IPC in Android using GreenRobot eventbus I need to communicate with a remote service, using (greenrobot) EventBus. Unfortunately, it does not seem to work with IPC. Looking at the code, I don't see a workaround either. Any help would be appreciated !
Bonus question - are there any other EventBuses (for Android) which support IPC ?

A:
I need to communicate with a remote service, using (greenrobot) EventBus.

The entire point of greenrobot's EventBus, like Square's Otto and LocalBroadcastManager, is to not use IPC.

Any help would be appreciated !

Don't use greenrobot's EventBus for IPC. Use one of Android's myriad IPC mechanisms for IPC:

*

*startActivity()

*startActivityForResult()

*startService()

*bindService()

*sendBroadcast() and its variations (e.g., sendOrderedBroadcast())

*a ContentProvider

A: There is an IPC EventBus option which allows you to send events over IPC. https://github.com/NewtronLabs/IpcEventBus
According to the documentation all you have to do to get an event is this:
public class Listener implements IIpcEventBusConnectionListener, IIpcEventBusObserver {

    public Listener() {
        String targetApp = "com.packagename";
        IIpcEventBusConnector connector =
            ConnectorFactory.getInstance().buildConnector(context, this, targetApp);
        connector.startConnection();
    }

    @Override
    public void onConnected(IIpcEventBusConnector connector) {
        connector.registerObserver(this);
    }

    @Override
    public void onEvent(IEventIpc event) {
        Log.d("ipceventbus", "Received event: " + event.getClass());
    }

    @Override
    public void onDisconnected(IIpcEventBusConnector connector) {

    }
}

And on the other side you post the event like this:
IpcEventBus.getInstance().postEvent(new MyEvent());

I created a two apps and they were able to send events to each other.

A: Another library that follows the EventBus syntax more closely is HermesEventBus. It supports IPC (and intra process) both.
Although they should have just derived from EventBus, so that we can just inject EventBus object (which is actually a HermesEventBus), and not have to update code everywhere.
https://github.com/eleme/HermesEventBus


text:
Q: Why <%= Html.TextArea("Id",Model)%> shows as an error? I am new in asp.net MVC. When I declear this code then an error shows. Why this is showing and how can i solve it? Thank you.
This is my code :
<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post))
{ %>
    Enter customer id :- <%= Html.TextArea("Id",Model)%> <br /> //shows error
    <input type="submit" value="Submit customer data" />
<%} %>

Error message :
CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'TextArea' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

A: I believe the problem is that you aren't providing the TextArea method with the right parameters. The second parameter of the TextArea overload that you are matching is called HtmlAttributes and it is of type Object. It is meant to take the html attributes you might provide your text area, such as an id, class name, readonly, or disabled. You are providing it with a Model that, while an object, probably isn't providing the text area with html attributes.
You should use TextAreaFor like this
<%= Html.TextAreaFor(x=> x.id)%>

Try looking up some info on Mvc Forms. It should explain how to use them better than I would.


text:
Q: Trying to break a string up and reverse it I am trying to code a program which will ask for a person's full name (first, middle, last) and will print (last, middle, tsrif). Like print their name backwards, but the letters are backwards only on their first name. I can't figure out how to flip the order of the words without flipping their letters. Any help?
My code so far:
import sys
str = raw_input("first middle last")

str.split( );

A: The str.split() function returns the list, it doesn't modify it in place. So you want :
split_up = str.split()

(obviously split_up is an arbitrary name, the point is that it's a list)

A: >>> my_string = raw_input('?: ').split()
?: first middle last
>>> new_string = ' '.join(my_string[:0:-1] + [my_string[0][::-1]])
>>> new_string
'last middle tsrif'

A: >>> s = 'first middle last'
>>> L = s.split()
>>> L[0] = L[0][::-1]
>>> L
['tsrif', 'middle', 'last']
>>> print L[::-1]
['last', 'middle', 'tsrif']

A: Reverse the list at first. Then reverse the last string in list
my_list = string.split()
my_list = list(reversed(my_list))
my_list[2] = my_list[2][::-1]
print my_list

Don't use str as variable.

A: This should work
import sys
str = "first middle last";
allWords = str.split(" ");
length = len(allWords)
for index in range(length-1):
    print(allWords[length-index-1],end=" ")
print((allWords[0])[::-1])

A: input_name = "first middle last" # whatever your input is: using as example here
split_name = input_name.split()
desired_output = [split_name [2], split_name [1], split_name [0][::-1]]

>>> desired_output
 ['last', 'middle', 'tsrif']

>>> ' '.join(desired_output)
'last middle tsrif'

>>> ', '.join(desired_output)
'last, middle, tsrif'

A: Let's assume you have a variable s which you've gotten from the user.  If you want to split that up into individual words, you use .split() and save the result
s = "john henry smith"
parts = s.split() # ['john', 'henry', 'smith']

now, to reverse these words, you can use the built in function reversed and convert the result to a list
rev_parts = list(reversed(parts))  # ['smith', 'henry', 'john']

Finally you want to reverse just the last element of rev_parts, you can use a -1 index to indicate the last element in the list.  What you want to do is overwrite the existing element.  We can use reversed again here, but we'll also need to use a join to tell it to but all the characters back together after
rev_name = ''.join(reversed(rev_parts[-1])) # 'nhoj'
rev_parts[-1] = rev_name # overwrite 'john'

Now you have a list of what you want.  If you want to put them all back together separated by spaces, use another join
result = ' '.join(rev_parts)

You can eliminate various intermediate variables and steps here as you feel comfortable.

An alternative to using reversed is to use the slice syntax [::-1] which says, from the end to the beginning, back one character at a time.  In that case you'd have
rev_parts = parts[::-1]
rev_parts[-1] = rev_parts[-1][::-1]


text:
Q: char pointer and static_cast in c++ code related to virtualalloc I was searching for some code related to VirtualAlloc and came across this piece of code:
#include<windows.h>
#include<iostream>
using namespace std;

int main() {
size_t in_num_of_bytes,i;
cout<<"Please enter the number of bytes you want to allocate:";
cin>>in_num_of_bytes;

LPVOID ptr = VirtualAlloc(NULL,in_num_of_bytes,MEM_RESERVE | MEM_COMMIT,PAGE_READWRITE); //reserving and commiting memory

if(ptr){
    char* char_ptr = static_cast<char*>(ptr);
    for(i=0;i<in_num_of_bytes;i++){ //write to memory
        char_ptr[i] = 'a';
    }

    for(i=0;i<in_num_of_bytes;i++){ //print memory contents
        cout<<char_ptr[i];
    }

    VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory
}else{
    cout<<"[ERROR]:Could not allocate "<<in_num_of_bytes<<" bytes of memory"<<endl;
}

return 0;
}

This is a piece of code that I am trying to understand. However, I am confused about the following line:
char* char_ptr = static_cast<char*>(ptr);

I am not sure as to why this line is needed. And what does it do?

A: Simpler example:
void* allocate_some_stuff(){
    return new char[42];
}

int main()
{
    void* ptr = allocate_some_stuff();
    char* cptr = ptr;
}

Because C++ does not allow implicit conversion from void* to char* it causes the error:
<source>:9:18: error: invalid conversion from 'void*' to 'char*' [-fpermissive]
    9 |     char* cptr = ptr;
      |                  ^~~
      |                  |
      |                  void*

But is fine when you explicitly cast:
int main()
{
    void* ptr = allocate_some_stuff();
    char* cptr = static_cast<char*>(ptr);
}

void* can point (almost) anywhere and casting to char* is generally ok (char is an exception with respect to that). When dealing with void* the type system is bypassed and to some large extend it is up to you to know what that pointer actually points to or what it can be used for.