text:
Q: Why does this C code give me a segmentation fault? Using the CS50 library, this is my code but it keeps giving me a segmentation fault. I have tried to figure out where it keeps doing a segmentation fault, and for some reason it has to do with my function. Why does it keep doing this?
#import <cs50.h>
#import <stdio.h>
#import <ctype.h>
#import <string.h>

string ciphertext(string plaintext[1], string key[1]);

int main(int argc, string argv[])
{
    // Variables
    string plaintext2[1];

    if (argc == 2)
    {
        if(strlen(argv[1]) == 26)
        {
            string text = get_string("plaintext: ");
            plaintext2[0] = text;
        }
        else
        {
            printf("Key must contain 26 characters.\n");
            return 1;
        }
    }
    else
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }

    string ciphertext2 = ciphertext(&plaintext2[0], &argv[1]);
    printf("ciphertext: %s\n", ciphertext2);
}

string ciphertext(string plaintext[1], string key[1])
{
    // Variables
    string ciphertext[1];

    for (int i = 0; i < strlen(plaintext[0]); i++)
    {
        if (plaintext[0][i] == 'a')
        {
            ciphertext[0][i] = tolower(key[0][0]);
        }
        else if (plaintext[0][i] == 'A')
        {
            ciphertext[0][i] = toupper(key[0][0]);
        }
        else if (plaintext[0][i] == 'b')
        {
            ciphertext[0][i] = tolower(key[0][1]);
        }
        else if (plaintext[0][i] == 'B')
        {
            ciphertext[0][i] = toupper(key[0][1]);
        }
        else if (plaintext[0][i] == 'c')
        {
            ciphertext[0][i] = tolower(key[0][2]);
        }
        else if (plaintext[0][i] == 'C')
        {
            ciphertext[0][i] = toupper(key[0][2]);
        }
        else if (plaintext[0][i] == 'd')
        {
            ciphertext[0][i] = tolower(key[0][3]);
        }
        else if (plaintext[0][i] == 'D')
        {
            ciphertext[0][i] = toupper(key[0][3]);
        }
        else if (plaintext[0][i] == 'e')
        {
            ciphertext[0][i] = tolower(key[0][4]);
        }
        else if (plaintext[0][i] == 'E')
        {
            ciphertext[0][i] = toupper(key[0][4]);
        }
        else if (plaintext[0][i] == 'f')
        {
            ciphertext[0][i] = tolower(key[0][5]);
        }
        else if (plaintext[0][i] == 'F')
        {
            ciphertext[0][i] = toupper(key[0][5]);
        }
        else if (plaintext[0][i] == 'g')
        {
            ciphertext[0][i] = tolower(key[0][6]);
        }
        else if (plaintext[0][i] == 'G')
        {
            ciphertext[0][i] = toupper(key[0][6]);
        }
        else if (plaintext[0][i] == 'h')
        {
            ciphertext[0][i] = tolower(key[0][7]);
        }
        else if (plaintext[0][i] == 'H')
        {
            ciphertext[0][i] = toupper(key[0][7]);
        }
        else if (plaintext[0][i] == 'i')
        {
            ciphertext[0][i] = tolower(key[0][8]);
        }
        else if (plaintext[0][i] == 'I')
        {
            ciphertext[0][i] = toupper(key[0][8]);
        }
        else if (plaintext[0][i] == 'j')
        {
            ciphertext[0][i] = tolower(key[0][9]);
        }
        else if (plaintext[0][i] == 'J')
        {
            ciphertext[0][i] = toupper(key[0][9]);
        }
        else if (plaintext[0][i] == 'k')
        {
            ciphertext[0][i] = tolower(key[0][10]);
        }
        else if (plaintext[0][i] == 'K')
        {
            ciphertext[0][i] = toupper(key[0][10]);
        }
        else if (plaintext[0][i] == 'l')
        {
            ciphertext[0][i] = tolower(key[0][11]);
        }
        else if (plaintext[0][i] == 'L')
        {
            ciphertext[0][i] = toupper(key[0][11]);
        }
        else if (plaintext[0][i] == 'm')
        {
            ciphertext[0][i] = tolower(key[0][12]);
        }
        else if (plaintext[0][i] == 'M')
        {
            ciphertext[0][i] = toupper(key[0][12]);
        }
        else if (plaintext[0][i] == 'n')
        {
            ciphertext[0][i] = tolower(key[0][13]);
        }
        else if (plaintext[0][i] == 'N')
        {
            ciphertext[0][i] = toupper(key[0][13]);
        }
        else if (plaintext[0][i] == 'o')
        {
            ciphertext[0][i] = tolower(key[0][14]);
        }
        else if (plaintext[0][i] == 'O')
        {
            ciphertext[0][i] = toupper(key[0][14]);
        }
        else if (plaintext[0][i] == 'p')
        {
            ciphertext[0][i] = tolower(key[0][15]);
        }
        else if (plaintext[0][i] == 'P')
        {
            ciphertext[0][i] = toupper(key[0][15]);
        }
        else if (plaintext[0][i] == 'q')
        {
            ciphertext[0][i] = tolower(key[0][16]);
        }
        else if (plaintext[0][i] == 'Q')
        {
            ciphertext[0][i] = toupper(key[0][16]);
        }
        else if (plaintext[0][i] == 'r')
        {
            ciphertext[0][i] = tolower(key[0][17]);
        }
        else if (plaintext[0][i] == 'R')
        {
            ciphertext[0][i] = toupper(key[0][17]);
        }
        else if (plaintext[0][i] == 's')
        {
            ciphertext[0][i] = tolower(key[0][18]);
        }
        else if (plaintext[0][i] == 'S')
        {
            ciphertext[0][i] = toupper(key[0][18]);
        }
        else if (plaintext[0][i] == 't')
        {
            ciphertext[0][i] = tolower(key[0][19]);
        }
        else if (plaintext[0][i] == 'T')
        {
            ciphertext[0][i] = toupper(key[0][19]);
        }
        else if (plaintext[0][i] == 'u')
        {
            ciphertext[0][i] = tolower(key[0][20]);
        }
        else if (plaintext[0][i] == 'U')
        {
            ciphertext[0][i] = toupper(key[0][20]);
        }
        else if (plaintext[0][i] == 'v')
        {
            ciphertext[0][i] = tolower(key[0][21]);
        }
        else if (plaintext[0][i] == 'V')
        {
            ciphertext[0][i] = toupper(key[0][21]);
        }
        else if (plaintext[0][i] == 'w')
        {
            ciphertext[0][i] = tolower(key[0][22]);
        }
        else if (plaintext[0][i] == 'W')
        {
            ciphertext[0][i] = toupper(key[0][22]);
        }
        else if (plaintext[0][i] == 'x')
        {
            ciphertext[0][i] = tolower(key[0][23]);
        }
        else if (plaintext[0][i] == 'X')
        {
            ciphertext[0][i] = toupper(key[0][23]);
        }
        else if (plaintext[0][i] == 'y')
        {
            ciphertext[0][i] = tolower(key[0][24]);
        }
        else if (plaintext[0][i] == 'Y')
        {
            ciphertext[0][i] = toupper(key[0][24]);
        }
        else if (plaintext[0][i] == 'z')
        {
            ciphertext[0][i] = tolower(key[0][25]);
        }
        else if (plaintext[0][i] == 'Z')
        {
            ciphertext[0][i] = toupper(key[0][25]);
        }
        else
        {
            ciphertext[0][i] = plaintext[0][i];
        }
    }
    return ciphertext[0];
}

I really need some help, and I don't know why it keeps giving a fault.

A: The array
string ciphertext[1];

is uninitialized and has indeterminate value.
Accessing such an array the way like this
ciphertext[0][i] = tolower(key[0][0]);

results in undefined behavior.
You need to allocate a character array with the size equal to the value of the expression
strlen( *plaintext ) + 1

Pay attention to that instead the numerous if-else statement you could define a string literal like for example
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

and then you can use the standard string function strchr like
char *p = strchr( letters, toupper( ( unsigned char)plaintext[0][i] ) );
if ( p != NULL )
{
    if ( plaintext[0][i] == *p )
    {
        ciphertext[0][i] = key[0][p - letters]);
    }
    else
    {
        ciphertext[0][i] = tolower(key[0][p - letters]);
    }
}

A: You already have the answer (@Vlad from Moscow), but I would like to point out a few things:

*

*Duplicating is a very bad practice, it is unreadable and more important seriously time-consuming. If you see "100" else if() statements one below the other you should suspect that something is terribly wrong with your code.

*Try your best to avoid using numbers in your code. What if you want to change a value that you already copy-pasted a hundred times? Instead of using numbers, I would advise you to use  variables and symbolic constants
Try to improve your current code, you can write something like this:
for (int i = 0; i < strlen(plaintext[0]); i++)
{
    int ind = 0;
    int lower_case = 97, upper_case = 65;

    if (plaintext[0][i] == lower_case)
    {
        ciphertext[0][i] = tolower(key[0][ind]);
    }
    else if (plaintext[0][i] == upper_case)
    {
        ciphertext[0][i] = toupper(key[0][ind]);
    }

    ind++; lower_case++; upper_case++;
}


text:
Q: GDB "layout src" terminal window output corruption I am using the "layout src" tui feature within gdb (amazing if you haven't used it) which allows you to step through the source code, showing the surrounding code in the terminal whilst you step through.
However, occasionally/bordering on frequently I encounter an issue where the terminal output becomes corrupted. The output on the screen becomes mixed, with source code from previous and current stack frames showing. I have seen this on Red Hat 6.5 and CentOS 6. The GDB version is 7.11
The latest instance of this occurring (5 mins ago) seems to have been triggered when I stepped over code which output to the screen.
I have seen this problem in various different code bases, at different companies and its a shame because the gdb tui mode is very helpful.
Does anyone know how to fix this/what causes it?

A: What you describe is likely a known issue when program output is getting mixed with tui output. When this happens you can "fix" tui windows by refreshing them either using command refresh or CTRL+L keyboard shortcut. See documentation:
refresh

    Refresh the screen. This is similar to typing C-L.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling select on change event div load I have a script that loads a set of form controls based off of the selection made in a drop-down list. I load the elements from a php file in to a div using the following code:
<script>
$(function() {
  $('#prompt_type').change(function() {
        switch ($( this ).find(":selected").text()) {
            case 'Select':
                $('#prompt_elements').load('index.php?path=promptelm&and_id=' + <?php echo $and->and_id; ?> + ' #type_select');
                break;
            case 'Radio':
                $('#prompt_elements').load('index.php?path=promptelm&and_id=' + <?php echo $and->and_id; ?> + ' #type_radio');
                break;
            case 'Checkbox':

This part works great. My issue however is I am saving this information to a database and when I revisit the form even though my drop-down contains the correct value the elements are not loading unless I reselect the option to spark the .change event again. Is there a way to call my switch right after the drop-down is loaded?

A: You can try having the change handler in a separate function which will be called on document ready event (depends on your deserialization).

A: put your switch in a seperated function, something like:
function loadingFunc(jqObj){

      switch ($( jqObj ).find(":selected").text()) {
            case 'Select':
               .....
}

$(document).ready(function () {
     loadingFunc( $('#prompt_type'));
     $('#prompt_type').change(function() {
         loadingFunc( $(this));
     });
});


text:
Q: XSLT & XSL-FO: Creating a table with multiple rows? I'm fairly new to XSLT and I am stuck with a problem where I have an Element with an unknown amount of children, and I need to display these children in a table such that there are 5-6 columns available to display the information.
If I'm given an XML file that looks like this:
<books>
    <book>
        <author>Ralls, Kim</author>
        <title>Midnight Rain</title>
    </book>
    <book>
        <author>Corets, Eva</author>
        <title>Maeve Ascendant</title>
    </book>
    <book>
        <author>Corets, Eva</author>
        <title>Oberon's Legacy</title>
    </book>
    <book>
        <author>Randall, Cynthia</author>
        <title>Lover Birds</title>
    </book>
    <book>
        <author>Thurman, Paula</author>
        <title>Splish Splash</title>
    </book>
    <book>
        <author>Knorr, Stefan</author>
        <title>Creepy Crawlies</title>
    </book>
    <book>
        <author>Kress, Peter</author>
        <title>Paradox Lost</title>
    </book>
    <book>
        <author>Crichton, Michael</author>
        <title>Jurassic Park</title>
    </book>
    <book>
        <author>Orwell, George</author>
        <title>1984</title>
    </book>
    <book>
        <author>Martin, George</author>
        <title>A Song of Ice And Fire</title>
    </book>
</books>

I would like to display these 10 books in a table consisting of two rows and five columns.
I've gotten this far:
<xsl:template match="books" mode="table">
    <fo:table margin-left="auto" margin-right="auto">
        <fo:table-body>
            <fo:table-row table-layout="fixed">
                <xsl:for-each select="skill">
                    <fo:table-cell border="1">
                        <fo:block font-weight="bold">
                            <xsl:value-of select="name"/>
                        </fo:block>
                    </fo:table-cell>
                </xsl:for-each>
            </fo:table-row>
        </fo:table-body>
    </fo:table>
</xsl:template>

But all this will do is put every cell on the same row.  I'm looking for a way to check if the loop has run a certain amount of times (5 or 6), and inserting a new row when that happens, but I don't know if that's something I can do in XSL.
Can anyone point me in the right direction?

A: The previous answers are way to complicated for what should be (and is) easy. Recursion is not required for such a simple thing.
In XSL FO you do not need to structure tables with rows. You can use the attribute "ends-row" to specify that you are ending a row and starting a new one. You can easily adapt this simple example and even pass in the "number of columns" (see the mod 5 ... which means after every fifth one start a new row ... change to 4 or 8 or whatever you wish) ... You would just create the structure for the table (fo:table and fo:table-body) outside of this. Inside the table body just put cells as children like this template does:
  <xsl:template match="book">
    <xsl:variable name="pos" select="position()"/>
    <fo:table-cell>
        <xsl:if test="not($pos mod 5)">
            <xsl:attribute name="ends-row">true</xsl:attribute>
        </xsl:if>
        <fo:block>
            <xsl:value-of select="author"/>
        </fo:block>
    </fo:table-cell>
</xsl:template>

So putting this into a simple example with your data ... see below. Formats your XML into five columns per row.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    version="1.0">
<xsl:template match="/">
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
        <fo:layout-master-set>
            <fo:simple-page-master margin-top="1in" margin-left="1in" margin-bottom="1in"
                margin-right="1in" page-width="8in" page-height="11in" master-name="first">
                <fo:region-body margin-top="0pt"/>
                <fo:region-before extent="0pt"/>
                <fo:region-after extent="0pt"/>
            </fo:simple-page-master>
        </fo:layout-master-set>
        <fo:page-sequence master-reference="first">
            <fo:flow flow-name="xsl-region-body" font-size="12pt" font-family="Helvetica">
    <xsl:apply-templates/>
            </fo:flow>
        </fo:page-sequence>
    </fo:root>
</xsl:template>
    <xsl:template match="books">
        <fo:table>
            <fo:table-body>
                <xsl:apply-templates/>
            </fo:table-body>
        </fo:table>
    </xsl:template>
    <xsl:template match="book">
        <xsl:variable name="pos" select="position()"/>
        <fo:table-cell border="1pt solid black">
            <xsl:if test="not($pos mod 5)">
                <xsl:attribute name="ends-row">true</xsl:attribute>
            </xsl:if>
            <fo:block>
                <xsl:value-of select="author"/>
            </fo:block>
        </fo:table-cell>
    </xsl:template>

</xsl:stylesheet>

A: One approach is to use two recursive templates:
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:ext="http://exslt.org/common"
                xmlns:fo="http://www.w3.org/1999/XSL/Format"
                exclude-result-prefixes="ext">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <!-- set the number of columns you want globally -->
    <xsl:param name="set-cols" select="'5'"/>

    <xsl:template match="books">
        <!-- count the needed rows -->
        <xsl:variable name="set-row" select="ceiling(count(book) div $set-cols)"/>

        <fo:table margin-left="auto" margin-right="auto">
            <fo:table-body>
                <xsl:call-template name="rows">
                    <xsl:with-param name="books">
                        <xsl:apply-templates/>
                    </xsl:with-param>
                    <xsl:with-param name="set-row" select="$set-row"/>
                </xsl:call-template>
            </fo:table-body>
        </fo:table>
    </xsl:template>

    <!-- rows -->
    <xsl:template name="rows">
        <xsl:param name="books" select="''"/>
        <xsl:param name="set-row" select="''"/>
        <xsl:param name="count-rows" select="'0'"/>

        <xsl:if test="$set-row > 0">
            <fo:table-row table-layout="fixed">
                <xsl:call-template name="cols">
                    <xsl:with-param name="books" select="$books"/>
                    <xsl:with-param name="count-rows" select="$count-rows"/>
                </xsl:call-template>
            </fo:table-row>
            <xsl:call-template name="rows">
                <xsl:with-param name="books" select="$books"/>
                <xsl:with-param name="set-row" select="$set-row - 1"/>
                <xsl:with-param name="count-rows" select="$count-rows + 1"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

    <!-- columns -->
    <xsl:template name="cols">
        <xsl:param name="books" select="''"/>
        <xsl:param name="cols" select="$set-cols"/>
        <xsl:param name="count-rows" select="''"/>
        <xsl:param name="count-cols" select="'1'"/>

        <xsl:if test="$cols > 0">
            <fo:table-cell border="1">
                <fo:block font-weight="bold">
                    <xsl:variable name="book" select="ext:node-set($books)//book[position() = ($count-rows * $set-cols + $count-cols)]"/>
                    <xsl:value-of select="$book/author"/>
                </fo:block>
            </fo:table-cell>
            <xsl:call-template name="cols">
                <xsl:with-param name="books" select="$books"/>
                <xsl:with-param name="cols" select="$cols - 1"/>
                <xsl:with-param name="count-rows" select="$count-rows"/>
                <xsl:with-param name="count-cols" select="$count-cols + 1"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

</xsl:stylesheet>

With yout input
<books>
    <book>
        <author>Ralls, Kim</author>
        <title>Midnight Rain</title>
    </book>
    <book>
        <author>Corets, Eva</author>
        <title>Maeve Ascendant</title>
    </book>
    <!-- ... -->
</books>

you get:
<fo:table margin-left="auto" margin-right="auto" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <fo:table-body>
        <fo:table-row table-layout="fixed">
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Ralls, Kim</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Corets, Eva</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Corets, Eva</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Randall, Cynthia</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Thurman, Paula</fo:block>
            </fo:table-cell>
        </fo:table-row>
        <fo:table-row table-layout="fixed">
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Knorr, Stefan</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Kress, Peter</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Crichton, Michael</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Orwell, George</fo:block>
            </fo:table-cell>
            <fo:table-cell border="1">
                <fo:block font-weight="bold">Martin, George</fo:block>
            </fo:table-cell>
        </fo:table-row>
    </fo:table-body>
</fo:table>


text:
Q: Can't connect from winXP in Virtual Box to ftp on my linux host I've try to connect to my host system (which is Xubuntu) that run ftp server,
 ftp://10.0.2.2/

I use default ftp built in WindowsXP:
error (I only have Polish version):

Wystąpił błąd podczas otwierania folderu na serwerze FTP. Upewnij się,
  czy masz uprawnienie dostępu do tego folderu.
Szczegóły: Ustanowienie połączenia z serwerem nie było możliwe

something like:

There was error while opening a folder on FTP server. Make sure you
  have access to that directory.
Details: Connection to the server was not possible

but windows XP give error that he can't access the directory. When I connect to http server it work fine, and when I connect to localhost from linux it also work.
FTP is in standard configuration (it work on localhost and from other machines in local network) and I didn't do anything with iptables, OS is Xubuntu 13.10.
I can't find config for ftp, nmap show: OpenBSD ftpd 6.4 (Linux port 0.17)
My Virtual Box network settings is set to NAT (default option).

A: If your FTP server is configured to work in Active mode you need to make sure that your XP firewall is configured to allow your FTP client to listen to connections from server AND as your XP is on the virtual machine you have to ensure that your virtual network is configured in the manner which will allow the ftp server to connect to it.
Alternatively you can configure your FTP to work in Passive mode.
Here is a good explanation of Active and Passive FTP modes. For information on how to configure your FTPD in Passive mode consult man ftpd and man 5 ftpd.conf or use google-fu :)


text:
Q: 'MOD' is not a recognized built-in function name I wanted to use MOD function in SQL Server 2008R2 and followed this link  but still got the message:

'MOD' is not a recognized built-in function name.

DECLARE @m INT
SET @m = MOD(321,11)
SELECT @m

Error:

Msg 195, Level 15, State 10, Line 2
  'MOD' is not a recognized built-in function name.

Why I can't use this function from the link above?

A: The MOD keyword only exists in the DAX language (tabular dimensional queries), not TSQL
Use  % instead.
Ref: Modulo

A: In TSQL, the modulo is done with a percent sign.
SELECT 38 % 5 would give you the modulo 3

A: for your exact sample, it should be like this.
DECLARE @m INT
SET @m = 321%11
SELECT @m

A: It can be done using the % operator.
i.e.
SELECT 50 % 5

A: If using JDBC driver you may use function escape sequence like this:
select {fn MOD(5, 2)}
#Result 1

select  mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.


text:
Q: How to customize the editor interface in vscode I want to develop a vscode plug-in, but I need to customize the editing interface view to be the same as the compare file interface that comes with vscode (the editing function remains the same, only the custom editing interface is required). What should I need to do, thank you
View effect: (One tab and two editing windows)


text:
Q: undefined method `returning' for WillPaginate:Module I was upgrading a Rails 2 application to Rails 3, when I execute rails console it throws this:
$ rails c production
/usr/lib/ruby/gems/1.8/gems/will_paginate-2.3.12/lib/will_paginate.rb:39:in `enable_activerecord': undefined method `returning' for WillPaginate:Module (NoMethodError)
    from /usr/lib/ruby/gems/1.8/gems/will_paginate-2.3.12/lib/will_paginate.rb:88
    from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `require'
    from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `require'
    from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `each'
    from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `require'
    from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `each'
    from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `require'
    from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.18/lib/bundler.rb:120:in `require'
    from /home/neoriddle/proyectos/interkids/config/application.rb:7
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.9/lib/rails/commands.rb:21:in `require'
    from /usr/lib/ruby/gems/1.8/gems/railties-3.0.9/lib/rails/commands.rb:21
    from script/rails:6:in `require'
    from script/rails:6

How can I solve this?

A: Update will_paginate gem.
Method #returning has been deprecated in favor of method #tap. Looks like the old version of will_paginate gem that you're using still uses that deprecated method.

A: Yes, that was true.
Here my details...
I change in Gemfile this line:
gem 'will_paginate', '2.3.12'

with this line:
gem 'will_paginate', '>=3.0.pre'

Then I update Gemfile.lock with this:
bundle update will_paginate

And I get this:
$ bundle update will_paginate
Fetching source index for http://rubygems.org/
...
Installing will_paginate (3.0.2)
Updating .gem files in vendor/cache
  * will_paginate-3.0.2.gem
Removing outdated .gem files from vendor/cache
  * will_paginate-2.3.12.gem
Your bundle is updated! Use `bundle show [gemname]` to see where a bundled gem is installed.

and this error were solved.


text:
Q: GoogleChart Plugin view empty I am using CakePHP 2.x, and I need to show reports via charts. I saw this plugin for CakePHP CakePHP GoogleCharts Plugin by Scott Harwell. I did everything step-by-step and somehow my views keep on appearing empty.
There were no javascript output in the DOM.
Here is my Code:
My bootstrap.php
CakePlugin::load('GoogleCharts');

My Controller:
$results = $this->Statistique->getIndicateursQuants( $this->request->data );
$this->set( 'results', $results );

$chart = new GoogleCharts();
$chart->type("LineChart");
$chart->options(array('title' => "Etat statistique du nombre de flux"));
$chart->columns(array(
       'name' => array(
           'type' => 'string',
            'label' => 'Name'
        ),
        'nb' => array(
            'type' => 'number',
             'label' => 'nombre',
        )
 ));
 $content_chart =array();
 foreach($results as $index => $result){
    foreach($result as $cle => $value){
                    array_push($content_chart,array("name"=>$cle,"nb"=> (int)$value));
    }
 }
 foreach($content_chart as $row){
     $chart->addRow(array('name' => $row['name'], 'nb' => $row['nb']));
 }
 $this->set(compact('chart'));

My view:
<div id="chart_div">
    <?php $this->GoogleCharts->createJsChart($chart);?>
</div>

I have tester in the GoogleChartsHelper, the $scriptOutput is like this:
$(document).ready(function(){
options_56823e100db90 = chartOptions = {
"width":400,
"height":300,
"title":"Etat statistique du nombre de flux",
"titleTextStyle":{"color":"red"}
};
js_56823e100dc16 = chartData = new google.visualization.arrayToDataTable([
['Name','nombre'],
['encours',852],
['refuse',11],
['valide',13],
['cloture',91],
['total',967]]);
chart_56823e100dcaf = chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart_56823e100dcaf.draw(js_56823e100dc16, options_56823e100db90);});

But this isn't included in the DOM when I see source.
Plugin: enter image description here
Thanks a lot.

A: In your controller, just before $this->set(compact('chart')); do a var_dump($chart); to be sure of what you are sending to the view. This will give you some information as to what the problem is.
Also two things which you didn't mention explicitly:
1 - Have you included App::uses('GoogleCharts', 'GoogleCharts.Lib'); in your controller?
2 - Have you included public $helpers = array('GoogleCharts.GoogleCharts'); in your controller?
These will guide us towards a final solution.


text:
Q: unauthenticated http proxy, wget fails, curl works I'm running a ubuntu 10.04 i386 desktop edition. I have configured the http proxy via the http_proxy variable. When I use wget I get a connection refused but, curl, apt-get etc. work just fine. Any idea what I'm missing here?
$ echo $http_proxy
http://10.0.0.42:8080/
$ export HTTP_PROXY=$http_proxy
$ wget --proxy=on http://www.google.com
--2010-06-24 18:56:53--  http://www.google.com/
Resolving www.google.com... 74.125.95.106, 74.125.95.147, 74.125.95.99, ...
Connecting to www.google.com|74.125.95.106|:80... failed: Connection refused.
Connecting to www.google.com|74.125.95.147|:80... failed: Connection refused.
Connecting to www.google.com|74.125.95.99|:80... failed: Connection refused.
Connecting to www.google.com|74.125.95.103|:80... failed: Connection refused.
Connecting to www.google.com|74.125.95.104|:80... failed: Connection refused.
Connecting to www.google.com|74.125.95.105|:80... failed: Connection refused.
$ curl http://www.google.com
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE>

302 Moved

The document has moved
here.

$

A: After setting http_proxy like so:
export http_proxy="http://proxy.example.com:8080"

Use wget with this flag:
--proxy=on

You can use
--proxy-username="username" --proxy-passwd="password"

to set proxy username and password where required.

A: I've found that some programs use the environment variable http_proxy (lower case), while others use HTTP_PROXY (upper case).  Because it's quicker than looking up which program uses which variable, I tend to set 'em both.

A: Thanks for your help guys. I found the solution with some help from the ever helpful folks at #ubuntu. The problem turned out to be the no_proxy that was set to localhost once I unset it wget worked fine

A: In my case I had problems with the proxy blocking the user agent set by wget. So to solve it, I had to set manually the user-agent option with the one used by curl:
 wget --user-agent="curl/7.47.0" http://host.com

A: I had proxy set up with proper config, but that was preventing me download anything using command line.
So had to off the proxy as below,
wget --proxy=off http://apache.claz.org/flume/1.6.0/apache-flume-1.6.0-bin.tar.gz

A: This happened to me when the wgetrc was configured to use port 443 with https_proxy. Once I used port 80 for http_proxy and https_proxy it worked fine.


text:
Q: How to edit commands in MySQL 8.0 Command Line Client on windows 10 I am looking for a solution where I don't need to use up and down arrow keys for editing commands. Previously, there used to be an edit command that opened an editor for editing. However, now I am finding no such command exist on my installed MySQL latest version. I installed MySQL in developer mode. Help command is not showing any edit or \e command.

A: I never knew the edit command existed up until now and tried it in my 5.7 , with no luck of course. Then I did a bit of research. Taken from mysql reference manual for 8.0: MySQL Shell's \edit command (available from MySQL Shell 8.0.18) opens a command in the default system editor for editing, then presents the edited command in MySQL Shell for execution. So I suppose you were using MySQL shell instead of the run-of-the-mill CLI launched by mysql command (or unlocked it in CLI after installing mysql shell). Please download it from MySQL community. The latest MySQL Shell 8.0.29 will do. Personally, I have not got round to trying mysql shell and probably won't do in the future, as I find workbench is too good to part with.


text:
Q: this inside an async object method I creating an object that uses async function methods with babel-polyfill/babel-preset-es2017, however I am having a problem with this:
let obj = () => {
    return {
        doAsync: async () => {
            let thing = await longProcess()
            return this.transform(thing)
        },

        transform: (thing) => {
            return psuedoCodeTransform(thing)
        }
    }
}

let instance = obj()
instance.doAsync()
// TypeError: cannot read property 'transform' of undefined`.

Is this something described in ES2017, a babel-polyfill/regeneratorRuntime gotcha?

A: Arrow functions do not create their own context. They don't have their own this and this will refer to the enclosing scope's context. In this case (no pun intended), this does not refer to the same object as instance at all.
If you log this inside doAsync, you'll notice it's the window global.

A: Joseph the Dreamer's response is exactly right obviously, but since I work best by example, here is your code changed which should make it work. Notice the only change is actually defining doAsync as a normal function instead of arrow function:
let obj = () => {
    return {
        doAsync: async function() {
            let thing = await longProcess()
            return this.transform(thing)
        },

        transform: (thing) => {
            return psuedoCodeTransform(thing)
        }
    }
}

let instance = obj()
instance.doAsync()
// TypeError: cannot read property 'transform' of undefined`.


text:
Q: Listbox delete item functionality? How to find the item id when deletion of item in listbox?
<DataTemplate x:Key="ToDoListBoxItemTemplate">

            <Grid HorizontalAlignment="Stretch" Width="420">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition  Width="30"/>
                    <ColumnDefinition Width="*" />
                   <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="100" />
                </Grid.ColumnDefinitions>

                <!--<CheckBox
                    IsChecked="{Binding IsComplete, Mode=TwoWay}"
                    Grid.Column="0" VerticalAlignment="Top"/>-->

                <TextBlock
                    Text="{Binding subcategname}"
                    FontSize="25"
                    Grid.Column="1" Grid.ColumnSpan="2"
                    VerticalAlignment="Top" Margin="-36, 12, 0, 0"/>

                <Button
                    Grid.Column="3"
                    x:Name="deleteTaskButton"
                    BorderThickness="0"
                    Margin="0, -18, 0, 0" Click="deleteTaskButton_Click">

                    <Image
                    Source="Images/appbar.delete.rest.png"
                    Height="75"
                    Width="75"/>

                </Button>
            </Grid>
        </DataTemplate>

<ListBox x:Name="FinanceListBox" Margin="0,0,-12,0" ItemsSource="{Binding}"  ItemContainerStyle="{StaticResource ListBoxItemStyle1}" ItemTemplate="{StaticResource ToDoListBoxItemTemplate}"  SelectionChanged="FinanceList_SelectionChanged">
                </ListBox>

in SelectionChanged event i wrote the following code.
private void FinanceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            System.Collections.IList list = e.AddedItems;
            if (e.AddedItems.Count == 1)
            {
                IEnumerable<Category> categs = list.Cast<Category>();
                Category em = categs.ElementAt<Category>(0);
                int id = em.id;
                int categoryid = em.categoryid;
                string subcategoryname = em.subcategname;

                NavigationService.Navigate(new Uri(String.Format("/SubCategories.xaml?id=" + id + "&categoryid=" + categoryid + "&subcategoryname=" + subcategoryname), UriKind.Relative));
            }
        }

 private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
        {

        }

But how to find the particular item id when deleting the item.
How to find the particular id to delete the item?

A: One of the ways is to bind the Tag property of the button to a meaningful identifier, then in your delete method use the following code:

Button b = sender as Button;
//and now delete from your collection where id = b.Tag

A: Apply tag to the button.
<Button
                    Grid.Column="3"
                    x:Name="deleteTaskButton"
                    BorderThickness="0"  Tag="{Binding id}"
                    Margin="0, -18, 0, 0" Click="deleteTaskButton_Click">

In code: as Euqene has mentioned:
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
        {
         Button b = sender as Button;
         var id = (int)b.Tag;
         //now do what you want with id
        }

A: No need to assign a tag to you Button and make your xaml ugly, you can get the DataContext from the button.
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
{
     Button deleteButton = (Button)sender;
     var entity = deleteButton.DataContext as MyEntity;

     //Delete entity
}


text:
Q: How can i create a horizontal scrolling chart in react using rechartjs? I'd like to create a areachart with Rechart.js but having the y-axis fixed position when i scroll.
Whats happening for me is the data gets crumbled, how could i make it scroll-able, i could'nt able to find in the docs also, Any ideas?
Thank you
  const validate = React.useCallback(() => {
    setArr((prevState) =>
      [...prevState, { X: Math.random() >= 0.5 ? 5 : 0 }]
    );
  }, []);

  React.useEffect(() => {
    if (timeoutRef.current !== null) {
      clearTimeout(timeoutRef.current);
    }
    const interval = 6000;
    const speed = 1000;
    for (let i = 0; i < interval; i++) {
      timeoutRef.current = setTimeout(() => {
        timeoutRef.current = null;
        validate();
      }, i * speed);
    }
  }, [validate]);
  return (

{time}

      <AreaChart
        width={730}
        height={250}
        data={arr}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        {/* <CartesianGrid strokeDasharray='3 3' /> */}

        <YAxis />
        <XAxis additive='sum' />
        <Tooltip />
        <Legend />
        <Area
          type='monotone'
          dataKey='X'
          stroke='#8884d8'
          isAnimationActive={false}
          additive='sum'
        />
        <Brush startIndex={0} endIndex={10}>
          <AreaChart>
            <Area dataKey='X' isAnimationActive={false} />
          </AreaChart>
        </Brush>
      </AreaChart>

  );
}


text:
Q: Javascript - Toggle Multiple Classes onclick I am trying to toggle multiple classes onclick using vanilla Javascript. What i am trying to do is when a btn is clicked two classes to toggle with another two classes. I have 5 classes in total which are: .menu_btn , .main_nav, .btn_active, .container, .container_active. When i press the .menu_btn i would like the classes .main_nav to toggle with .btn_active and at the same time i would like to have the .container to toggle with .container_active. The class .container is the only one that has 5 elements of that class, the others are single. I have done this using jQuery but i would like to know the way using vanilla Javascript. Hopefully someone can help.
One thing to point out is when i console.log the .btn_active and .container_active i get back [ ] an empty array. Those 2 css classes are not assigned to any element of my project. They are existing only in the css and their purpose is for toggle.
Thanks
jQuery Code:
$(function(){

   $(".menu_btn").on("click", function(){

       $(".main_nav").toggleClass("btn_active");
       $(".container").toggleClass("container_active");

   });

});

Vanilla Javascript Code:
var menuBtn = document.getElementsByClassName("menu_btn");
var mainNav = document.getElementsByClassName("main_nav");
var btnActive = document.getElementsByClassName("btn_active");
var container = document.getElementsByClassName("container");
var containerActive = document.getElementsByClassName("container_active");

menuBtn.onclick = function(){

    mainNav.classList.toggle(btnActive);
    for ( index = 0; index <= container.lenght -1; index++ ){
        container[index].classList.toggle(containerActive);
    }

};

A: I have modified your script and created a fiddle so you see how it works: https://jsfiddle.net/eyrpdsc2/
The toggle accepts a string as a parameter, not a Node. So you need to pass 'btn_active' instead of btnActive. Also keep in mind that querySelectorAll returns a NodeList (not an array) so you cannot use forEach.
var menuBtn = document.querySelectorAll(".menu_btn");
var mainNav = document.querySelectorAll(".main_nav");
var container = document.querySelectorAll(".container");

for (var i = 0; i < menuBtn.length; ++i) {
    menuBtn[i].addEventListener('click', toggleClasses);
}

function toggleClasses() {
        var i = 0;
    for (i = 0; i < mainNav.length; ++i) {
        mainNav[i].classList.toggle('btn_active');
    }
    for (i = 0; i < container.length; ++i) {
        container[i].classList.toggle('container_active');
    }
}


text:
Q: Displaying an Activity on the Android lock screen I'm trying to figure out how exactly (if it's possible) to replicate the way the camera app works on the Jelly Bean lock screen.
From the lock screen, I can swipe left and the camera app displays, if I swipe right, I have the ability to add widgets.  Would it be possible to provide an activity in such a manner it can be added to the lock screen, or is this only available for the default camera app?

A: It's just another widgetCategory, namely keyguard, which enables widgets to be added to the lock-screen. See the documentation here.
You would define your appwidget-provider xml as follows:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
   ...
   android:widgetCategory="keyguard|home_screen">
</appwidget-provider>


text:
Q: Introduction to the "steps" of a debugger? Step Over, Step In, and Step Out.
I want a better understanding of what to expect when pressing these buttons in a debugger.
There are a lot of language & tool specific debugger entries, but I couldn't find a generic explanation of the feature.

A: Simply put, this is how you advance ("step") through your code via the debugger, one line at a time. Here's an example of using Visual Studio debugger.
Suppose you have the following code:
public static void Main(string[] args)
{
  int x = 4;
  M(x);
}

private static void M(int x)
{
  Console.WriteLine(x);
}

Suppose you put a breakpoint on the M(x) line. When the debugger stops ("breaks"), you now have 3 options:
1. Step Over (F10)
If you press F10, you will step over the line M(x). The debugger will execute this method, but you will not go into it. On the console output, you will see 4.
2. Step Into (F11)
If you press F11, the debugger will take you inside the M() method, allowing you to single-step (with F10 or F11) inside the M() method. If you keep pressing F11, you will enter additional methods (provided you have their source code available)
3. Step Out (Shift-F11)
Instead of single-stepping one line at a time, you can press Shift-F11 to step out of the current method, and return to the calling method. In this case, if you press Shift-F11 while inside the M() method, you will be taken back to the calling Main() method.
I hope this makes it clearer.
P.S. This is not Visual Studio specific, but a general concept of debugging. With the debugger, you always single-step over instructions, be that lines of code or assembly instructions. Step over/in/out are concepts you will find in every debugger, and they all mean the same thing.
There are additional things some debuggers allow you to do, such as Run to selected line. Here's more info about Visual Studio debugging capabilities: http://msdn.microsoft.com/en-us/library/y740d9d3.aspx

A: This will be IDE specific, so your question is targeted as being too broad.
But in general, this is what these terms mean.
When debugging code, if the current line is the call to a function, let's call it M(y).
If you Step In, then the debugger will start stepping into the function M(y).
If you chose Step Over, then the function M(y) will be executed and the debugger will stop at the next line after the call of the function M(y).
Step Out only works if you are already inside of M(y). Let's say you are in the middle of M(y) and you realize the bug is not there, and you'd like to continue on the first line of code after the call to M(y). That's when you pick Step Out.
Again, this will vary from IDE to IDE, but on my experience (more than 11 IDEs) this is the standard behaviour.


text:
Q: Filter between two input dates on html table - Java script I'm trying to filter on my html table by inputting two dates(From and To) and then it should filter the data in the html table column[0] "Date Column" accordingly.
The inputs on my page::
<input type="date" id="date-start" onselect="searchDate()" />
<input type="date" id="date-stop" onselect="searchDate()" />
The java script I have together so far is:
    function searchDate() {
        var input_startDate, input_stopDate, table, tr, i;
        input_startDate = document.getElementById("date-start");
        input_stopDate = document.getElementById("date-stop");
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i
= input_startDate && td_name <= input_stopDate) {
                    ??? - Display Rows;
                }
                else {
                    ??? - Hide Rows;
                }
            }
        }
    }

I know this might be pretty straight forward but I have no idea what to do as I can't seem to get it working.
My table gets created as follows:
        @if (employees is null)
    {

Loading . . .

    }
    else
    {

                    Entry Date
                    Employee

                @foreach (var employee in employees)
                {

                        @employee.EntryDate
                        @employee.POI

                }

    }

Any help would be appreciated.
Database format is: 2020-06-05 10:57:10
Thanks.

A: You can use style.display to hide/show your rows. Set it to 'none' to hide the rows or 'block' to view them.
function searchDate() {
    var input_startDate, input_stopDate, table, tr, i;
    input_startDate = document.getElementById("date-start");
    input_stopDate = document.getElementById("date-stop");
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i
= input_startDate && td_name <= input_stopDate) {
                tr[i].style.display = "block";
            }
            else {
                tr[i].style.display = "none";
            }
        }
    }
}

A: You have multiple issues in the sample:

*

*you are not getting the actual values from the table td cells or
inputs

*you need to convert the values to dates to compare
correctly

*you can then hide/show a row by setting the display
property on the style

See the commented demo below:

function searchDate() {
  var input_startDate, input_stopDate, table, tr, i;

  // get the values and convert to date
  input_startDate = new Date(document.getElementById("date-start").value);
  input_stopDate = new Date(document.getElementById("date-stop").value);

  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  for (i = 0; i
= input_startDate && td_date <= input_stopDate) {
        // show the row by setting the display property
        tr[i].style.display = 'table-row;';
      } else {
        // hide the row by setting the display property
        tr[i].style.display = 'none';
      }
    }

  }
}

function searchDateAlternative() {
  // get the values and convert to date
  const input_startDate = new Date(document.getElementById("date-start").value);
  const input_stopDate = new Date(document.getElementById("date-stop").value);

  // only process table body rows, ignoring footer/headers
  const tr = document.querySelectorAll("#myTable tbody tr")

  for (let i = 0; i
= input_startDate && td_date <= input_stopDate) {
        // show the row by setting the display property
        tr[i].style.display = 'table-row;';
      } else {
        // hide the row by setting the display property
        tr[i].style.display = 'none';
      }
    }

  }
}
#myTable td {
 border: 1px solid;
 border-collapse: collapse;
}
<input id="date-start" type="text" value="2020-01-01"></input>
<input id="date-stop" type="text" value="2020-01-02"></input>
<button type="button" onclick="searchDateAlternative()">Go</button>

      Date
      Name

      2020-01-01
      Foo

      2020-01-02
      Bar

      2020-01-03
      Baz


text:
Q: Как получить значения ключа в вложенном словаре? Хочу спарсить все ссылки изображений из поста инстаграм,понял где можно найти их,этим местом оказался вложенный словарь,как его перебрать я не знаю
Вот код
import requests
import json
from bs4 import BeautifulSoup as BS
import re

url = 'https://www.instagram.com/p/B5n2EXjF_1C/'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
JS_SHARED_DATA_PATTERN = re.compile('window._sharedData = ({.+});')

r = requests.get(url, headers=headers, allow_redirects=True)

soup = BS(r.content, 'html.parser')
script = soup.find('script', attrs={'type':"text/javascript"}, text=JS_SHARED_DATA_PATTERN)
m = JS_SHARED_DATA_PATTERN.search(script.text)
shared_data_text = m.group(1)
data = json.loads(shared_data_text)
print(data)

Если что,нужно получить информацию по ключу 'display_url'
Извините сразу,я только учусь это делать,если я задаю банальный или глупый вопрос

A: import requests
import json
from bs4 import BeautifulSoup as BS

url = 'https://www.instagram.com/p/B5n2EXjF_1C/'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
JS_SHARED_DATA_PATTERN = re.compile('window._sharedData = ({.+});')

r = requests.get(url, headers=headers, allow_redirects=True)

soup = BS(r.content, 'html.parser')
script = soup.find(
    'script', attrs={'type': "text/javascript"}, text=JS_SHARED_DATA_PATTERN)
m = JS_SHARED_DATA_PATTERN.search(script.text)
shared_data_text = m.group(1)
data = json.loads(shared_data_text)
array = data['entry_data']['PostPage'][0]['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']

result = {}

for i, img in enumerate(array):
    result[i] = img['node']['display_url']

print(result)


text:
Q: prove point series generation using exact line search method I have a function as:
min $f(x_1,x_2) = x_1^2 +2x_2^2$ where $x_0 = (2,1)^T$
Using steepest descent we compute $x_{k+1}$ as:
$x_{k+1} = x_k + \alpha*p_k$ where:
$p_k = -\nabla f(x_k)$ and $\alpha = - \frac{\nabla f(x_k)^Tp_k}{p_k^TQp_k}$
Here Q is simply the hessian given by:
$Q = (\begin{array}{cc} 2&0 \\ 0 & 4\end{array})$
Now the book states the points $x_k$ are given by the following sequence given the starting point $x_0$ as $x_k = \frac{1}{3}^k (\frac{2}{(-1)^k})$
Clearly this is correct given at k=0 $x_0 = (2,1)^T$.
However I have no idea how they derive this geometric seq

A: Thinking about this some more the answer is very simple, I'll prove for $x_1=2$
based on the starting point $\alpha$ is always $1/3$ and thus:
$x_1 = x_0 - 2\alpha x_0 \ni \alpha = 1/3$
$\implies x_1 = 1/3 *x_0$
$\implies x_2 = 1/3*x_1 \implies 1/3*1/3*x_0$
This implies the variable $(x_1)_k = 2*\frac{1}{3}^k$


text:
Q: What are the advantage of AIDL in android? What are the advantage and where we can use that.
   Which type of apps we can build using AIDL.
   please help to explain this.

A: AIDL basically used for communication between two process either in same android application or may be different android application as well. This is the tool used for process communication, you can think it like a programming interface between client and server.Basically this is android technique, you can do same thing in different way as well but android provides it's own  tool to make it done. Practical example you may consider like if you have two integers to get those multiply then those two variables will be multiplied and stored somewhere, this whole process is single one process and now you can use this process in another process for output or response purpose. And processes have different memory location, so this is the best option for process communication.


text:
Q: How to show that $ \int_1^{+\infty} \frac{\sin \frac{1}{x}}{x^a} \mathrm{d}x$ is not integrable? I wonder how to show that $$ \int_1^{+\infty} \frac{\sin \frac{1}{x}}{x^a} \mathrm{d}x$$ is not Lebesgue-integrable, where $a<1$.
Thanks in advance!

A: Hint:
$$
\begin{align}
\int_1^\infty\frac{\sin\left(\frac1x\right)}{x^a}\,\mathrm{d}x
&=\int_0^1\sin(x)\,x^{a-2}\,\mathrm{d}x\\
&=\int_0^1\frac{\sin(x)}x\,x^{a-1}\,\mathrm{d}x
\end{align}
$$


text:
Q: Remove Empty XML Elements - Python I am attempting to remove empty XML elements from an XML, but having an issue with the elements that have attributes but no text values. I can successfully remove the empty XML elements, but cannot preserve the elements with attributes in the final XML.  I would like to essentially clean up the XML and remove empty nodes with no text values altogether, but keep the nodes with attributes.
Below is the script I am using, along with the input and (desired) output XMLs....any assistance is most appreciated!
The Script:
from lxml import etree
import os

path = "C:\\users\\mdl518\\Desktop\\"

### Removing empty XML elements
tree = etree.parse(os.path.join(path,"my_file.xml"))

for elem in tree.xpath('//*[not(node())]'):
   elem.getparent().remove(elem):

with open(".//new_file.xml","wb") as f:
    f.write(etree.tostring(tree, xml_declaration=True, encoding='utf-8')) ## Removes empty XML elements, including the elements with attributes

Input XML:
<?xml version='1.0' encoding='utf-8'?>
<nas:metadata xmlns:nas="http://www.arcgis.com/schema/nas/base"
xmlns:mcc="http://standards.org/iso/19115/-3/mcc/1.0"
xmlns:mdl="http://standards.org/iso/19115/-3/mdl/1.0"
xmlns:mnl="http://standards.org/iso/19115/-3/mnl/1.0">
xmlns:lan="http://standards.org/iso/19115/-3/lan/1.0">
xmlns:lis="http://standards.org/iso/19115/-3/lis/1.0">
xmlns:gam="http://standards.org/iso/19115/-3/gam/1.0">

  <mdl:metadataIdentifier>
    <mcc:MD_Identifier>
        <mnl:type>
          <gam:String>The Metadata File</gam:String>
        </mnl:type>
          <mnl:description codeList="http://arcgis.com/codelist/ScopeCode" codeListValue="dataset"/>
         <mnl:address>
          <mnl:defaultLocale>
          </mnl:defaultLocale>
         </mnl:address>
         <lan:language>
           <lan:type>
             <lis:name>English</lis:name>
           </lan:type>
          </lan:language>
      </mcc:MD_Identifier>
      <mcc:contactInfo>
        <mdl:POC>
          <mnl:name>
            <lis:person>Tom</lis:person>
          </mnl:name>
          <mnl:age>
          </mnl:age>
          <mnl:status>
          </mnl:status>
        </mdl:POC>
      </mcc:contactInfo>
    </mdl:metadataIdentifier>
 </nas:metadata>

Output XML:
<?xml version='1.0' encoding='utf-8'?>
<nas:metadata xmlns:nas="http://www.arcgis.com/schema/nas/base"
xmlns:mcc="http://standards.org/iso/19115/-3/mcc/1.0"
xmlns:mdl="http://standards.org/iso/19115/-3/mdl/1.0"
xmlns:mnl="http://standards.org/iso/19115/-3/mnl/1.0">
xmlns:lan="http://standards.org/iso/19115/-3/lan/1.0">
xmlns:lis="http://standards.org/iso/19115/-3/lis/1.0">
xmlns:gam="http://standards.org/iso/19115/-3/gam/1.0">

  <mdl:metadataIdentifier>
    <mcc:MD_Identifier>
        <mnl:type>
          <gam:String>The Metadata File</gam:String>
        </mnl:type>
        <mnl:description codeList="http://arcgis.com/codelist/ScopeCode" codeListValue="dataset"/>
      <lan:language>
        <lan:type>
          <lis:name>English</lis:name>
        </lan:type>
       </lan:language>
     </mcc:MD_Identifier>
     <mcc:contactInfo>
       <mdl:POC>
         <mnl:name>
           <lis:person>Tom</lis:person>
         </mnl:name>
       </mdl:POC>
     </mcc:contactInfo>
   </mdl:metadataIdentifier>
 </nas:metadata>

A: The xml is your question is not well formed, but assuming that's fixed, try changing this line
for elem in tree.xpath('//*[not(node())]'):

to this:
for elem in tree.xpath('//*[not(node())][not(count(./@*))>0]'):

and see if it works.
Edit:
The edited XML in the question still isn't well formed. I tried to fix it and then applied the following:
xml_str = """<?xml version='1.0' encoding='utf-8'?>
<nas:metadata xmlns:nas="http://www.arcgis.com/schema/nas/base"
xmlns:mcc="http://standards.org/iso/19115/-3/mcc/1.0"
xmlns:mdl="http://standards.org/iso/19115/-3/mdl/1.0"
xmlns:mnl="http://standards.org/iso/19115/-3/mnl/1.0"
xmlns:lan="http://standards.org/iso/19115/-3/lan/1.0"
xmlns:lis="http://standards.org/iso/19115/-3/lis/1.0"
xmlns:gam="http://standards.org/iso/19115/-3/gam/1.0">

  <mdl:metadataIdentifier>
    <mcc:MD_Identifier>
        <mnl:type>
          <gam:String>The Metadata File</gam:String>
        </mnl:type>
          <mnl:description codeList="http://arcgis.com/codelist/ScopeCode" codeListValue="dataset"/>
         <mnl:address>
          <mnl:defaultLocale>
          </mnl:defaultLocale>
         </mnl:address>
         <lan:language>
           <lan:type>
             <lis:name>English</lis:name>
           </lan:type>
          </lan:language>
      </mcc:MD_Identifier>
      <mcc:contactInfo>
        <mdl:POC>
          <mnl:name>
            <lis:person>Tom</lis:person>
          </mnl:name>
          <mnl:age>
          </mnl:age>
          <mnl:status>
          </mnl:status>
        </mdl:POC>
      </mcc:contactInfo>
    </mdl:metadataIdentifier>
 </nas:metadata>

"""
doc = etree.XML(xml_str.encode())
for elem in doc.xpath('//*[not(count(./@*))>0][not(normalize-space(.))]'):
    elem.getparent().remove(elem)
print(etree.tostring(doc, xml_declaration=True, encoding='utf-8').decode())

The output I get from the above is the desired output in the question.


text:
Q: jquery ajax passing more than one parameter I am trying to pass two request parameters by ajax using jquery. The following is what I do:
function querySummary(){
$.ajax({
    type:"POST",
    url:"internalSummary.action",
    data:{starttime:$("#starttime").val(),endtime:${"#endtime"}.val()},
    success: function(data) {
        $("#hello").html( data );
    }
});

}
I am trying to pass starttime and endtime two parameters, but get
Uncaught SyntaxError: Unexpected token ILLEGAL

Can anyone give some suggestions on how to solve this?
Thanks alot!

A: You're using curly braces instead of parentheses on the second jquery select.  data should be as follows:
{starttime:$("#starttime").val(),endtime:$("#endtime").val()}

The names of the values can be quoted or unquoted; javascript assumes they are names and not variables.


text:
Q: Can we install an Adobe AIR application on Microsoft Surface Hub We have a rich interactive application build on Adobe AIR platform which runs on Windows 10. We want to make this available on our Microsoft Surface Hub with minimal changes?
I couldn't find any related information in internet.

A: Dos Microsoft Hub run on Windows 10? Please share a bit more info so I can help.
If it does, then the app should run without issues. If it doesn't but it comes with a Windows Store, then you can change your AIR app to be added in Windows Store and download from there.


text:
Q: SQL LIKE for partial sentence value I have a database (change) which I am trying to create an sql report on the detail field value. The issue is that the detail value displays a "phrase" and I need to evaluate based on this phrase, or a part of it.
SQL
SELECT *
FROM change
WHERE change.detail LIKE '%To: [Step Two]%'

I want it to display all of the values where detail contains "To: [1. Step Two]" but the result is consistently not returning anything, where there are table values for this. Following is an example of the full value of the detail field:
"[Step] Changed From: [1. Step One] To: [1. Step Two]"
The items in [] represent other values in the database as well

A: If this is Microsoft SQL Server then you can escape brackets:
SELECT *
FROM change
WHERE change.detail LIKE '%To: \[Step Two\]%' ESCAPE '\'

Brackets used LIKE clause stand for a character range, So [Step Two] matches a character after To: that is either S,t,E,p, ,w, or o.
You can read about this on MSDN.

A: Presuming you're using SQL Server/TSQL, the problem you have is that the square bracket characters have a special meaning:

[ ] Any single character within the specified range ([a-f]) or set
  ([abcdef]).
WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with
  arsen and starting with any single character between C and P, for
  example Carsen, Larsen, Karsen, and so on. In range searches, the
  characters included in the range may vary depending on the sorting
  rules of the collation.

In order to literally match the square bracket characters, you need to escape them:
LIKE '%To: \[Step Two\]%' ESCAPE '\'

A: Part of the problem is the square brackets introduce character constants.  Here is one solution:
where change.detail like '%To:  ___Step Two_%'

This just takes the risk that the square brackets are really needed for the match.
where change.detail like '%To:  __[[]Step Two]%'

An alternative is to escape those characters:
where change.detail like '%To:  __![Step Two!]%' escape '!'


text:
Q: How to wait for Windows TCP Network at startup? I know this should be obvious, but I have found far too many DIFFERENT answers and the ones I've tried all fail (sometimes or all the time), so...
We are working on a service and some applications that run at startup on a Windows 10 computer that performs an automatic login.  The service and applications require Windows sockets for TCP, UDP and Multicast.  Most of the time, our programs fail because they get errors about the network not being ready and such.  Currently, we work around this by just adding a dumb, fixed length delay time before attempting to start, but we would prefer to start as soon at the network is ready to be used.
Our most recent attempt was to wait on the LanmanWorkstation (Workstation) service, but that generally reports it is running/ready before the sockets functions will succeed.  I have also seen suggestions to use LanmanServer (Server) or Netman (Network Connections) or maybe even Tcpip (TCP/IP Protocol Driver), but I cannot find anything definitive.  One would think this is a common requirement, so why would Microsoft make the info so difficult to find?
Ahem.  Does any know a definitive method for a service or application to wait until winsock functions will succeed before using them?  Short of a spin wait on a failing winsock function, of course!


text:
Q: update 3 columns in 1 uppdate I'm writing a query to update a table. The table has many fields among which there are 3 fields: column1, column2, column3 each of which can be null.
The data is loaded every day. On day 1 a row can come in which
column1 is null,
column2 is not null
column3 is null.
The next day there may be a row where
column1 is not null,
column2 is null,
column3 is null.
The idea is to insert new rows, and those rows which are identical to previously uploaded ones, but which column1, column2, column3 change are not inserted, but updated.
I tried to write a query to update all three fields at once. But in case described above, I will change not null to null.
Does anyone know a way to update any of the fields in a single update query without writing null there?
for example:
update table2 upt
set column1 = n.column1,
    column2 = n.column2,
    column3 = n.column3
from (select new.column1, new.column2, new.column3, new.column4, new.column5
      from table1 new
      where new.column4 in (select old.column4 from table2 old
                            where old.column5 = new.column5
                            and (old.column1 is null or old.column2 is null or old.column3 is null)
      and (new.column1 is not null or new.column2 is not null and new.column3 is not null) n
where upt.date_fielad = '2022-01-01'
and upt.column4 = n.column4
and upt.column5 = n.column5
and (upt.column1 <> n.column1
     or upt.column2 <> n.column2
     or upt.column3 <> n.column3)

How I can change this query to not update not null fields null?


text:
Q: How to format a string as Vietnamese currency? If I set Format in [Region and Language] to US...
CultureInfo cul = CultureInfo.CurrentCulture;
string decimalSep = cul.NumberFormat.CurrencyDecimalSeparator;//decimalSep ='.'
string groupSep = cul.NumberFormat.CurrencyGroupSeparator;//groupSep=','
sFormat = string.Format("#{0}###", groupSep);
string a = double.Parse(12345).ToString(sFormat);

The result is: 12,345 (is correct)
But if I set the format in [Region and Language] to VietNam, then the result is: 12345
The result should be 12.345.
Can you help me? Thanks.

A: You are helping too much.  The format specifier is culture insensitive, you always use a comma to indicate where the grouping character goes.  Which is then substituted by the actual grouping character when the string is formatted.
This formats correctly:
        CultureInfo cul = CultureInfo.GetCultureInfo("vi-VN");   // try with "en-US"
        string a = double.Parse("12345").ToString("#,###", cul.NumberFormat);

You should actually use "#,#" to ensure it still works in cultures that have a uncommon grouping.  It wasn't clear from the question whether that mattered or not so I punted for "#,###"

A: Try something like this:
var value = 8012.34m;
var info = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
Console.WriteLine(String.Format(info, "{0:c}", value));

The result is:
8.012,34 ₫

Oh, and with the value 12345 the result is 12.345,00 ₫.


text:
Q: How can I elegantly combine resource and exception handling?

I'm writing a Clojure wrapper for an object-oriented API that heavily involves resource handling. For instance, for the Foo object, I've written three basic functions: foo?, which returns true iff something is a Foo; create-foo, which attempts to obtain the resources to create a Foo, then returns a map containing a return code and (if the construction succeeded) the newly created Foo; and destroy-foo, which takes a Foo and releases its resources. Here are some stubs for those three functions:
(def foo? (comp boolean #{:placeholder}))

(defn create-foo []
  (let [result (rand-nth [::success ::bar-too-full ::baz-not-available])]
    (merge {::result result}
           (when (= ::success result)
             {::foo :placeholder}))))

(defn destroy-foo [foo] {:pre [(foo? foo)]} nil)

Obviously, every time create-foo is called and succeeds, destroy-foo must be called with the returned Foo. Here's a simple example that doesn't use any custom macros:
(let [{:keys [::result ::foo]} (create-foo)]
  (if (= ::success result)
    (try
      (println "Got a Foo:")
      (prn foo)
      (finally
        (destroy-foo foo)))
    (do
      (println "Got an error:")
      (prn result))))

There's a lot of boilerplate here: the try-finally-destroy-foo construct must be present to ensure that all Foo resources are released, and the (= ::success result) test must be present to ensure that nothing gets run assuming a Foo when there is no Foo.
Some of that boilerplate can be eliminated by a with-foo macro, similar to the with-open macro in clojure.core:
(defmacro with-foo [bindings & body]
  {:pre [(vector? bindings)
         (= 2 (count bindings))
         (symbol? (bindings 0))]}
  `(let ~bindings
     (try
       ~@body
       (finally
         (destroy-foo ~(bindings 0))))))

While this does help somewhat, it doesn't do anything about the (= ::success result) boilerplate, and now two separate binding forms are required to achieve the desired result:
(let [{:keys [::result] :as m} (create-foo)]
  (if (= ::success result)
    (with-foo [foo (::foo m)]
      (println "Got a Foo:")
      (prn foo))
    (do
      (println "Got an error:")
      (prn result))))

I simply can't figure out a good way to handle this. I mean, I could complect the behaviors of if-let and with-foo into some sort of if-with-foo macro:
(defmacro if-with-foo [bindings then else]
  {:pre [(vector? bindings)
         (= 2 (count bindings))]}
  `(let [{result# ::result foo# ::foo :as m#} ~(bindings 1)
         ~(bindings 0) m#]
     (if (= ::success result#)
       (try
         ~then
         (finally
           (destroy-foo foo#)))
       ~else)))

This does eliminate even more boilerplate:
(if-with-foo [{:keys [::result ::foo]} (create-foo)]
  (do
    (println "Got a Foo:")
    (prn foo))
  (do
    (println "Got a result:")
    (prn result)))

However, I don't like this if-with-foo macro for several reasons:

*

*it's very tightly coupled to the specific structure of the map returned by create-foo

*unlike if-let, it causes all bindings to be in scope in both branches

*its ugly name reflects its ugly complexity

Are these macros the best I can do here? Or is there a more elegant way to handle resource handling with possible resource obtainment failure? Perhaps this is a job for monads; I don't have enough experience with monads to know whether they would be useful tool here.

A: I'd add an error-handler to with-foo. This way the macro has a focus on what should be done. However, this simplifies the code only when all error-cases are treated by a handful of error handlers. If you have to define a custom error-handler every time you call with-foo this solution makes readability worse than an if-else construct.
I added copy-to-map. copy-to-map should copy all relevant information from the object to a map. This way the user of the macro doesn't by accident return the foo-object, since it gets destroyed inside the macro
(defn foo? [foo]
  (= ::success (:result foo)))

(defn create-foo [param-one param-two]
  (rand-nth (map #(merge {:obj :foo-obj :result %} {:params [param-one param-two]})
                 [::success ::bar-too-full ::baz-not-available])))

(defn destroy-foo [foo]
      nil)

(defn err-handler [foo]
      [:error foo])

(defn copy-to-map [foo]
      ;; pseudo code here
      (into {} foo))

(defmacro with-foo [[f-sym foo-params & {:keys [on-error]}] & body]
  `(let [foo# (apply ~create-foo [~@foo-params])
         ~f-sym (copy-to-map foo#)]
     (if (foo? foo#)
       (try ~@body
            (finally (destroy-foo foo#)))
       (when ~on-error
         (apply ~on-error [~f-sym])))))

Now you call it
(with-foo [f [:param-one :param-two] :on-error err-handler]
    [:success (str "i made it: " f)])

A: Building from @murphy's excellent idea to put the error handler into with-foo's bindings to keep the focus on the normal case, I've ended up with a solution that I like quite a lot:
(defmacro with-foo [bindings & body]
  {:pre [(vector? bindings)
         (even? (count bindings))]}
  (if-let [[sym init temp error] (not-empty bindings)]
    (let [error? (= :error temp)]
      `(let [{result# ::result foo# ::foo :as m#} ~init]
         (if (contains? m# ::foo)
           (try
             (let [~sym foo#]
               (with-foo ~(subvec bindings (if error? 4 2))
                 ~@body))
             (finally
               (destroy-foo foo#)))
           (let [f# ~(if error? error `(constantly nil))]
             (f# result#)))))
    `(do
       ~@body)))

*

*like my if-with-foo macro in the question, this with-foo macro is still tied to the structure returned by create-foo; unlike my if-with-foo macro and @murphy's with-foo macro, it eliminates the need for the user to manually take apart that structure

*all names are properly scoped; the user's sym is only bound in the main body, not in the :error handler, and conversely, the ::result is only bound in the :error handler, not in the main body

*like @murphy's solution, this macro has a nice, fitting name, instead of something ugly like if-with-foo

*unlike @murphy's with-foo macro, this with-foo macro allows the user to provide any init value, rather than forcing a call to create-foo, and doesn't transform the returned value

The most basic use case simply binds a symbol to a Foo returned by create-foo in some body, returning nil if the construction fails:
(with-foo [foo (create-foo)]
  ["Got a Foo!" foo])

To handle the exceptional case, an :error handler can be added to the binding:
(with-foo [foo (create-foo)
           :error (partial vector "Got an error!")]
  ["Got a Foo!" foo])

Any number of Foo bindings can be used:
(with-foo [foo1 (create-foo)
           foo2 (create-foo)]
  ["Got some Foos!" foo1 foo2])

Each binding can have its own :error handler; any missing error handlers are replaced with (constantly nil):
(with-foo [foo1 (create-foo)
           :error (partial vector "Got an error!")
           foo2 (create-foo)]
  ["Got some Foos!" foo1 foo2])


text:
Q: React.js -- state not updating in functional component I have a functional component with a state hook called "checked" that is an array of Booleans for a list of checkboxes. When a checkbox is clicked, I have an event handler that updates state so the checkbox will render a check or an empty box.
According to the console.logs in my function, state is updating, but the checkboxes are not responsive in the browser and dev tools confirm that state is not updating. If I manually toggle state using the dev tools the checkboxes work just fine, so I believe it's an issue with state not updating. Any advice would be very appreciated!
import React, { useState, useContext } from 'react';

export default function MessengerCheckboxes() {
 const [checked, setChecked] = useState([false, false, false]);

...

 const handleChangeChild = (event) => {
   console.log('Currently state is: ' + checked); // Currently state is: [false, false, false]

   let index = parseInt(event.target.id.slice(0, 1));
   let localChecked = checked; //
   localChecked[index] = !checked[index];

   console.log('State should be: ' + localChecked); //State should be: [true, false, false] [[for example]]
   setChecked(localChecked);

   setTimeout(() => { // Added setTimeout for troubleshooting to make sure I wasn't calling state too quickly after setting it
       console.log('State is now: ' + checked); // State is now: [true, false, false] [[but won't trigger re-render and dev tools show state is [false, false, false]]
   }, 1 * 1000);
 };
}

Image of my console.log
Image of my dev tools

A: you shouldn't update state like that.
In situations like this, a bit more complex state object is required. I like to use an object to keep state for each item in the list.
Check this link: https://codesandbox.io/s/checkbox-state-https-stackoverflow-com-questions-69680938-react-js-state-not-updating-in-functional-component-di0dd
import "./styles.css";
import { useState } from "react";

export default function App() {
  // 1.
  const stateObj = {
    cb1: false,
    cb2: false,
    cb3: false
  };
  const [cbState, setCbState] = useState(stateObj);
  const handleCb = (event) => {
    console.log(event.target.name, event.target.checked);
    // 4.
    setCbState({ ...cbState, [event.target.name]: event.target.checked });
  };
  return (
    <div>
      <input
        type="checkbox"
        name="cb1" // 2.
        onChange={handleCb}
        value={cbState["cb1"]} // 3.
      />
      <input
        type="checkbox"
        name="cb2"
        onChange={handleCb}
        value={cbState["cb2"]}
      />
      <input
        type="checkbox"
        name="cb3"
        onChange={handleCb}
        value={cbState["cb3"]}
      />
    </div>
  );
}

So for take away, in steps:

*

*create/prepare state object - keys will be used as names to html elements

*set name attribute for html element - use same keys from 1.

*set value attribute for html element - bracket notation using state['key']. This is how you achieve controlled components

*set state in a way that you persist existing data/values (using spread operator) + update (bracket notation for accessing the properties). In this example we achieve it with event name and checked attributes.

A: Well you'd have read the comments that you shouldn't mutate the state. So to handle such situations, I usually to do like this:-

setChecked(data => ({
      ...data,
      [ind]: !checked[ind]
}))

P.S. - Do read about different approaches of handling states, it's gonna help you alot in the longer run. :)


text:
Q: Maximising battery longevity: when to charge I have a question that came to me with my new M1 MBP, running Monterey 12.5
The laptop warns me I need to plug in at 10%.  My previous laptop, a late 2013 MBP with Mojave, warned me at 5%.  Once upon a time I was told by a friend that is an electronic engineer to recharge a battery as late as possible (say 1% of charge remaining), but that was a long time ago, and said advice might not apply to modern (2022) batteries.  In any case, I used that advice (drain the battery as much as you can) for the old laptop, and it still managed about 1 hour of netflix streaming unplugged by the end of its life..
So, what is the best 'remaining charge' level to aim for before plugging in to maximise battery longevity?

A: Strictly speaking the "best" remaining charge level to reach before plugging in to maximize battery longevity would be around 40%, and then charging it up to about 50% or 60%.
This isn't really practical however, and the actual benefits become less noticable the closer to 50% you keep your charge level.
Keeping the charge level between 20% to 80% will significantly increase the number of useful charge cycles you get from a lithium battery.

Once upon a time I was told by a friend that is an electronic engineer to recharge a battery as late as possible (say 1% of charge remaining)

This would apply to nickel-cadmium chemistry batteries, which haven't  been used widely in laptops for a couple of decades.
Side note: Apple often over reports charge levels by a few %. When you take your laptop off charge from full it will report as 100% for a few minutes so when you see 99% charge level reported that's likely to be closer to 96% actual charge.


text:
Q: How many cups/tablespoons are in x% of a quart? I'm wanting to find an equation for calculating how many cups or tablespoons are in a certain percentage of a quart.
Example question to be solved with the equation: How many cups are in 10% of a quart?
I know there are four cups in a quart. A cup is 25% of a quart.

Thoughts after accepting an answer—
I got some good answers. I like the equation 0.01xn (or x% of n), derived from some of those answers, where 0.01x is the percentage, and n is the number of units in the other kind of unit (e.g. the number of cups that can fit in a quart or the number of tablespoons that can fit in a gallon). So, if you want to know how many tablespoons are in 7% of a quart, you can do 0.01*7*64. (There are 64 tablespoons in a quart.) So, there are 4.48 tablespoons in 7% of a quart. So, just convert the quart to tablespoons, cups, etc., and take the percentage of that. Kind of obvious when you really think about it.
Anyway, in practice, this Q/A will be helpful for people wanting to lacto-ferment pickles/etc. with a certain percent salt solution (different people suggest a different percent); also, for people wanting to know how much sugar to add to make vinegar (I read that a 10% sugar solution is good); also, for people wanting to mix fertilizer in the right amounts—and so forth. Some fertilizers won't tell you how many tablespoons to add per quart, but they might tell you a percentage, or some other measure. Anyway, there are broad applications, so I figured I'd ask on the Math StackExchange site instead of Gardening/Landscaping or Cooking.

A: Since 1 quart equals 64 tablespoons (which I looked up just to be sure), you have that the volume in tablespoons of $x\%$ of 1 quart equals $$64\cdot x\% = \frac{64x}{100} = \frac{16x}{25} = 0.64x$$

A: Hint:
If $4$ cups equals $100\%$ of a quart, then since they are proportional to each other, you have to divide both sides by $k$ so that the right-hand side is $10\%$.
Can you find what $k$ is?

A: First off, ditch the $\%$, if you can. They will distract you. $25\%$ of a quart means $0.25$ quarts, and $10\%$ of a quart means $0.1$ quarts.
You say in your post that
$$
1\text{ quart} = 4\text{ cup}
$$
is something you already know. Here is a great tip that, if you utilise it correctly, will help you in any converting problem you will ever face: Those units in the equation up there ($\text{quart}$ and $\text{cup}$), and any other unit, behaves algebraically just like a single letter. That means you can manipulate expressions that use those words the same way you can any $x$ or $a$ or $n$ you have ever come across. (Just be careful that if you stop midway through a calculation and try to understand what an intermediary expression says, it's not always easy.)
So, by manipulating our equation above, we get
$$
1 = 4\frac{\text{cup}}{\text{quart}}
$$
(Don't simplify away the $\text u$ here; it is the entire word as one that behaves like an algebraic letter and may be simplified if possible.) As you probably know, multiplying by $1$ doesn't change the value of anything. The last equation here says that $1$ and $4\frac{\text{cup}}{\text{quart}}$ are exactly the same thing. That means that multiplying by $4\frac{\text{cup}}{\text{quart}}$ doesn't change the value of anything.
Now you are ready to face your problem. You have $0.1\text{ quart}$. That is the same as $1\cdot 0.1\text{ quart}$. As per the above, this is the same as $4\frac{\text{cup}}{\text{quart}}\cdot 0.1\text{ quart}$. Here we can simplify: $\text{quart}$ disappears, and we're left with $4\text{ cup}\cdot 0.1 = 0.4\text{ cup}$.
So we have gone from $0.1\text{ quart}$ to $0.4\text{ cup}$ by only using operations that do not change the value of the expression (multiply by $1$, substitute one part for something which is equal, fraction simplification and finally carrying out the multiplication $4\cdot 0.1$ to get $0.4$). That means that the two must be equal, and we have our answer.
Now, this might seem like a lot of work, but if you do it like this, most of it will be in your head. The solution, as done here, but written on a test, might look something more like this:

We have $$
1\text{ quart} = 4\text{ cup}\\
1 = 4\frac{\text{cup}}{\text{quart}}
$$
  Therefore
  $$
0.1\text{ quart} = 4\frac{\text{cup}}{\text{quart}}\cdot 0.1\text{ quart}\\
= 4\text{ cup}\cdot 0.1 = 0.4\text{ cup}
$$


text:
Q: XSD Unique Constraint of elements in different sequences I have follow xsd Schema file:
   <?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xsd:element name="Config">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Modul">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element maxOccurs="unbounded" name="Content1">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element maxOccurs="unbounded" name="Content2">
                      <xsd:complexType>
                        <xsd:sequence>
                          <xsd:element name="AttributeType1">
                            <xsd:complexType>
                              <xsd:attribute name="X" type="xsd:double" use="required" />
                            </xsd:complexType>
                          </xsd:element>
                          <xsd:element name="AttributeType1">
                            <xsd:complexType>
                              <xsd:attribute name="X" type="xsd:double" use="required" />
                            </xsd:complexType>
                          </xsd:element>
                        </xsd:sequence>
                        <xsd:attribute name="Name" type="xsd:string" use="required" />
                      </xsd:complexType>
                    </xsd:element>
                  </xsd:sequence>
                  <xsd:attribute name="Name" type="xsd:string" use="required" />
                </xsd:complexType>
                <xsd:unique name="Content2NameUniqueKey">
                  <xsd:selector xpath="Content2" />
                  <xsd:field xpath="@Name" />
               </xsd:unique>
              </xsd:element>
            </xsd:sequence>
            <xsd:attribute name="Name" type="xsd:string" use="required" />
           </xsd:complexType>
          <xsd:unique name="Content1NameUniqueKey">
            <xsd:selector xpath="Content1" />
            <xsd:field xpath="@Name" />
          </xsd:unique>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xs:schema>

With the unique constraints I can check if the content1 name is unique and if all content2 name`s are unuique in a content1 element.
But my problem ist, i want to check if all content2 elements are unique in all content1 elements. Therefore there can only be one content1 element with the name "xy" in the complete XML-File.
Could someone please help me?
Many greetings to all!

A: The unique element for Content2 should simply be moved one level higher in Modul, with the XPath Content1/Content2. That way, Content2 elements must also be unique through the entire Modul.
There is another issue with a double occurrence of AttributeType1, which I replaced with a min/maxOccurs=2, but it may simply be a typo.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xsd:element name="Config">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Modul">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element maxOccurs="unbounded" name="Content1">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element maxOccurs="unbounded" name="Content2">
                      <xsd:complexType>
                        <xsd:sequence>
                          <xsd:element name="AttributeType1" maxOccurs="2" minOccurs="2">
                            <xsd:complexType>
                              <xsd:attribute name="X" type="xsd:double" use="required" />
                            </xsd:complexType>
                          </xsd:element>
                        </xsd:sequence>
                        <xsd:attribute name="Name" type="xsd:string" use="required" />
                      </xsd:complexType>
                    </xsd:element>
                  </xsd:sequence>
                  <xsd:attribute name="Name" type="xsd:string" use="required" />
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
            <xsd:attribute name="Name" type="xsd:string" use="required" />
          </xsd:complexType>
          <xsd:unique name="Content1NameUniqueKey">
            <xsd:selector xpath="Content1" />
            <xsd:field xpath="@Name" />
          </xsd:unique>
          <xsd:unique name="Content2NameUniqueKey">
            <xsd:selector xpath="Content1/Content2" />
            <xsd:field xpath="@Name" />
          </xsd:unique>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xs:schema>


text:
Q: Alternative for deprecated ViewModelProviders? According to that Medium article here, I am using the ViewModelProviders accordingly:
myViewModel = ViewModelProviders.of(this, this.viewModeFactory).get(MyViewModel::class.java)

deprecated for me currently:

@deprecated Use the 'by viewModels()' Kotlin property delegate or

 @link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)},
 passing in the fragment.

In that article ViewModels with possible constructor arguments have a workaround where it implements the ViewModelProvider.Factory and its overridden function override fun create(//..) to provide different ViewModel arguments in a Map with Dagger.
Since I would like to learn modern technologies, I am looking for some examples with the proposed solutions?

A: use this
myViewModel = ViewModelProvider(this, this.viewModeFactory).get(MyViewModel::class.java)


text:
Q: Jacobian criterion for smoothness of schemes An affine scheme $X = Spec(A)$ is said to be smooth if for any closed embedding
$X\subset\mathbf A^n$, of ideal $I$, it is true that, locally on $x\in X$, the ideal $I$
can be generated by a sequence $f_{r+1},\dots,f_n$ such that their Jacobian has maximal rank.
My question is:

*

*Will the Jacobian of ANY set of $n-r$ generators of $I$ be of maximal rank?

A: I believe you need to be careful if $A$ is not over a perfect field.  When $A$ is over a perfect field, the Jacobian ideal is the $r$th fitting ideal of the module of differentials, and so it is canonical (and independent of the choice of generators).
I am getting all of this from Section 16.6 of Eisenbud's Commutative Algebra.

A: Yes, the rank of the Jacobian matrix doesn't depend on the set of generators of $I$. The Jacobian matrix at $x$ represents the subspace generated by the differentials at $x$ of all $f\in I$.
Note that the rank of the Jacobian matrix at $x$ is computed in the fiber where $x$ lives, it has nothing to do with the base scheme.
Some more explanations We work over a base field $k$. Let $I$ be the ideal defining $X$ in $Y:=\mathbb A^n$. Then we have a canonical exact sequence
$$  I/I^2 \to \Omega_{Y}|_X \to \Omega_X \to 0 $$
where the first map is $\bar{f}\mapsto df\otimes 1$. Tensoring by $k(x)$ we get
$$  I/I^2 \to \Omega_{Y}\otimes k(x) \to \Omega_X\otimes k(x) \to 0.$$
If $g_1,...,g_m$ are a system of generators of $I$, then $dg_1,...., dg_m$ generate the image of $I/I^2$ in $\Omega_{Y}\otimes k(x)\simeq k(x)^n$. Call this image $C$. Let $J_x$ be the Jacobian matrix associated to $g_1,...,g_m$ at $x$ in a system of coordinates of $Y$. Then the columns of $J_x$ correspond to the images of $dg_1,...,dg_m$ in $C\subseteq \Omega_{Y}\otimes k(x)$. Therefore the rank of $J_x$ is just the dimension of $C$ over $k(x)$, and this is independent on the choice of the system of generators $g_1,...g_m$.
By the way, these discussions show that
$$\dim_{k(x)} (\Omega_{X}\otimes k(x))=n - \mathrm{rank} J_x.$$
As the smoothness at $x$ is equivalent to $ \dim_{k(x)} (\Omega_{X}\otimes k(x))= \dim_x X$, we see that it is also equivalent to $\mathrm{rank} J_x=n-\dim_x X$ which is the Jacobian criterion of smoothness.


text:
Q: Autohotkey how to make this toggle when I press F4? I am pretty new at this, so this code could be very broken within itself, but the goal is for it to basically alternate between clicking from left to right over and over. Of course, for efficiency, I would like to toggle it. I cannot find the solution after reading multiple articles, so any help would appreciated. Thanks.
~$F4::
While GetKeyState("F4", "P"){
        Send, {Click down}
        sleep 50
        Send, {Click up}
        sleep 50
        Send, {Click down right}
        sleep 50
        Send, {Click up right}
        sleep 50
}
return

A: ~$F4::
While GetKeyState("F4", "P"){
        Send, {LButton down}
        sleep 50
        Send, {LButton up}
        sleep 50
        Send, {RButton down}
        sleep 50
        Send, {RButton up}
        sleep 50
}
return

Your mistake is that you are not using right key names in Send command and also command parameters are not in right place. First parameter should be name of the key. You can get the list of all keys here: http://ahkscript.org/docs/KeyList.htm . Second parameter should be the state of the key (up, down).
Also, always use AutoHotkey and its documenatation from http://ahkscript.org/ (current uptodate version, new official website)! AutoHotkey and its documentation from autohotkey.com is outdated and you may have some problems using them!


text:
Q: Is there a strict store sequence of function arguments in registers r0-r4 in ARM assembly for Raspberry Pi? In ARM assembly code on Raspberry Pi, can we use register r1 (instead of register r0) for receiving the first function parameter while keeping register r0 only for the returned value of the function? Or must the first 4 function parameters be stored, sequentially and strictly, in the registers r0, r1, r2 and r3?

A: Depends if your code have to be used/called from other code. There are some "rules" on how the registers shall be used, how the parameters shall be pass betweeen calls etc. These rules are called ABI (Application Binary Interface) and for ARM can be found here: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.swdev.abi/index.html
That allows to call code written in "C" to code written in (for example) Assembler or other languages, that is part of the magic behind shared libraries.
If you are programming your Raspberry as a bare metal piece of HW, that is, you are not doing SW that shall interface with the operating system nor other applications, you can write code on your way, but in general you should follow these rules when programming in assembler. Even if you do not plan to work with other SW components or OS.  That will make simpler to port your code.


text:
Q: Implementing The SingalR Sample Into An ASP.Net WEB SITE APPLICATION -- Error In JS I am trying to implement the SignalR into my ASP.Net "WEB SITE PROJECT".  (This is an existing application and it is a Web Site Project, and can not be changed over to be a Web Application.)
I get the following error when I try to run the SignalR Sample code.  (This is the basic stock ticker sample.  Just wanting to verify I have everything setup correctly before I start implementing this into my existing code.)
Here is the error I get
Unhandled exception at line 71, column 5 in http://localhost:49218/SchoolFinancial/SignalR.Sample/SignalR.StockTicker.js

0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'client': object is null or undefined

Here is the javascript that the error is thrown with
// Add client-side hub methods that the server will call
$.extend(ticker.client, {
    updateStockPrice: function (stock) {
        var displayStock = formatStock(stock),
            $row = $(rowTemplate.supplant(displayStock)),
            $li = $(liTemplate.supplant(displayStock)),
            bg = stock.LastChange === 0
                ? '255,216,0' // yellow
                : stock.LastChange > 0
                    ? '154,240,117' // green
                    : '255,148,148'; // red

        $stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']')
            .replaceWith($row);
        $stockTickerUl.find('li[data-symbol=' + stock.Symbol + ']')
            .replaceWith($li);

        $row.flash(bg, 1000);
        $li.flash(bg, 1000);
    },

    marketOpened: function () {
        $("#open").prop("disabled", true);
        $("#close").prop("disabled", false);
        $("#reset").prop("disabled", true);
        scrollTicker();
    },

    marketClosed: function () {
        $("#open").prop("disabled", false);
        $("#close").prop("disabled", true);
        $("#reset").prop("disabled", false);
        stopTicker();
    },

    marketReset: function () {
        return init();
    }
});

Here is the Web.Config setting change that is to allow SignalR work with a Web Site project
(This is inside of the following section of the Web.Config   )
  <modules runAllManagedModulesForAllRequests="true">
  </modules>

I am NEW to using SignalR and from what I have found from a previous post, this should solve my issue if I can get it working.
So, if anyone has any experience with using the SignalR in a Web Site Project in ASP.Net I would greatly appreciate any suggestions / recommendations.
Not sure if it matters or not, but I am using Visual Studio 2012 (ASP.Net / C#) and my web site is on the .Net Framework 4.5 version.
Thanks in advance for your help...

A: You are getting this error probably because of the any of the following reasons:-
1) yourbaseurl/signalr/hubs is giving 404. You can verify that in the chrome console after the page is loaded. If you are getting this error you need to make sure that the Hub routes are mapped. using
RouteTable.Route.MapHubs()

either in your global.asax application start or using some startup injector like WebActivatorEx.
 void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RouteTable.Routes.MapHubs();
    }

2) All the SIgnalr related dlls are of compatible versions. This wont be an issue if you have installed with library package manager console.
3) if above steps is not the issue then the issue is that the client proxies are not getting generated properly. This means if you hit yourbaseurl/signalr/hubs you should be able to see the hub registered with the name same as the c# hub class name in camel case and
proxies.stockTicker.client

initialized and
proxies.stockTicker.server

defined with the function names same as that declared in the c# HubProxy. And all of these present under the following prototype decalration .
 $.hubConnection.prototype.createHubProxies

4) If you are not able to get the proxy generated as per step 3 try placing the class files in the SignalR.StockTicker in to the AppCode.
Note:- I just tried and got the sample working in Asp.Net 4.5 website.
All the Best!!


text:
Q: How to find which process is currently writing to the disk? For some unknown reason there is no space left on my /, even 5 minutes after removing 300 MBs of junk packages, there is no space left again. So I've come to conclusion that there is some process that floods my disk space. (--> Recently I installed docker).
How can I find which process produces most data on /?

A: Your best bet is probably iotop:
   iotop  watches  I/O  usage  information  output  by  the  Linux  kernel
   (requires 2.6.20 or later) and displays a table of current I/O usage by
   processes   or   threads   on   the   system.   At   least   the   CON‐
   FIG_TASK_DELAY_ACCT,  CONFIG_TASK_IO_ACCOUNTING,  CONFIG_TASKSTATS  and
   CONFIG_VM_EVENT_COUNTERS  options need to be enabled in your Linux ker‐
   nel build configuration.

Assuming your process is doing a lot of I/O operations, it should show up pretty high in that list.