text:
Q: how to migrate a squashfs system to another filesystem that's read/write Well, basically what i want to do is copy all of my router's files (even the dev file (because i'm running busybox)) to my usb flash drive and let my router by default boot from the usb device. it might be not as fast as the nand flash that my router boots from, but i want to access the router's file any time and edit the files of the router.
also, i don't want to mount it as squashfs, but as a filesystem the router understands, as it is currently running busybox v1.9.1 and has linux 2.6.15-17 (don't exactly remember), and i want the new filesystem to be read/write.
here's the output of the mount command:
rootfs on / type rootfs (rw)
/dev/root on / type squashfs (ro)
none on /dev type tmpfs (rw)
/proc on /proc type proc (rw)
none on /var type tmpfs (rw)
none on /tmp type tmpfs (rw)
none on /mnt type tmpfs (rw)
usbfs on /proc/bus/usb type usbfs (rw)
/dev/nandflash on /upgflash type ext3 (rw,data=ordered)
/dev/sda1 on /mnt/usb1_1 type vfat (rw,fmask=0000,dmask=0000,codepage=cp936,iocharset=cp936,shortname=winnt)
none on /html/help type tmpfs (rw)

and the output of the df -k command:
Filesystem           1k-blocks      Used Available Use% Mounted on
rootfs                    8320      8320         0 100% /
/dev/root                 8320      8320         0 100% /
/dev/nandflash          251919    102992    136127  43% /upgflash
/dev/sda1              2880416   1078268   1802148  37% /mnt/usb1_1

and the output of the cat /proc/filesystems command:
nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   debugfs
nodev   sockfs
nodev   usbfs
nodev   pipefs
nodev   tmpfs
nodev   inotifyfs
        ext3
        squashfs
nodev   ramfs
        vfat
nodev   fuse
        fuseblk
nodev   fusectl

and the output of the cat /proc/partitions command:
major minor  #blocks  name

  31     0        256 mtdblock0
  31     1        512 mtdblock1
  31     2       8826 mtdblock2
   8     0    3942400 sda
   8     1    2888608 sda1
   8    16     256000 nflashb

and the output of the cat /proc/diskstats command:
  31    0 mtdblock0 0 0 0 0 0 0 0 0 0 0 0
  31    1 mtdblock1 0 0 0 0 0 0 0 0 0 0 0
  31    2 mtdblock2 236 3876 8224 3310 0 0 0 0 0 3310 3310
   8    0 sda 5 7 19 124 0 0 0 0 0 124 124
   8    1 sda1 11 11 0 0
   8   16 nflashb 748 2937 29848 11605 423 878 2854 465219 0 36340 476824

and the output of cat /proc/devices command:
Character devices:
  1 mem
  2 pty
  3 ttyp
  4 ttyS
  5 /dev/tty
  5 /dev/console
 10 misc
 13 input
 21 sg
 89 i2c
 90 mtd
180 usb
188 ttyUSB
189 usb_device
209 endpoint
242 fcache
248 bhal
249 commondrv
250 i2c_pca
251 usb_endpoint
252 usbmon
253 nvram
254 gpio

Block devices:
  8 sd
 31 mtdblock
 65 sd
 66 sd
 67 sd
 68 sd
 69 sd
 70 sd
 71 sd
128 sd
129 sd
130 sd
131 sd
132 sd
133 sd
134 sd
135 sd

and the output of the cat /proc/meminfo command:
MemTotal:       126080 kB
MemFree:         90392 kB
Buffers:          4508 kB
Cached:          15428 kB
SwapCached:          0 kB
Active:           9616 kB
Inactive:        14412 kB
SwapTotal:           0 kB
SwapFree:            0 kB
Dirty:               0 kB
Writeback:           0 kB
AnonPages:        4116 kB
Mapped:           3452 kB
Slab:             5344 kB
SReclaimable:     1152 kB
SUnreclaim:       4192 kB
PageTables:        520 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:     63040 kB
Committed_AS:     7740 kB
VmallocTotal:  1032148 kB
VmallocUsed:      3460 kB
VmallocChunk:  1027212 kB

note: i provided all of this information so that you could get the right answer that's safe and not extremely fragile. please test the answers that you type in here BEFORE you tell me to do something unreliable or derpy.


text:
Q: Prove that the equation of the tangent at P is $ \frac {xx_1}{a^2} - \frac {yy_1}{b^2} = 1 $ (Hyperbolas)

Question: Point P ($x_1 , y_1$) is on the hyperbola $\frac {x^2}{a^2}$ - $\frac {y^2}{b^2}$ = 1
Prove that the equation of the tangent at P is
$$ \frac {xx_1}{a^2} - \frac {yy_1}{b^2} = 1 $$

What I have attempted:
Equation of a tangent is:
$$ (y-y_0) = m(x-x_0) $$
In this case we have $x_0 = x_1$ and $y_0 = y_1$ Now we need to find $m$ so I am going to implicitly differentiate the equation of the hyperbola
$$ \frac {x^2}{a^2} - \frac {y^2}{b^2} = 1 $$
$$ \frac {2x}{a^2} - \frac {2y}{b^2} (\frac {dy}{dx})= 1 $$
$$ \frac {dy}{dx}= \frac {xb^2}{ya^2}$$
at $x = x_1$ and $y = y_1$
$$ \frac {dy}{dx}= \frac {x_1b^2}{y_1a^2}$$
With $ (y-y_0) = m(x-x_0) $
$$ (y-y_1) = \frac {x_1b^2}{y_1a^2}(x-x_1) $$
$$ (y-y_1) = \frac {xx_1b^2}{y_1a^2} -  \frac {x_1^2b^2}{y_1a^2} $$
$$ (y-y_1) = \frac {xx_1b^2 - x_1^2b^2 }{y_1a^2}  $$
$$ yy_1a^2 - y_1^2a^2 = xx_1b^2 - x_1^2b^2 $$
$$ \frac{yy_1}{b^2} -\frac{y_1^2}{b^2}  = \frac{xx_1}{a^2}  - \frac{x_1^2}{a^2}$$
$$ \frac{x_1^2}{a^2} -\frac{y_1^2}{b^2} = \frac{xx_1}{a^2} - \frac{yy_1}{b^2} $$
Now I am stuck I am trying to get rid of
$ \frac{x_1^2}{b^2} -\frac{y_1^2}{b^2} $ and try to make that equal to $1$ and prove the statement but the equation of the hyperbola is given $\frac {x^2}{a^2}$ - $\frac {y^2}{b^2}$ = 1...

A: Since $(x_1,y_1)$ lie on hyperbola, they satisfy the equation $\frac{x^2}{a^2}-\frac{y^2}{b^2} = 1$
$$ \frac{x_1^2}{a^2}-\frac{y_1^2}{b^2} = 1$$
$$\implies\frac{xx_1}{a^2} - \frac{yy_1}{b^2} = 1$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to sort columns of a query in wordpress hello With the code that I will provide you here below, I manage to sort my columns in ascending or descending order
This works for the "date" column, for the "total des prises" column for the "vues" column
But not for the "auteur" column
I went to see in my database and the name of the auteur whose display_name
I have already tried a lot of code, but nothing works to allow me to sort this auteur column by clicking on the column title as for the other columns
<?php
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'post',
    'posts_per_page' => '10',
    'category_name' => 'nouveautes',
    'paged' => $paged,
    'meta_key' => isset($_GET['orderby']) && ($_GET['orderby'] == 'entry_views' || $_GET['orderby'] == 'total_des_prises') ? $_GET['orderby'] : 'date',
    'orderby' => isset($_GET['orderby']) && ($_GET['orderby'] == 'entry_views' || $_GET['orderby'] == 'total_des_prises') ? 'meta_value_num' : array('meta_value' => 'DESC', 'date' => 'DESC', 'display_name' => 'ASC'),
    'order' => isset($_GET['order']) && $_GET['order'] == 'asc' ? 'ASC' : 'DESC'
);

$the_query = new WP_Query($args);

if ($the_query->have_posts()) { ?>

Détail

            <a href="<?php echo add_query_arg(array('orderby' => 'date', 'order' => isset($_GET['order']) && $_GET['order'] == 'asc' ? 'desc' : 'asc')); ?>">Date

            <a href="<?php echo add_query_arg(array('orderby' => 'total_des_prises', 'order' => isset($_GET['order']) && $_GET['order'] == 'asc' ? 'desc' : 'asc')); ?>">Total des prises

            <a href="<?php echo add_query_arg(array('orderby' => 'display_name', 'order' => isset($_GET['order']) && $_GET['order'] == 'asc' ? 'desc' : 'asc')); ?>">Auteur

            <a href="<?php echo add_query_arg(array('orderby' => 'entry_views', 'order' => isset($_GET['order']) && $_GET['order'] == 'asc' ? 'desc' : 'asc')); ?>">Vues

    <?php while ($the_query->have_posts()) {
        $the_query->the_post();
        $total_des_prises = get_post_meta(get_the_ID(), 'total_des_prises', true);
        ?>

<?php echo '' . 'Détail' . '';?>

<?php echo get_the_date(); ?>

<?php echo $total_des_prises; ?>

<?php echo get_the_author(); ?>

<?php echo do_shortcode('[WPPV-TOTAL-VIEWS]'); ?>

        <?php
     }

        wp_pagenavi( array( 'query' => $the_query ) );
    }
    /* Restore original Post Data */
    wp_reset_postdata();
?>


text:
Q: How convert an undirected graph to a directed graph in which each node has at most K parents? I need to convert an undirected graph to a DAG that requires each node have at most K parents. I want to minimize the number of edges lost in the conversion. Can anyone suggest some methods?

A: Ok so assuming that I understood the problem, a nice algorithm to solve this is Kuhn-Munkres (https://en.wikipedia.org/wiki/Hungarian_algorithm).
For each edge, you want to associate one of the two nodes (the one it is directed to).
For each node, you have maximum K association possible.
So your bigraph is on one side (let s say left side) the edges of your initial graph and on the other (let s say right side) K times each nodes + one sink node per edge. The sink nodes correspond to the loss of the edge.
Then you put the edges in your bigraph (not to be confused with the edges of your problem). You put a 0 cost edge, for all the connections of your initial graph and a 1 cost edge from any left node to its sink node.
Then you use Kuhn-Munkres algorithm to minimize the association.


text:
Q: Primefaces resetinput in cancel button hanging other tabs I have got an issue with primefaces resetinput. When I press this cancel button all of my other Tabs just hanged. I am using primefaces 3.5.
        <p:commandButton id="cancelMainButton" process="@this"
             value="#{bundle.Cancel}" update=":ss_form:ss_tabView:main_tab"
             actionListener="#{eccmServiceSpecController.cancelServiceSpec}"
            icon="ui-icon-cancel">
            <p:resetInput target=":ss_form"/>
        </p:commandButton>

    **Controller**
    @Named("eccmServiceSpecController")
    @SessionScoped

    public void cancelServiceSpec(ActionEvent event) {
        eccmServiceSpec = ejbFacade.findByServiceSpec(eccmServiceSpec);
        this.setSelected(eccmServiceSpec);
    }

    **Facade** Statefull session bean with Extended mode.
public EccmServiceSpec findByServiceSpec(EccmServiceSpec eccmServiceSpec){
    this.getEntityManager().detach(eccmServiceSpec);
    eccmServiceSpec = this.find(eccmServiceSpec.getServSpecId());
    eccmServiceSpec = this.getEntityManager().merge(eccmServiceSpec);
    return eccmServiceSpec;
}

Thanks for your reply. I have added my controller and Facade please look at this. I shall be thankful to you.


text:
Q: Elixir doctest fails for function that returns random values I have a function in Elixir that produces three random RGB tuples in a list.
defmodule Color do

  @doc """
  Create three random r,g,b colors as a list of three tuples

  ## Examples

      iex> colors = Color.pick_color()
      iex> colors
      [{207, 127, 117}, {219, 121, 237}, {109, 101, 206}]

  """
      def pick_color() do
        color = Enum.map((0..2), fn(x)->
          r = Enum.random(0..255)
          g = Enum.random(0..255)
          b = Enum.random(0..255)
          {r, g, b}
        end)
end

When I run my tests, my doctests fail. The resulting list of tuples are different than what is defined in my doctest. How can I write a doctest for a function that returns a random value?

A: You can make the random functions deterministic by setting the seed of :rand's random number generator. This is also how Enum.random/1 is tested in Elixir.
First, open iex and set the seed of the current process to any value:
iex> :rand.seed(:exsplus, {101, 102, 103})

Then, run your function in iex
iex> Color.pick_color()

Now just copy this value into your doctest along with the :rand.seed call. By explicitly setting the seed, you're going to get the same values from the functions in :rand module and Enum.random/1 uses :rand internally.
iex(1)> :rand.seed(:exsplus, {1, 2, 3})
iex(2)> for _ <- 1..10, do: Enum.random(1..10)
[4, 3, 8, 1, 6, 8, 1, 6, 7, 7]
iex(3)> :rand.seed(:exsplus, {1, 2, 3})
iex(4)> for _ <- 1..10, do: Enum.random(1..10)
[4, 3, 8, 1, 6, 8, 1, 6, 7, 7]
iex(5)> :rand.seed(:exsplus, {1, 2, 3})
iex(6)> for _ <- 1..10, do: Enum.random(1..10)
[4, 3, 8, 1, 6, 8, 1, 6, 7, 7]

A: In order to test a function with doctests, you must be able to predict the output of your function. In this case, you can't predict the output of your function.

However you could test your function with regular tests.
Here is a test that would make sure Color.pick_color() produces a list of 3 tuples, using pattern matching:
test "pick color" do
  [{_, _, _}, {_, _, _}, {_, _, _}] = Color.pick_color()
end

You could also check if each value is between 0 and 255, etc.


text:
Q: PHP Undefined Object Error and Call a Function on a Non-Object Error I get the following error when I run my php scripts.
the error is presented below

Below are the codes.
The config.php file
<?Php

$dbhost_name = "localhost";
$database = "datacentre";  // Your database name
$username = "root";                  //  Login user id
$password = "";                  //   Login password

define( "TEMPLATE_PATH", "templates" );

define( "ADMIN_USERNAME", "username" );

define( "ADMIN_PASSWORD", "password" );

?>

The register.php file
<?php
require "config.php";

$requests = array();

$sql = "SELECT request FROM request_type";

foreach ($dbo->query($sql) as $row)
{
    $requests[] = $row['request'];
}

include('/templates/file.template.php');

The file.template.php codes
<!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="layout.css">

<title>Title of the document</title>

<?php
include('header.php');
?>

<form class="form" action="insert.php" method="post" name="access_form">

Please Fill The Form

     First Name
        <input name="firstname" id="keyword" type="text" placeholder="type first name (required)" required />

     Last Name
     <input name="lastname" id="lastname" type="text" placeholder="type second name (required)" required />

Type of Request
<input name="request" id="request" list="request1" />
        <datalist id="request1" >
            <?php foreach ($requests as $request): ?>
                <option value="<?php echo $request; ?>" />
            <?php endforeach; ?>
        </datalist>

    Purpose

    <input type = "radio"
           name = "purposebuttons"
           id = "official"
           value = "Official" />
    Official

    <input type = "radio"
           name = "purposebuttons"
           id = "unofficial"
           checked = "checked"
           value = "denied" />
    Unofficial

   Description
   <textarea name="description" id="description" placeholder="type description (required)" required ></textarea>

          <input type = "radio"
                 name = "approvalbuttons"
                 id = "approved"
                 value = "Approved"
          Approved

          <input type = "radio"
                 name = "approvalbuttons"
                 id = "denied"
                 checked = "checked"
                 value = "Denied" />
          Denied

   Approved By
   <input name="approvedby" id="approveby" type="text" placeholder="approval name (required)" required />

          <input type = "reset" class="submit"/>
          <input type = "submit" class="reset"/>

</form>

<?php
include('footer.php');
?>

Any suggestion to fix the problem.

A: Change your config.php with
<?php

$dbhost_name = "localhost";
$database = "datacentre";  // Your database name
$username = "root";                  //  Login user id
$password = "";                  //   Login password
$dbo = new mysqli($dbhost_name , $username, $password, $database );
if ($dbo->connect_error) {
  die("Connection failed: " . $dbo->connect_error);
}
define( "TEMPLATE_PATH", "templates" );

define( "ADMIN_USERNAME", "username" );

define( "ADMIN_PASSWORD", "password" );

?>


text:
Q: IF Reference cell is blank Hello these are two formulas that i have and work perfectly when it has values in the reference cells. I do not know how to show zero if the reference key is Blank.
Please help
=IF(AND(E10=E3,G10=G3),3,0)

and
=IF(OR(AND(E3>G3,E10>G10)),1,0)+IF(OR(AND(E3=G3,E10=G10)),1,0)+IF(OR(AND(E3<G3,E10<G10)),1,0)

A: you can use isempty function
or(isempty(E10),isempty(E3),isempty(G10),isempty(G3) will return true if on of the reference key is blank
if(or(isempty(E10),isempty(E3),isempty(G10),isempty(G3)),0,IF(AND(E10=E3,G10=G3),3,0))


text:
Q: Why does my flutter app crash when I add `sqflite` to my pubspec.yaml? When I add sqflite as a dependency to my project my application crashes. Just adding the dependency crashes the application.
I've tried adding permissions like
<uses-permission android:name="android.permission.STORAGE" /> and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> but that didn't fix the problem.
My pubspec.yaml file:
environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http:
  video_player:
  screen:
  sqflite:

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_launcher_icons:

flutter_icons:
  image_path: "assets/logo.png"
  android: true
  ios: true

How to prevent this crash?

A: It is hard to tell exactly what is problem without crash log,
You can check this link.
If that is not problem

*

*Try to run flutter clean.

*Change version of sqflite plugin version.

*If you are using android emulator, wipe emulator data and try again.

*Checkout those plugin issues (open and closed both).


text:
Q: Custom showsCameraControls for UIImagePickerControllerSourceTypeCamera I want to add two extra buttons to my UIImagePickerController. I saw that done in an app:
camwow but I couldn't find the documentation to do that. I have a view overlay over the UIImagePickerControllerSourceTypeCamera but at the moment touches on the buttons from the view overlay propagate to the camera controller which focuses.


text:
Q: How to ingest variable data like passwords into compute instance when deploying from template We are trying to figure out how we can create a compute engine template and set some information like passwords with the help of variables in the moment when the final instance is generated by deployment manager, not in the base image.
When deploying something from marketplace you can see that passwords are generated by "password.py" and stored as metadata in the VMs template. But i can't find the code that writes this data into the VMs disk image.
Could someone explain how this can be achieved?
Edit:
I found out that startup scripts are able to read the instance's metadata: https://cloud.google.com/compute/docs/storing-retrieving-metadata Is this how they do it in marketplace click-to-deploy scripts like https://console.cloud.google.com/marketplace/details/click-to-deploy-images/wordpress ? Or is there an even better way to accomplish this?

A: The best way is to use the metadata server.
In a star-up script, use this to recover all the attributes of your VM.
curl  -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetada
ta/v1/instance/attributes/"

Then, do what you want with it
Don't forget to delete secret from metadata after their use. Or change them on the compute. Secrets must be stay secret.

By the way, I would to recommand you to have a look to another things: berglas. Berglas is made by a Google Developer Advocate, specialized in security: Seth Vargo. In summary the principle:

*

*Bootstrap a bucket with Berglas

*Create a secret in this Bucket ith Berglas

*Pass the reference to this secret in your compute Metadata (berglas://<my_bucket>/<my secret name>)

*Use berglas in start up script to resolve secret.

All this action are possible in command line, thus an integration in a script is possible.

A: You can use python templates , this give you more flexibility. In your YAML you can call the python script to fill the necessary information, from documentation:
imports:
- path: vm-template.py

resources:
- name: vm-1
  type: vm-template.py
- name: a-new-network
  type: compute.v1.network
  properties:
    routingConfig:
      routingMode: REGIONAL
    autoCreateSubnetworks: true

Where vm-template.py it's a python script:
    """Creates the virtual machine."""

COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/'

def GenerateConfig(unused_context):
  """Creates the first virtual machine."""

  resources = [{
      'name': 'the-first-vm',
      'type': 'compute.v1.instance',
      'properties': {
          'zone': 'us-central1-f',
          'machineType': ''.join([COMPUTE_URL_BASE, 'projects/[MY_PROJECT]',
                                  '/zones/us-central1-f/',
                                  'machineTypes/f1-micro']),
          'disks': [{
              'deviceName': 'boot',
              'type': 'PERSISTENT',
              'boot': True,
              'autoDelete': True,
              'initializeParams': {
                  'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/',
                                          'debian-cloud/global/',
                                          'images/family/debian-9'])
              }
          }],
          'networkInterfaces': [{
              'network': '$(ref.a-new-network.selfLink)',
              'accessConfigs': [{
                  'name': 'External NAT',
                  'type': 'ONE_TO_ONE_NAT'
              }]
          }]
      }
  }]
  return {'resources': resources}

Now for the password it depends which VM you are using, Windows or Linux.
Linux you can add a startup script which inject a ssh public key.
Windows you can first prepare the proper key, see this Automate password generation


text:
Q: Query only most recent value if duplicates exist I work at a warehouse and I am developing an Inventory System. When products come in, it is because they are damaged. I have one person fill out a row in Google Sheets when the product arrives (Sheet1 in the workbook link below). I mainly need Barcode, Issue, and Date from this Sheet).
Next, a mechanic fixes the product and fills out a google form with his name and the barcode of the product; the responses are Form Responses 1 in the workbook link below.
I then pull the data for all the incoming products from Sheet1 to a new tab (Barcodes In/Out in the workbook link below), querying Barcode, Issue, and Date. I pull the data for all the outgoing product in another column in this tab, querying the Barcode from the Form Responses 1. Column E (Backlog) has a formula that only shows barcodes of products that have not been repaired (gone "out").
I pull the data for what is in my Back log (products still in warehouse needing repair) into another tab named Back Log. This was working perfectly until I realized products can come back to our warehouse (i.e. "123" can come in and get fixed and sent out again. "123" can come back again for more repairs.)
This poses a problem because Back Log now shows "123" twice with two different Issues.
I need Back Log to query "123" only and only with the most recent Issue.
This is a lot of info, but I tried to be as detailed as I could. Thank you for your help in advance!
Here is the link to my workbook

A: In G2 I entered
=ArrayFormula(iferror(vlookup(unique(Sheet1!B2:B), sort({Sheet1!B2:B, Sheet1!A2:F}, 7, 0), {2, 3, 4, 5, 6}, 0)))

UPDATE: Based on new info...
=query(ArrayFormula(iferror(vlookup(unique(Sheet1!B2:B), sort(filter({Sheet1!B2:B, Sheet1!A2:F}, not(regexmatch(Sheet1!B2:B&"", textjoin("|", 1, filter('Barcodes In/Out'!D2:D, isna(match('Barcodes In/Out'!D2:D, 'Barcodes In/Out'!E2:E, 0))))))), 7, 0), {2, 3, 4, 5, 6}, 0))), "where Col1 <>''")

See if that works for you?


text:
Q: Wasting of vertical space by an itemize within a tabularx When I am using an itemize within a tabular(x) cell, it wastes a lot of vertical space.. How can I get rid of it?

My MWE:
\documentclass{beamer}

\usetheme{Boadilla}

\usepackage{tabularx}

\begin{document}

    \begin{frame}
        \begin{tabularx}{\textwidth}{|l|X|}
            \hline
            Test
            &
            \begin{itemize}
                \item item 1
                \item item2
            \end{itemize}
            \\\hline
        \end{tabularx}

    \end{frame}

\end{document}

Thank you for your help!

A: Try the following:
\documentclass{beamer}
\usetheme{Boadilla}

\usepackage{tabularx}

\begin{document}

\begin{frame}
    \begin{tabularx}{\textwidth}{|l|X|}
        \hline
        Test
        &   \begin{minipage}{\linewidth}
            \smallskip
        \begin{itemize}
            \item item 1
            \item item2
        \end{itemize}
            \smallskip
            \end{minipage}
        \\\hline
    \end{tabularx}
\end{frame}

\end{document}


text:
Q: Two array list, passing values and using database I have written code to get all the list of installed apps in the device and pick one to run. Now but I want that when an item is clicked the item should get added to another list which would be used in another activity.
I have ActivityA which lists all the installed apps. When an user clicks an app in ActivityA it should be added to arraylist which is used in ActivityB. i.e. ActivityB will just have the apps that are selected by user in ActivityA. How can I do that?
Also this ActivityB is in another app so what should I use to store the arraylist? SQLiteDatabase or is there something much simpler than that?
Thank you.

A: If I understand your question correctly, you essentially want to store information across applications.  The best way to do this would be through a ContentProvider


text:
Q: Joomla Wysiwyg & jquery post problem I'm using this joomla method to display a wysiwyg editor inside my custom app.
// this initiates the wysiwig

<?php $editor =& JFactory::getEditor(); ?>

// this displays a text area with the wysiwyg

<?php echo $editor->display("desc",$desc,'100%','300','20','20','0'); ?>

I now want to POST the content of that text-area off, through my inline jquery script
// SAVE THE FORM  DATA

$('#SAVELISTING').click(function(){

if (confirm("Click OK to save the data"))
{

var txt = $.ajax({
url: 'update.php',
async: true,
type:'POST',

data:({

id:$('input#id').val(),
listTitle:$('input#listTitle').val(),
introdesc:$('textarea#introdesc').val(),
fulldesc:$(JRequest::getVar('textarea#desc')).val()

})

}).success;
$('.alert').show('slow');
}
});

Which in turn sends it to my update.php script.
$desc = mysql_real_escape_string($_POST['fulldesc']);

DO THE INSERT

The firebug response i get is JRequest is not defined
Update

And this is the normal method joomla uses for posting the data, can anyone work out maybe from that how i would pst the data inside my jquery code above?
/*The store-procedure in your model might then look like this*/
[...]
function store()
{
  $row =& $this->getTable();
  $data = JRequest::get( 'post');
  /* Get proper HTML-code for your HTML-encoded field now by using JREQUEST_ALLOWHTML*/
  $data['yourfieldname']=JRequest::getVar( 'yourfieldname', '', 'post', 'string', JREQUEST_ALLOWHTML );
  /* now proceed as suggested */

  $row->bind($data);
  [...]
  $row->check();
  [...]
  $row->store();
  [...]
}
[...]

A: Try
fulldesc:$(<?php echo JRequest::getVar('textarea#desc')%>).val()

After looking at your update I'm not even sure you need the JRequest call.  Try:
fulldesc:$('textarea#desc').val()


text:
Q: How to adjust Synaptics touchpad in 18.04 Ever since I installed Bionic Beaver last week, my touchpad cursor freezes, disappears, stutters, trips when crossing UI elements, and gets stuck to the edge of the screen. When I used 14.04 I was able to smooth things out using synclient, but that's not available out of the software store anymore.
Is there any way in 18.04 to get the kind of touchpad control that I used to have with synclient?


text:
Q: Rxjs 6 flatten observable I need your advice on how to convert the Rxjs 5 to Rxjs 6.
My code is below and I am not too sure why it did not work.
Rxjs 5
Observable.from([{amount:5},{amount:10}])
.flatMap(_ => depositService.deposit(depositAmount))
.toArray()
.subscribe(result => {
    console.log(result.length);
})

Rxjs 6
import { Observable, from, } from 'rxjs';
import { map, catchError, mergeMap} from 'rxjs/operators';
...

const source = from([{amount:5},{amount:10}]);
source
.pipe(mergeMap(_ => depositService.deposit(_.amount).toArray())
.subscribe(result => {
    console.log(result.length);
})

I got the error
You provided an invalid object where a stream was expected You can provide an Observable, Promise, Array, or Iterable.

A: I think toArray is an operator and should be passed in in the pipe.
import { Observable, from, } from 'rxjs';
import { map, catchError, mergeMap, toArray} from 'rxjs/operators';
...

const source = from([{amount:5},{amount:10}]);
source
.pipe(
    mergeMap(_ => depositService.deposit(_.amount)),
    toArray()
)
.subscribe(result => {
    console.log(result.length);
})


text:
Q: Некорректное добавление данных в поле бд <?php
if (isset($_POST['login']))
    {
        $login = $_POST['login'];
    }
if (isset($_POST['password']))
    {
        $password = $_POST['password'];
    }
if (isset($_POST['data']))
    {
        $data = $_POST['data'];
    }
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
$data = stripslashes($login);
$data = htmlspecialchars($login);
$login = trim($login);
$password = trim($password);
$data = trim($data);
include ("bd.php");
$result = mysql_query("SELECT id FROM users WHERE login='$login'", $db);

$myrow = mysql_fetch_array($result);
if (!empty($myrow['id']))
{
    exit ("Извините, введённый вами логин уже зарегистрирован. Введите другой логин.");
}
$result2 = mysql_query ("INSERT INTO users (login,password, data) VALUES('$login','$password', '$data')");
echo mysql_error();
if ($result2=='TRUE')
    {
        include 'scr.js';
        require('index.php');
    }
else
    {
        echo "Ошибка! Вы не зарегистрированы.";
    }

Народ, уже всё облазил, не могу понять в чём проблема. Почему в строку "data" в бд добавляется то же значение, что и значение "login"? То есть, поля "login" и "data" в бд одинаковы. Запрос вставки в строку написан вроде правильно. Как это исправить, и вообще, где ошибка тут может быть? Для уточнения, data - ФИО пользователя, login - логин. При вводе, например, login "aloha" и data "FIO", в поля бд login и data вставляется "aloha". Не кидайтесь помидорами, php начал совсем недавно заниматься.

A: $data = stripslashes($login);
$data = htmlspecialchars($login);

а надо
$data = stripslashes($data);
$data = htmlspecialchars($data);


text:
Q: Shorthand for groovy String If I am using Groovy String Template:
http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#markuptemplate-gotchas
I have a variable $name1,name2 and I want to says something like:
${name1? name1:''} ${name2? 'name2 was here, too': ''}

Is there a cleaner way to write expression like this.
Given I don't know if $name1, $name2 is null or not. If they are, printing empty   or not printing anything is fine. I just don't want 'null' as the text.

A: There is such thing as an Elvis operator:
def foo = bar?:baz

Which is equal to calling:
def foo = bar ? bar : baz

In your case, you can use it like this:
${name1?:''}

A: ${name1 ?: ''} ${name2 ? 'name2 was here, too' : ''}


text:
Q: Stored Procedure or a query for this special requirement I want to write a query or a stored procedure in SQL Server to solve this problem - I tried a lot but no chance !
I have this data in a SQL table and I want to make a special operation on it :
0   3   1   0   0   0   0   NULL    NULL    35  117461  Mark    CEO     OBAMA   NULL    PARIS   FaceBook    NULL          NULL  NULL    NULL    NULL    NULL    NULL    NULL    01/10/2015  Very Good
0   3   1   0   0   0   0   1901    6925    35  117461  Mark    CEO     OBAMA   Med1    PARIS   FaceBook    One2Few 20/10/2015  NULL    NULL    NULL    NULL    NULL    NULL           NULL NULL
0   3   1   0   0   0   0   2135    7835    35  117461  Mark    CEO     OBAMA   Soft1   PARIS   FaceBook    One2Few 27/11/2015  NULL    NULL    NULL    NULL    NULL    NULL           NULL NULL
0   3   1   0   0   0   0   2574    9575    35  117461  Mark    CEO     OBAMA   Med1    PARIS   FaceBook    GroupMe 17/03/2016  NULL    NULL    NULL    NULL    NULL    NULL           NULL NULL
0   3   1   0   0   0   0   2832    1849    35  117461  Mark    CEO     OBAMA   Tech1   PARIS   FaceBook    One2Few 30/05/2016  NULL    NULL    NULL    NULL    NULL    NULL           NULL NULL

What I want is to remove the duplication and group those 5 rows into one single row containing the important information:
0   3   1   0   0   0   0     Mark          CEO         OBAMA     Med1|Soft1|Tech1     PARIS     FaceBook    01/10/2015    Very Good

I explain :
The 7 first columns are count operation and it is always the same in each row.
A concatenation of values Med1|Soft1|Tech1 - when two Values are the same take only one.
Take the comment when it exists here =  "very Good"  - The comment will exist once.


text:
Q: Audio not starting when loading Just Audio player I'm new to Flutter and followed this tutorial https://suragch.medium.com/background-audio-in-flutter-with-audio-service-and-just-audio-3cce17b4a7d to setup Just Audio and audioservice. I'm building my app for Android at the moment.
I'm having 3 issues:

*

*The main problem is that when I use context.go (from GoRouter) to move to the player screen, audio should start playing, but it doesn't, I have to manually press the Play button.

*Additionaly when I load a playlist and press Next, it also doesn't start playing automatically.

*Finally, sometimes if I leave the player for other screen and come back, I can't press the Play button.

Here are the 3 files I'm using:
Player screen:
import 'package:audio_service/audio_service.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:podfic_app/screens/chapterlist_screen.dart';
import 'package:podfic_app/utils/api_service.dart';
import './just_audio/notifiers/play_button_notifier.dart';
import './just_audio/notifiers/progress_notifier.dart';
import './just_audio/page_manager.dart';
import './just_audio/services/service_locator.dart';
import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';

class Player extends StatefulWidget {
  const Player({super.key});

  @override
  State<Player> createState() => _PlayerState();
}

class _PlayerState extends State<Player> {
  @override
  void initState() {
    super.initState();
    getIt<PageManager>().init();
  }

  @override
  void dispose() {
    getIt<PageManager>().dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // startPlaying();
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 25.0),
          child: Column(
            children: [
              // const SizedBox(height: 10),

              // back button and menu button
              Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  IconButton(
                      icon: const Icon(Icons.arrow_back),
                      onPressed: () => context.pop()),
                  const Text('Listening to'),
                  IconButton(
                      icon: const Icon(Icons.playlist_play_outlined),
                      onPressed: () => context.push('/chapters')),
                ],
              ),

              const SizedBox(height: 25),

              // cover art, artist name, song name
              const CurrentMetadata(),

              const SizedBox(height: 30),

              const SizedBox(height: 20),

              // linear bar
              const AudioProgressBar(),

              const SizedBox(height: 30),

              // previous song, pause play, skip next song
              Align(
                alignment: Alignment.topCenter,
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(0),
                  child: Stack(children: [
                    Container(
                      child: const ChangeSpeedButton(),
                    ),
                    Center(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: const [
                          PreviousSongButton(),
                          PlayButton(),
                          NextSongButton(),
                        ],
                      ),
                    ),
                  ]),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// class CurrentSongTitle extends StatelessWidget {
//   const CurrentSongTitle({Key? key}) : super(key: key);
//   @override
//   Widget build(BuildContext context) {
//     final pageManager = getIt<PageManager>();
//     return ValueListenableBuilder<String>(
//       valueListenable: pageManager.currentSongTitleNotifier,
//       builder: (_, title, __) {
//         return Padding(
//           padding: const EdgeInsets.only(top: 8.0),
//           child: Text(title, style: const TextStyle(fontSize: 40)),
//         );
//       },
//     );
//   }
// }

class AddRemoveSongButtons extends StatelessWidget {
  const AddRemoveSongButtons({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final pageManager = getIt<PageManager>();
    return Padding(
      padding: const EdgeInsets.only(bottom: 20.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          FloatingActionButton(
            onPressed: pageManager.add,
            child: const Icon(Icons.add),
          ),
          FloatingActionButton(
            onPressed: pageManager.remove,
            child: const Icon(Icons.remove),
          ),
        ],
      ),
    );
  }
}

class AudioProgressBar extends StatelessWidget {
  const AudioProgressBar({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final pageManager = getIt<PageManager>();
    return ValueListenableBuilder<ProgressBarState>(
      valueListenable: pageManager.progressNotifier,
      builder: (_, value, __) {
        return ProgressBar(
          progress: value.current,
          buffered: value.buffered,
          total: value.total,
          onSeek: pageManager.seek,
        );
      },
    );
  }
}

class AudioControlButtons extends StatelessWidget {
  const AudioControlButtons({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: const [
          PreviousSongButton(),
          PlayButton(),
          NextSongButton(),
        ],
      ),
    );
  }
}

class PreviousSongButton extends StatelessWidget {
  const PreviousSongButton({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final pageManager = getIt<PageManager>();
    return ValueListenableBuilder<bool>(
      valueListenable: pageManager.isFirstSongNotifier,
      builder: (_, isFirst, __) {
        return IconButton(
          icon: const Icon(Icons.skip_previous),
          iconSize: 32,
          onPressed: (isFirst) ? null : pageManager.previous,
        );
      },
    );
  }
}

class PlayButton extends StatelessWidget {
  const PlayButton({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final pageManager = getIt<PageManager>();
    return ValueListenableBuilder<ButtonState>(
      valueListenable: pageManager.playButtonNotifier,
      builder: (_, value, __) {
        switch (value) {
          case ButtonState.loading:
            return Container(
              margin: const EdgeInsets.all(8.0),
              width: 48.0,
              height: 48.0,
              child: const CircularProgressIndicator(),
            );
          case ButtonState.paused:
            return Container(
                decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primary,
                    borderRadius: BorderRadius.circular(200)),
                child: IconButton(
                  icon: const Icon(Icons.play_arrow),
                  iconSize: 48,
                  color: Colors.white,
                  onPressed: pageManager.play,
                ));
          case ButtonState.playing:
            return Container(
                decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primary,
                    borderRadius: BorderRadius.circular(200)),
                child: IconButton(
                  icon: const Icon(Icons.pause),
                  iconSize: 48,
                  color: Colors.white,
                  onPressed: pageManager.pause,
                ));
        }
      },
    );
  }
}

class NextSongButton extends StatelessWidget {
  const NextSongButton({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final pageManager = getIt<PageManager>();
    return ValueListenableBuilder<bool>(
      valueListenable: pageManager.isLastSongNotifier,
      builder: (_, isLast, __) {
        return IconButton(
          icon: const Icon(Icons.skip_next),
          iconSize: 32,
          onPressed: (isLast) ? null : pageManager.next,
        );
      },
    );
  }
}

class ChangeSpeedButton extends StatefulWidget {
  const ChangeSpeedButton({Key? key}) : super(key: key);

  @override
  State<ChangeSpeedButton> createState() => _ChangeSpeedButtonState();
}

class _ChangeSpeedButtonState extends State<ChangeSpeedButton> {
  var selectedValue = 1.0;

  @override
  Widget build(BuildContext context) {
    final pageManager = getIt<PageManager>();
    return DropdownButtonHideUnderline(
      child: DropdownButton(
          icon: const Visibility(
              visible: false, child: Icon(Icons.arrow_downward)),
          value: selectedValue
              .toString(), //we set a value here depending on the button pressed, and call the pagemanager method assing it the value.
          items: dropdownItems,
          onChanged: (value) {
            setState(() {
              selectedValue = double.parse(value.toString());
            });
            pageManager.changeSpeed(selectedValue);
          }),
    );
  }

  List<DropdownMenuItem<String>> get dropdownItems {
    List<DropdownMenuItem<String>> menuItems = [
      const DropdownMenuItem(value: "0.75", child: Text("0.75x")),
      const DropdownMenuItem(value: "1.0", child: Text("1.0x")),
      const DropdownMenuItem(value: "1.25", child: Text("1.25x")),
      const DropdownMenuItem(value: "1.5", child: Text("1.5x")),
      const DropdownMenuItem(value: "1.75", child: Text("1.75x")),
      const DropdownMenuItem(value: "2.0", child: Text("2.0x")),
    ];
    return menuItems;
  }
}

class CurrentMetadata extends StatelessWidget {
  const CurrentMetadata({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final pageManager = getIt<PageManager>();
    return ValueListenableBuilder<MediaItem?>(
      valueListenable: pageManager.currentSongMetadataNotifier,
      builder: (context, mediaItem, child) {
        if (mediaItem == null) {
          return SizedBox.shrink();
        }
        return Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.network((mediaItem.artUri ?? '').toString()),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(mediaItem.extras!['chapterName'],
                          overflow: TextOverflow.fade,
                          style: Theme.of(context)
                              .textTheme
                              .titleMedium
                              ?.copyWith(fontWeight: FontWeight.w700)),
                      const SizedBox(height: 6),
                      Text(
                        mediaItem.title,
                        overflow: TextOverflow.fade,
                        style: Theme.of(context).textTheme.titleSmall,
                      ),
                      const SizedBox(height: 6),
                      Text(
                        'By ${mediaItem.artist}',
                        overflow: TextOverflow.fade,
                        style: Theme.of(context).textTheme.titleSmall,
                      ),
                    ],
                  ),
                  IconButton(
                      icon: const Icon(Icons.favorite),
                      color: Colors.red,
                      onPressed: () {}),
                ],
              ),
            )
          ],
        );

        // Text(mediaItem.album ?? ''),
        // Text(mediaItem.displaySubtitle ?? ''),
      },
    );
  }
}

PageManager.dart
import 'package:flutter/foundation.dart';
import 'package:podfic_app/models/getpodficlist_model.dart';
import 'package:podfic_app/models/series_model.dart';
import 'package:podfic_app/notifiers/chapterObject_notifier.dart';
import 'package:podfic_app/utils/api_service.dart';
import 'notifiers/play_button_notifier.dart';
import 'notifiers/progress_notifier.dart';
import 'notifiers/repeat_button_notifier.dart';
import 'services/playlist_repository.dart';
import 'package:audio_service/audio_service.dart';
import 'services/service_locator.dart';

class PageManager {
  // Listeners: Updates going to the UI
  final currentSongMetadataNotifier = ValueNotifier<MediaItem?>(null);
  final playlistNotifier = ValueNotifier<List<String>>([]);
  final progressNotifier = ProgressNotifier();
  final repeatButtonNotifier = RepeatButtonNotifier();
  final isFirstSongNotifier = ValueNotifier<bool>(true);
  final playButtonNotifier = PlayButtonNotifier();
  final isLastSongNotifier = ValueNotifier<bool>(true);
  final isShuffleModeEnabledNotifier = ValueNotifier<bool>(false);
  final _audioHandler = getIt<AudioHandler>();
  List<Chapter>? chapterObject = getIt<ChapterObject>().chapterObject.value;

  // Events: Calls coming from the UI
  void init() async {
    await loadPlaylist();
    _listenToChangesInPlaylist();
    _listenToPlaybackState();
    _listenToCurrentPosition();
    _listenToBufferedPosition();
    _listenToTotalDuration();
    _listenToChangesInSong();
    // _startPlaying();
  }

  Future<void> loadPlaylist() async {
    final mediaItems = seriesItems.chapterList?.map((chapter) {
          final _podficInfo = chapter.podficInfo;
          return MediaItem(
            id: _podficInfo.id.toString(),
            artUri: Uri.parse(_podficInfo.coverArt!),
            artist: seriesItems.author,
            title: seriesItems.title!,
            extras: {
              'url': _podficInfo.url,
              'chapterName':
                  "Chapter ${_podficInfo.chapterNumber}: ${_podficInfo.title}"
            },
          );
        }).toList() ??
        [];
    _audioHandler.addQueueItems(mediaItems);
  }

  // void _setInitialPlaylist() {
  //   final _seriesInfo = getIt<SeriesInfo>();
  //   final _playlist = SeriesInfo(chapterList: chapterItems);
  // }

  void play() => _audioHandler.play();
  void pause() => _audioHandler.pause();
  void seek(Duration position) => _audioHandler.seek(position);
  void previous() => _audioHandler.skipToPrevious();
  void next() => _audioHandler.skipToNext();
  void repeat() {}
  void shuffle() {}
  void add() async {
    //don't need this for now.
    final songRepository = getIt<PlaylistRepository>();
    final song = await songRepository.fetchAnotherSong();
    final mediaItem = MediaItem(
      id: song['id'] ?? '',
      album: song['album'] ?? '',
      title: song['title'] ?? '',
      extras: {'url': song['url']},
    );
    _audioHandler.addQueueItem(mediaItem);
  }

  void remove() {
    //don't need this for now.
    final lastIndex = _audioHandler.queue.value.length - 1;
    if (lastIndex < 0) return;
    _audioHandler.removeQueueItemAt(lastIndex);
  }

  void dispose() {
    _audioHandler.stop();
  }

  void _listenToChangesInPlaylist() {
    _audioHandler.queue.listen((playlist) {
      if (playlist.isEmpty) {
        playlistNotifier.value = [];
        currentSongMetadataNotifier.value = '' as MediaItem?;
      } else {
        final newList = playlist.map((item) => item.title).toList();
        playlistNotifier.value = newList;
      }
      _updateSkipButtons();
    });
  }

  void _listenToPlaybackState() {
    _audioHandler.playbackState.listen((playbackState) {
      final isPlaying = playbackState.playing;
      final processingState = playbackState.processingState;
      if (processingState == AudioProcessingState.loading ||
          processingState == AudioProcessingState.buffering) {
        playButtonNotifier.value = ButtonState.loading;
      } else if (!isPlaying) {
        playButtonNotifier.value = ButtonState.paused;
      } else if (processingState != AudioProcessingState.completed) {
        playButtonNotifier.value = ButtonState.playing;
        logger.i('Reproduciendo');
      } else {
        _audioHandler.seek(Duration.zero);
        _audioHandler.pause();
      }
    });
  }

  void _listenToCurrentPosition() {
    AudioService.position.listen((position) {
      final oldState = progressNotifier.value;
      progressNotifier.value = ProgressBarState(
        current: position,
        buffered: oldState.buffered,
        total: oldState.total,
      );
    });
  }

  void _listenToBufferedPosition() {
    _audioHandler.playbackState.listen((playbackState) {
      final oldState = progressNotifier.value;
      progressNotifier.value = ProgressBarState(
        current: oldState.current,
        buffered: playbackState.bufferedPosition,
        total: oldState.total,
      );
    });
  }

  void _listenToTotalDuration() {
    _audioHandler.mediaItem.listen((mediaItem) {
      final oldState = progressNotifier.value;
      progressNotifier.value = ProgressBarState(
        current: oldState.current,
        buffered: oldState.buffered,
        total: mediaItem?.duration ?? Duration.zero,
      );
    });
  }

  void _listenToChangesInSong() {
    _audioHandler.mediaItem.listen((mediaItem) {
      currentSongMetadataNotifier.value = mediaItem;
      _updateSkipButtons();
    });
  }

  void _updateSkipButtons() {
    final mediaItem = _audioHandler.mediaItem.value;
    final playlist = _audioHandler.queue.value;
    if (playlist.length < 2 || mediaItem == null) {
      isFirstSongNotifier.value = true;
      isLastSongNotifier.value = true;
    } else {
      isFirstSongNotifier.value = playlist.first == mediaItem;
      isLastSongNotifier.value = playlist.last == mediaItem;
    }
  }

  void changeSpeed(value) {
    _audioHandler.setSpeed(value);
  }

//   void _startPlaying(){
//   _audioHandler.
// }
}

// class PlaySpeedNotifier extends ValueNotifier {
//   PlaySpeedNotifier() : super(initialSpeed);
//   static const initialSpeed = 1.0;
//   var speed = initialSpeed;

//    void changeSpeed(value) {
//     speed = value;
//     _audio
//   }

// }

Audiohandler.dart
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
import 'package:podfic_app/utils/api_service.dart';

Future<AudioHandler> initAudioService() async {
  return await AudioService.init(
    builder: () => MyAudioHandler(),
    config: const AudioServiceConfig(
      androidNotificationChannelId: 'com.mycompany.myapp.audio',
      androidNotificationChannelName: 'FanPods',
      androidNotificationOngoing: true,
      androidStopForegroundOnPause: true,
    ),
  );
}

class MyAudioHandler extends BaseAudioHandler {
  final _player = AudioPlayer();
  final _playlist = ConcatenatingAudioSource(children: []);

  MyAudioHandler() {
    loadEmptyPlaylist();
    _notifyAudioHandlerAboutPlaybackEvents();
    _listenForDurationChanges();
    _listenForCurrentSongIndexChanges();
  }
  Future<void> loadEmptyPlaylist() async {
    try {
      await _player.setAudioSource(_playlist);
    } catch (e) {
      logger.i('algo paso con loadEemptyplaylist');
    }
  }

  // Future<void> startPlaying() => _player.setAudioSource(_playlist);

  @override
  Future<void> addQueueItems(List<MediaItem> mediaItems) async {
    // manage Just Audio
    final audioSource = mediaItems.map(_createAudioSource);
    _playlist.addAll(audioSource.toList());
    // notify system
    final newQueue = queue.value..addAll(mediaItems);
    queue.add(newQueue);
    logger.i(newQueue);
  }

  UriAudioSource _createAudioSource(MediaItem mediaItem) {
    return AudioSource.uri(
      Uri.parse(mediaItem.extras!['url']),
      tag: mediaItem,
    );
  }

  @override
  Future<void> play() => _player.play();

  @override
  Future<void> pause() => _player.pause();

  void _notifyAudioHandlerAboutPlaybackEvents() {
    _player.playbackEventStream.listen((PlaybackEvent event) {
      final playing = _player.playing;
      playbackState.add(playbackState.value.copyWith(
        controls: [
          MediaControl.skipToPrevious,
          if (playing) MediaControl.pause else MediaControl.play,
          MediaControl.skipToNext,
        ],
        systemActions: const {
          MediaAction.seek,
        },
        androidCompactActionIndices: const [0, 1, 3],
        processingState: const {
          ProcessingState.idle: AudioProcessingState.idle,
          ProcessingState.loading: AudioProcessingState.loading,
          ProcessingState.buffering: AudioProcessingState.buffering,
          ProcessingState.ready: AudioProcessingState.ready,
          ProcessingState.completed: AudioProcessingState.completed,
        }[_player.processingState]!,
        playing: playing,
        updatePosition: _player.position,
        bufferedPosition: _player.bufferedPosition,
        speed: _player.speed,
        queueIndex: event.currentIndex,
      ));
    });
  }

  @override
  Future<void> seek(Duration position) => _player.seek(position);

  void _listenForDurationChanges() {
    _player.durationStream.listen((duration) {
      final index = _player.currentIndex;
      final newQueue = queue.value;
      if (index == null || newQueue.isEmpty) return;
      final oldMediaItem = newQueue[index];
      final newMediaItem = oldMediaItem.copyWith(duration: duration);
      newQueue[index] = newMediaItem;
      queue.add(newQueue);
      mediaItem.add(newMediaItem);
    });
  }

  @override
  Future<void> skipToNext() => _player.seekToNext();
  @override
  Future<void> skipToPrevious() => _player.seekToPrevious();

  void _listenForCurrentSongIndexChanges() {
    _player.currentIndexStream.listen((index) {
      final playlist = queue.value;
      if (index == null || playlist.isEmpty) return;
      mediaItem.add(playlist[index]);
      logger.i(playlist);
    });
  }

  @override
  Future<void> addQueueItem(MediaItem mediaItem) async {
    // manage Just Audio
    final audioSource = _createAudioSource(mediaItem);
    _playlist.add(audioSource);
    // notify system
    final newQueue = queue.value..add(mediaItem);
    queue.add(newQueue);
  }

  @override
  Future<void> removeQueueItemAt(int index) async {
    // manage Just Audio
    _playlist.removeAt(index);
    // notify system
    final newQueue = queue.value..removeAt(index);
    queue.add(newQueue);
  }

  @override
  Future<void> skipToQueueItem(int index) async {
    if (index < 0 || index >= queue.value.length) return;
    if (_player.shuffleModeEnabled) {
      index = _player.shuffleIndices![index];
    }
    _player.seek(Duration.zero, index: index);
  }

  @override
  Future<void> stop() async {
    await _player.dispose();
    return super.stop();
  }
}

I tried including pageManager.play in the init section of Player and PageManager, but nothing happens. I think I need to set the audiosource as a concatenatingAudioSource, but I created a method to execute it and passed it _playlist, running it under     _listenForCurrentSongIndexChanges(), but nothing happened.

A: Realized the play method was executing before the init method finished, so simple delay worked.


text:
Q: How to refresh/reload WooCommerce checkout page after adding a coupon code (wordpress)? I need to reload the entire WooCommerce checkout page after adding a coupon code.
I tried the following code but it doesn't reload it.
The reason why I need this function:
Prices of the review table turns to defalut language prices after adding the coupon code.
When I refresh the page, it shows translated language prices, so I need to reload it.
Would you please let me know how to reload it?
Added this code in a checkout page:
jQuery(document).ajaxComplete(function(event, xhr, settings) {
    if (settings.url === '/?wc-ajax=apply_coupon') {
        location.reload();
    }
});

jQuery(document).ajaxComplete(function(event, xhr, settings) {
    if (settings.url === '/?wc-ajax=apply_coupon') {
    jQuery('body').trigger('update_checkout');
    }
});

Order review table:

Template Type

1

<bdi>$820,000</bdi>

<bdi>$820,000</bdi>

<bdi>$820,000</bdi>

Apply coupon:

        Have a coupon? Click here to enter your code

                <form class="checkout_coupon woocommerce-form-coupon" method="post" style="">

If you have a coupon code, please apply it below.

                        <input type="text" name="coupon_code" class="input-text" placeholder="Coupon code" id="coupon_code" value="">

                        <button type="submit" class="button" name="apply_coupon" value="Apply Coupon">Apply Coupon</button>

                </form>

A: You should use
jQuery('body').trigger('update_checkout');

instead of
location.reload();

Alternative
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);

function woocommerce_custom_update_checkout()
{
  if (is_checkout()) {
?>

A: In case someone who needs it
It's working with the following code:
jQuery( document.body ).on( 'applied_coupon_in_checkout removed_coupon_in_checkout', function () {
    location.reload();
} );


text:
Q: AppleTalk framework not found I have a library which was Building perfectly fine in MacOSX10.10 XCode5.0.2 I was using Base SDK 10.8 and deployment target 10.6. now I have to ported that solution to MacOSX10.11 and Deployment target 10.9 in Xcode 7.2. one of my target has dependency on AppleTalk framework, when I tried to Build it It started giving error AppleTalk Framework not found I looked in SDKs folder APPleTalk Framework was not there in case of SDK10.11, but it was there in case of SDK10.8.
Is there any way i can get AppleTalk framework on MacOSX10.11 as I have read somewhere that AppleTalk is no longer Part of Framework.

A: From: https://en.wikipedia.org/wiki/AppleTalk

With the purchase of NeXT and subsequent development of Mac OS X,
AppleTalk was strictly a legacy system. Support was added to OS X in
order to provide support for the large number of existing AppleTalk
devices, notably laser printers and file shares, but alternate
connection solutions common in this era, notably USB for printers,
limited their demand. As Apple abandoned many of these product
categories, and all new systems were based on IP, AppleTalk became
less and less common. AppleTalk support was finally removed from the
MacOS in Mac OS X v10.6 in 2009.[32]


text:
Q: XSLTemplate in Mono i have just comleted my project in c#.net and now the client has put up an horrible requirement that this application should be compatible with other Operating Systems as well such as Linux. So, i have to move towards mono development and i am using tool xamarin studio 4.0.12
The problem i am facing is about xslTemplate as mono does not support MSXML2. I have tried using MSXML but it does not contain xslTemplate.
What should i do? Can anyone help?

A: For running an xsl[t] transformation over xml, you should be able to use either System.Xml.Xsl.XslTransform or System.Xml.Xsl.XslCompiledTransform from System.Xml.dll. The API should be largely identical to the Microsoft implementations:

*

*mono, XslCompiledTransform

*mono, XslTransform

*microsoft, XslCompiledTransform

*microsoft, XslTransform


text:
Q: Site too Slow to establish db connection? After deployment site was too slow on analysis it takes time at db connection side.
DB is in remote server.
Trying queries without WordPress gives faster response.
But WordPress takes around 40 sec waiting for DB ?

A: This has something to do with your database server to speed up response time. Also may be it is validating your IP from where your are pinging . If you can whitelist your IP,the connection would be more reliable and may increase ping time.


text:
Q: I am trying log match for last row in form submission against an index I created I have a forms responses sheet and an index sheet. The index sheet has Name, Location, Email. I am needing to get the value of the last row in form responses and find a name match in my index sheet. Then log the location and email. Right now my code finds all matches and displays them. As I stated before I only want the match for last row.
    function findLocation() {
  var ss = SpreadsheetApp.getActive();
  var sh1 = ss.getSheetByName('Form Responses');
  var vs1 = sh1.getRange('I3:I' + sh1.getLastRow()).getValues().flat();
  var sh2 = ss.getSheetByName('Match');
  var vs2 = sh2.getRange('A2:C' + sh2.getLastRow()).getValues();
  var matchRows = vs2.filter(row => row[0].length && vs1.includes(row[0]));
  matchRows.forEach(row => {
    var siteMatch = row[1];
    var emailMatch = row[2];
    Logger.log(JSON.stringify(siteMatch));
    Logger.log(JSON.stringify(emailMatch));
  });
}

Screenshot for clarification

A: Description
I made a simple test data set that I think is similar to yours.  The sample script finds the name in index sheet Match that matches the last form response row.
Form Responses

Match

Sample script
function findLocation() {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh1 = ss.getSheetByName('Form Responses');
    var vs1 = sh1.getRange(sh1.getLastRow(),1).getValue();
    var sh2 = ss.getSheetByName('Match');
    var vs2 = sh2.getRange('A2:C' + sh2.getLastRow()).getValues();
    var matchRow = vs2.find( row => row[0] ===  vs1 );
    Logger.log(matchRow);
  }
  catch(err) {
    Logger.log(err);
  }
}

Execution log
9:51:59 AM  Notice  Execution started
9:52:00 AM  Info    [John, A, john@somemail.com]
9:52:01 AM  Notice  Execution completed

References

*

*Array.find()


text:
Q: Действие jQuery при нажатии на 2 класса Работает:
$(document).on("click", ".class1", function(e){
  $('#id').css("display", 'none');
});

Возможно ли обработка 2 классов так что-то типа:
$(document).on("click", ".class1",".class2", function(e){

Или однозначно надо присваивать один класс всем блоками например:

1

1

A: jQuery прекрасно работает с CSS селекторами

$('.one,.two').on('click', function(e) {
  console.log(this.innerHTML)
})

<button class="one">1</button>
<button class="two">2</button>

A: Вполне себе работает перечисление, если это необходимо:

$(document).on('click', '.one,.two', function(e) {
  console.log($(this).text());
});
div {
  width: 40px;
  height: 40px;
  border: 1px solid red;
}

1

2


text:
Q: On the union of algebraic sets The definition of an algebraic set is given by:

Let $S \subseteq k[x_1,x_2,...,x_n]$ be a set of polynomials. The algebraic set defined by S is $$
V(S) = \{(a_1,a_2,...a_n) \in \mathbb{A}^n (k) : P(a_1,a_2,...,a_n)=0, \forall P \in S \}
$$

Then I was asked to prove that given $X= V(f_1,..f_s)$ and $Y=V(g_1,...,g_t)$ are algebraic sets in $\mathbb{A}(k)$, then $X \cup Y$ is also an algebraic set.
My interpretation of the notation $X= V(f_1,..f_s)$ was that
$$X = \{(a_1,a_2,...a_n) \in \mathbb{A}^n (k) : f_i=0, i=1,...,s\}
$$
Then the solution I came up with was that $$
X \cup S = \{(a_1,...,a_n) \in \mathbb{A}^n(k) : f_ig_j = 0\}
$$
so it's an algebraic subset.
However, I'm not sure if this is the correct solution.


text:
Q: Using C# with Crystal Reports, How Can I Create 4-Up Subreports? The simplest example that I can provide for what I want to do is this:
I need to create a Report, whose only requirement is that I have (4) of the same subreport on the page (imagine 4 portrait-oriented post cards on a page), each quadrant using a separate row from my datatable, yet all 4 are identical in terms of fields.  If there are more than 4, it needs to carry over to a new page with the same format.
I'm using C# and the built-in Crystal Reports Basic for the task.

A: Couple of suggestions:

*

*What about structuring your subreport to have two entries side by side, bind two rows to that subreprt, and handle formatting such that the last one on the right side is blanked should you have an odd number of rows?

*Or there may be a way to specify your page size to be 1/4 of the full page size (4.25 x 6.5 inches) and then fit four reports on one page.


text:
Q: CSV Files -How to Handle Bad Layers I have moved my QGIS Project to a new Directory. On opening the project in new folder, Handle Bad Layer window pops up with a list of shp and csv files. I am able to correct the shp files using browse button but browse button is disabled when I am trying to provide the new path for csv files.

A: You needn't go into the .qgz file. Although there is no browse button, you can edit the file path in the "Datasource" field of the "Handle Unavailable Layers" window that pops up when you first open the project in QGIS. Click "Apply Changes" after the edit and if the window or line disappears, then the new path is working fine.

A: You could open the project file in a text editor like Notepad++ and replace the old csv folder path(s) to the new and save it.  The project file is just xml so you can open, read, and write to the file.


text:
Q: @Input gets the variable name from AngularJS I am trying to migrate my AngularJS app to Angular.
I have some components with bindings which needs to be converted to Angular
AngularJS Code:
<my-comp test="test.data" otherData="test.otherData"><my-comp>

my-comp.ts:
export default {
    template: html,
    bindings: {
        test: '<',
        otherData: '=',
    },
}

my-comp.html:
<div ng-repeat="val in $ctrl.test">
    {{ val }}
</div>

output:
1
2
3
Now I have migrated my-comp.ts from AngularJS to Angular
my-comp.ts:
export class MyCompComponent implements OnInit {
    @Input() test: any;
    @Input() otherData: any;
    ngOnInit() {
        console.log('test: ', this.test);  // prints "test.data"
        console.log('otherData: ', this.otherData); // prints "test.otherData"
    }
}

my-comp.html:
{{ test }}

Actual output:
"test.data"
Expected output:
1 2 3
I am using @Input for bindings with '=' and '<'
I downgrade the updated component so it can be used in AngularJS code in
<my-comp test="test.data" otherData="test.otherData"><my-comp>

without having to write it as
<my-comp [test]="test.data" [otherData]="test.otherData"><my-comp>

Update:
Docs
Using NgUpgrade we can use the Angular Component (downgrade) in AngularJS template and pass inputs with [] as regular Angular inputs
<my-comp [test]="test.data" [otherData]="test.otherData"><my-comp>

A: You need to include your component like this, using square brackets. See Property Binding.
<my-comp [test]="test.data" [otherData]="test.otherData"></my-comp>


text:
Q: Why does Android Studio compile my whole app to launch a primitive unit test? Whenever I launch a unit test "from the margin menu" (see screenshot), that does not have any Android dependencies, Android Studio compiles my whole app only to run one primitive assert.
Is it the intended behaviour that my app needs to fully compile? I was expecting that unit tests are extremely fast and compile only those classes mentioned in the test and their dependent classes are to be compiled for unit testing.

Moreover, if I add any Android class, e.g. Application or AppCompatActivity, to the test it will still complete successfully. Every article about testing on Android says that it's impossible to run a unit test that depends on any Android library.

A: Gradle projects are usually structured to have a main source set and a test source set. They are compiled separately and test is configured to depend on main. All Gradle knows is that it needs main if it is supposed to run test. Therefore it compiles all of main before compiling test. You can see that in action when compiling test if you look at the "build" panel. In fact, if any class in main has syntax errors it will not even try to compile test even if that class is not needed for test.


text:
Q: Making per Service Account directories on Storage Bucket I currently have a GCP bucket connected to a load balancer as a CDN for our shared hosting environment. I want to configure the GCP bucket so that each shared host can access their own directory on the bucket using a service account.
How do I configure my GCP bucket so that a service account only has write access to their own folder on the bucket.


text:
Q: Unable to get a "null" value from Firebase snapshot in Unity on android I want to do x when FirebaseRef snapshot.Value == null. This works in the Unity Editor everytime but when I do this on the Android device, it fails every time. The app doesn't crash, it just doesn't do anything.
auth is working fine.
database is working fine (I'm getting all other values when the values exist) but when the value doesn't exist, that's where I have the issue.
Here is my sudo code, any help would be appreciated.
ref.Child("Location/That/Doesnt/Exist").GetValueAsync().ContinueWithTask(Task => {
  if (task.IsFaulted){
    //Do something
  }
  else if (task.IsCompleted){
    DataSnapshot snap = task.Result;
    if(snap.Value == null){
      //This is what hangs. I get here and it just does nothing.
    }
  }
});

I'm so lost. I'm not sure how to figure this out. I get no errors but it's like the function just stops there.
Thanks all!
EDIT
So what I'm doing to get around this is to create a DB entry in the path with key == "0" and value == 0. Then I say if the ChildCount is greater than 1 and that child has more than 1 child, proceed.
I feel like this is a really poor approach.

A: I was getting the same error. I caught an exception of this, and i got NullReference, it's seems that on android when it's not found on database return Null, so you have to convert this:
if(snap.Value == null){
}
to this:
if (snap==null && snap.Value==null)
You are trying to access to snap.Value when snap object is null.
Sorry my english, i hope this helps you.

A: try trailing slash

"Location/That/Doesnt/Exist/"


text:
Q: Python Tkinter: Passing List Arguments to Populate another List Summary
I am building a Tkinter program in Python 2.7.  The goal is to automatically populate a list with available removable flash drives.  When the user selects a drive or multiple drives from the list, the selected drive(s)(sel_drv) is passed to another function which will search the drive for a specific file type and generate a list to populated on the screen.
The Problem
The issue I am running into is the ordering of the functions.  When the user selects a drive its passed the drv_sel variable which is then appended to the sel_drives list.  I keep getting errors for trying to use the sel_drv before its defined, or TypeErrors.
Important modules:
drive_ctypes.find_rmdrv() -  This function will search the computer for removable drives and populate the list.  (This is working fine)
file_search.file_search(sel_drives) - This function will search the drives(sel_drives) and return a list of all files of a certain type.  (This function works, but I can't pass sel_drive properly.
Background
I am new to programming and Python, including class and OOP.  I would appreciate any resources that might help me learn more about Tkinter and Classes/OOP.
Here is the error
Traceback (most recent call last):
  File "C:\Python27\window.py", line 70, in <module>
    main()
  File "C:\Python27\window.py", line 64, in main
    ex = Example(root)
  File "C:\Python27\window.py", line 13, in __init__
    self.initUI()
  File "C:\Python27\window.py", line 33, in initUI
    for i in sel_files:
TypeError: 'instancemethod' object is not iterable

Here is the code:
from Tkinter import *
import drive_ctypes
import file_search

#global sel_files
#sel_files[]

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

    ## Drive Select List Box
        global rdrive
        rdrive = drive_ctypes.find_rmdrv()
        lb = Listbox(self, height=10, selectmode=MULTIPLE)
        for i in rdrive:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)
        sel_files = self.onSelect

        lb.grid(row =3, column =2)

    ## File Select List Box
        flb = Listbox(self, height=10, selectmode=MULTIPLE)
        for i in sel_files:
            flb.insert(END, i)
        flb.grid(row =3, column =4)

    def onSelect(self, val):
        sender = val.widget
        drv_sel = sender.curselection()
        print drv_sel
        ## List of Drives Selected
        sel_drives = []
        for i in drv_sel:
            drive_with_gb = rdrive[i]
            ## This trims the name of the drive for the file_search function
            drive = drive_with_gb[:-9]
            ## This is creating a list to pass to the file_search function
            sel_drives.append(drive)
        sel_files = file_search.file_search(sel_drives)
        return sel_files

    def findfiles(self,val):
        sender = val.widget

def main():

Any Assistance is GREATLY appreciated!

A: I amended your example, and made dummy rdrive and sel_files variables. Otherwise I can't reproduce your problem. Have a look at this:
from Tkinter import *

# dummy list so that the code does not relay on actually drives and files
rdrive = ['drive1','drive2','drive3']

sel_files = {'drive1': ['file1','file2'],
                  'drive2': ['file3','file4'],
                  'drive3': ['file6','file5']}

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        # Drive Select List Box
        # global rdrive
        # rdrive = drive_ctypes.find_rmdrv()

        # use dummy rdrive instead of physical drives. Otherwise,
        # cant reproduce the problem.

        self.lb = Listbox(self, height=10, selectmode=MULTIPLE)
        for i in rdrive:
            self.lb.insert(END, i)

        self.lb.bind("<<ListboxSelect>>", self.onSelect)

        self.lb.grid(row =3, column =2)

        ## File Select List Box
        self.flb = Listbox(self, height=10, selectmode=MULTIPLE)

        self.flb.grid(row =3, column =4)

    def onSelect(self, event):
        # most changes are here. GUI programming is event driven, so you need
        # to get the list of files for selected drive (i.e. when selection even occurs).
        # Also here you respond the the even, so that the right list is populated.

        # get widget (i.e. right listbox) and currently selected item(s)
        widget = event.widget
        selection=widget.curselection()

        files_avalibe = []

        # if something was selected, than get drives for which it was selected
        # and retrieve files for each drive
        if selection:

            for drive_i in selection:
                selected_drive = rdrive[drive_i]
                files_avalibe += sel_files[selected_drive]

            print(files_avalibe)

        # once we have files from the selected drive, list them
        # in the right list box
        self.update_file_list(files_avalibe)

    def update_file_list(self, file_list):
          # updates right listbox
          self.flb.delete(0, END)
          for i in file_list:
            self.flb.insert(END, i)

    def findfiles(self,val):
        sender = val.widget

root = Tk()
f = Example(root)
root.mainloop()

How it works is shown here:

Sorry for not detailed explanation what was changed. But I think you can figure these things yourself. The main problem with your code was sel_files = self.onSelect. This just assigns a function to sel_files, not it output. To get the actual file list for a selected drive, need to do it in onSelect.


text:
Q: React - Import dynamically path to pdf file Firstly, my page will make an http request to an API
API then response an object which have a path: ./assets/sample.pdf
I want to get urlPdf from import urlPdf from response.path
How can I do that ?

A: I'd try with https://www.npmjs.com/package/react-pdf
import React, { useState } from 'react';
import { Document, Page } from 'react-pdf';

const App = () => {
  const [pageNumber, setPageNumber] = useState();
  const [numPages, setNumPages] = useState();
  const [urlPdf, setUrlPdf] = useState();

  const _onDocumentLoadSuccess = ({ numPages }) => setNumPages(numPages);

  const fetchPdfPath = ({
    // logic handle get path...
    // setUrlPdf(response.data);
  })

  return (

      {urlPdf && (
        <Document
          file={urlPdf}
          onLoadSuccess={_onDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
        </Document>
      )}

Page {pageNumber} of {numPages}

  );
}

A: Oh super simple. Just const result = require(response.path)


text:
Q: Stata pie chart error Hi I'm trying to create a pie chart that has a lot of slices. For some reason I get an error when running this code.
My code
graph pie ccounter if year==1900 & ccounter>100 & labforce==2, over(occ1950)

and I get this error
(note:  areastyle p193pie not found in scheme, default attributes used)
(note:  areastyle p194pie not found in scheme, default attributes used)
(note:  areastyle p195pie not found in scheme, default attributes used)
(note:  areastyle p196pie not found in scheme, default attributes used)
option min() incorrectly specified

Note that the variable occ1950 has more than 100 values. I don't know whether this is what causing the problem.
Extra Information
I use this code to create the variable ccounter
bys mcdstr year occ: gen counter=_n
bys mcdstr year occ: egen ccounter=max(counter)

I used this to calculate the number of people working in each industry by year and location.

A: The problem lies in that the variable occ1950 has too much unique values. Let us examine the problem using a CSV dataset of only 40 countries.
country,fdi
Afghanistan,141.391
Algeria,541.478
Angola,238.637
Antigua and Barbuda,1.653
Argentina,205.691
Bahamas,21.927
Bahrain,1.317
Bangladesh,50.298
Barbados,2.816
"Bolivia, Plurinational State of",41.572
Botswana,87.649
Brazil,455.5649999999999
British Virgin Islands,12387.568
Brunei Darussalam,21.02
Cambodia,672.6800000000001
Cameroon,30.159
Cape Verde,3.783
Cayman Islands,15323.116
Chile,53.149
Colombia,49.047
Congo,112.104
"Congo, Democratic Rep. of",302.505
Costa Rica,.826
Côte d' Ivoire,27.099
Dominican Republic,.112
Ecuador,93.673
Egypt,191.59
Equatorial Guinea,80.21700000000001
Eritrea,16.269
Ethiopia,205.824
Fiji,38.742
Gabon,76.66500000000001
Ghana,129.068
Guinea,97.413
Guyana,79.899
Honduras,2.6
"Hong Kong, China",124987.422
India,291.567
Indonesia,850.0709999999999
"Iran, Islamic Republic of",480.71

After loading this into Stata 14, we can observe that
graph pie fdi, over(country)

produces the error: option min() incorrectly specified.
If we now reduce the dataset to simply 30 countries by: drop _n > 30. We would be able to get a pie chart.
This suggests that you should collapse your data, take the n categories with the largest ccounter and then classify the other classes as "other".
The magic number is 36. So you can have at most 36 unique categories in your pie chart.


text:
Q: Installing PCL using CMake on Ubuntu 18.04 I am using PCL without problems for about a month now. I was following this tutorial:
b-spline Fitting when I realized that I do not have the full PCL installed.
I installed PCL using the aptitude package as recommended on the official download page. However, it does not include a /on_nurbs directory inside of the /surface directory. It is mentioned at the beginning of the tutorial that a variable called BUILD_surface_on_nurbs needs to be enabled in order for the code to work. However, I could not find out where this variable is, and how to toggle it if I am installing PCL using apt-get.
That's why I resorted to installing PCL again, however, by cloning the GitHub repo and using CMake for building. With the help of cmake-GUI I was able to spot the variable and set toggled it accordingly.
I generated the build files after that, and that was my last step in re-installing PCL.
I then tried to run the tutorial, however the directory structure is significantly different than the one installed using the apt-get tool. Though I was able to go around this issue by specifying the target_include_path for each module accordingly as shown below in the CMakeLists.txt file, I was faced by another 2 errors when running the "make" command; namely, make[2]: **no rule to make target.
Is there another step that needs to be done in order to finalize the installation? Or am I missing something?
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)

project(bspline_fitting)

find_package(PCL 1.7 REQUIRED)

include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})

add_executable (bspline_fitting bspline_fitting.cpp)
target_link_libraries (bspline_fitting ${PCL_LIBRARIES})
target_include_directories(bspline_fitting
                            PRIVATE
                            usr/include/pcl-1.8.1/common/include
                            usr/include/pcl-1.8.1/features/include
                            usr/include/pcl-1.8.1/filters/include
                            usr/include/pcl-1.8.1/geometry/include
                            usr/include/pcl-1.8.1/io/include
                            usr/include/pcl-1.8.1/kdtree/include
                            usr/include/pcl-1.8.1/octree/include
                            usr/include/pcl-1.8.1/registration/include
                            usr/include/pcl-1.8.1/search/include
                            usr/include/pcl-1.8.1/sample_consensus/include
                            usr/include/pcl-1.8.1/surface/include
                            usr/include/pcl-1.8.1/visualization/include)


text:
Q: HttpResponseRedirect not working Django 1.7 I am having a problem with HttpResponseRedirect in Django. It seems that, whatever parameters I try, it either throws an error, or it redirects without changing the URL. I am using it on a custom login_user view, and I want the URL in the address bar to change after they are redirected. If I use redirect instead of HttpResponseRedirect, it does not change. Either way, I can get it to serve the correct template, but the URL stays the same. Being new to Django, it would be helpful if someone could explain to me how to do this and why my current code is not working.
I have seen a couple of similar questions to mine on Stack Exchange, but the answers have not helped.
Here are the relevant parts of my views.py (please note the indenting has gone weird due to copying and pasting in here, and is not the cause of the error).
from django.http import *
from django.contrib.auth import authenticate, login, logout

def login_user(request):
    logout(request)
    username = password = ''
if request.POST:
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('dashboard')
        else:
            state = "Your account is not active, please contact the app administrator."
    else:
        state = "Your username and/or password were incorrect."
state = "Please log in below..."
context = RequestContext(request, {
    'state': state,
    'username': username,
})
return render_to_response('bank/auth.html', {}, context)

dashboard is the name of another view, and it works fine in a redirect from my index view. I've also tried hard-coding the url in, but that doesn't work either. Any suggestions?? Thanks.

A: If you use HttpResponseRedirect, you must provide the url, not the name of the url.
You can either get the url by using reverse:
from django.core.urlresolvers import reverse

def my_view(request):
    ...
    return HttpResponseRedirect(reverse('dashboard'))

or by using the redirect shortcut.
from django.shortcuts import redirect

def my_view(request):
    ...
    return redirect('dashboard')

If using the either of the above approaches does not work, then there's probably a mistake somewhere else in the view. It's difficult to tell where, since the indentation is incorrect. Try adding some logging or print statements to see if you are really returning the redirect where you think you are.

A: In this particular case, the problem wasn't anything to do with my view code, it was actually a problem caused through using JQuery mobile. I found the answer here: Error with Redirects in JQuery Mobile which was to set the data-url attribute on the page div.
However, I have up-voted Alasdair's answer, as his way is the correct one of the ways I had tried.

A: I personally prefer the simple way as follows:
In urls.py:
url(r'^dashboard/$', 'appname.views.dashboard_view', name='dashboard_view'),

In views.py:
from django.http import HttpResponseRedirect

def dashboard_view(request):
    ...
    return HttpResponseRedirect('/dashboard/')


text:
Q: org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException This is my orderservice implementation for creating and saving orders here with the customerid I'm getting customer and customer has a cart and in the cart product list is there and for that product list, I should create an order.
public Order save(int custid) {
        Optional<Customer> cust = customerRepo.findById(custid);//here customer is there and inside customer cart is there inside cart medicine list is there.
        Cart ct= cust.get().getCart();//getting cart from customer
        if(ct.getMedicineList().size()!=0) {//create order only if the medicine list is not empty. there are 8 fields **orderDate,dispatchDate,status,medicineList,totalCost,customer and orderId(GeneratedValue)** I can't set the orderId cuz it is auto generated.
            LocalDate todaysDate = LocalDate.now();
            LocalDate dispatchdate = todaysDate.plusDays(3);
            List<Medicine> orderList= new ArrayList<Medicine>();
            List<Medicine> cartList= new ArrayList<Medicine>();
            cartList=ct.getMedicineList();
            orderList.addAll(cartList);
            Order ord = new Order();
            ord.setCustomer(cust.get());
            ord.setMedicineList(orderList);
            ord.setDispatchDate(dispatchdate);
            ord.setOrderDate(todaysDate);
            ord.setStatus("Placed");
            ord.setTotalCost((float)ct.getTotalAmount());
            logger.info("Add order to the database");
            return orderRepository.save(ord);
        }
        return null;

    }

this is my order controller
@PostMapping("/order/{custid}")
    public ResponseEntity<Order> addOrder(@Valid @PathVariable("custid") int custid) {
        logger.info("Add order in database");
        return new ResponseEntity<>(orderService.save(custid), HttpStatus.OK);
    }

this is my medicine Entity
@Data
@RequiredArgsConstructor
@ToString
@Table(name = "medicine")
@Entity
public class Medicine {
    @Id
    @Column(name = "medicine_id", nullable = false)
    @NonNull
    @GeneratedValue
    private int medicineId;

    @NonNull
    @Size(min = 3, message = "Minimum charecters in medicine name should be 3.")
    @NotEmpty
    @Column(unique = true, name = "medicine_name", nullable = false)

    private String medicineName;

    @NonNull
    @Column(name = "medicine_cost", nullable = false)
    private float medicineCost;

    @NonNull
    @Column(name = "mfd", nullable = false)
    private LocalDate mfd;

    @NonNull
    @Column(name = "expiry_date", nullable = false)
    private LocalDate expiryDate;

    @NonNull
    @Column(name = "medicine_quantity", nullable = false)
    private int medicineQuantity = 1;
    @NonNull
    private String medicineCategory;
    @NonNull
    private String medicineDescription;

    @JsonIgnore
    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "medicineList",fetch = FetchType.EAGER)
    private List<Order> orderList;
}

this is my order Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString

    public class Order {
        @Id
        @Column(name = "orderId")
        @GeneratedValue
        private int orderId;
        @NonNull
        private LocalDate orderDate;
        @ManyToMany(targetEntity = Medicine.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        @JoinTable(name = "ord_med", joinColumns = { @JoinColumn(name = "ord_id") }, inverseJoinColumns = {
                @JoinColumn(name = "med_id") })
        private List<Medicine> medicineList = new ArrayList<>();
        @NonNull
        private LocalDate dispatchDate;
        @NotEmpty
        private float totalCost;
        @NonNull
        private String status;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name="c_ord_fk",referencedColumnName = "customerId")
        @NonNull
        private Customer customer;

    }

here when i try to create order for the list inside cart it gives me [36m.m.m.a.ExceptionHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction]
i'm not sure but i think its because of the id but it is autogenerated. Idk how to create an order object for the list of products or is this the correct way to do it.

A: Actually I found the answer, all I have to do is when you use ManyToMany mapping the cascade type must be cascade = {CascadeType.MERGE,CascadeType.REFRESH} instead of {cascade = CascadeType.ALL} and it works fine. reference JPA: detached entity passed to persist: nested exception is org.hibernate.PersistentObjectException


text:
Q: onEdit Search for specific text and copy corresponding value The Problem
I am attempting to use an onEdit trigger to copy values based on a "key" from one sheet to appropriate column/row on the next sheet.
A script that I found looks up the value and copies over. The only downside is it runs for each row even if the values were already filled in. However, I only want the script to run for the cell that is being edited. Here is a sample sheet.
Here is a link to the sheet that I am working with.
Desired Outcome
What I am looking to achieve is if I insert any value into Column B and it matches what appears on the Directory, then the row that was edited is updated to include values found on Directory. However, it should not affect any previously edited rows.
The Script
function updateEntrees() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var sh1=ss.getSheetByName('Directory');
  var rg1a=sh1.getRange(2,1,sh1.getLastRow()-1,1);
  var vA1a=rg1a.getValues();
  var rg1b=sh1.getRange(2,2,sh1.getLastRow()-1,5);  // Modified
  var vA1b=rg1b.getValues();

  var sh2=ss.getSheetByName('Insert');
  var rg2a=sh2.getRange(2,2,sh2.getLastRow()-1,1);
  var vA2a=rg2a.getValues();
  var rg2b=sh2.getRange(2,3,sh2.getLastRow()-1,5);  // Modified
  var vA2b=rg2b.getValues();

  for(var i=0;i<vA1a.length;i++) {
    for(var j=0;j<vA2a.length;j++) {
      if(vA1a[i][0]==vA2a[j][0]) {
        vA2b[j]=vA1b[i];  // Modified
      }
    }
  }
  rg2b.setValues(vA2b);
}

Example 1:
If in A5 I input "Gary" then the script would look up "Gary" from the Directory sheet and copy over 'Black' and 'Tiger' to the appropriate row. (The script above currently does this...see example 2).

Input Sheet
A
B
C

1
Bob
Orange
Dog

2
Carrie
Blue
Cat

3
Juan
Green
Cat

4
Stephanie
Red
Bird

5
Gary

Here's the "Directory" sheet.

Directory Sheet
A
B
C

1
Bob
Orange
Dog

2
Carrie
Blue
Cat

3
Juan
Green
Cat

4
Stephanie
Red
Bird

5
Gary
Black
Tiger

Example 2:
If I manually change Stephanie's color to Green and the animal to Elephant, when I input "Gary" into the next row, Stephanie's color is reverted back to Red and animal to Bird. I want to only edit the values based on the row that is being edited. So if I type in "Gary" then only Gary's line is affected, not the rest of the lines.

Input Sheet
A
B
C

1
Bob
Orange
Dog

2
Carrie
Blue
Cat

3
Juan
Green
Cat

4
Stephanie
Green
Elephant

5
Gary

A: In your situation, how about the following sample script?
Sample script:
function onEdit(e) {
  const range = e.range;
  const sheet = range.getSheet();
  if (sheet.getSheetName() != "Insert" || range.columnStart != 2 || range.rowStart == 1 || range.isBlank()) return;
  const insertValues = sheet.getRange("B2:B" + sheet.getLastRow()).getValues();
  const directorySheet = e.source.getSheetByName("Directory");
  const obj = directorySheet.getRange("A2:D" + directorySheet.getLastRow()).getValues().reduce((o, [a, ...v]) => (o[a] = v, o), {});
  const values = insertValues.map(([b]) => obj[b] || Array(3).fill(null));
  sheet.getRange(2, 3, values.length, values[0].length).setValues(values);
}

*

*In this sample script, when the dropdown list of column "B" of "Insert" is changed, the values from "Directory" sheet are searched using the dropdown list value. And, those values are put to "Insert" sheet as the overwrite. By this, even when other cells in "Insert" sheet are changed, the changed cells are back using the values of "Directory" sheet.

Note:

*

*This script is run by the simple trigger of OnEdit. So when you directly run the script, an error occurs, because the event object e is not given. Please be careful about this.

Reference:

*

*Simple Triggers


text:
Q: Seq.contains in SQL in Spark Dataframe I have the following data structure:

*

*id: int

*records: Seq[String]

*other: boolean
In a json file, in order to ease testing:
var data = sc.makeRDD(Seq[String](
   "{\"id\":1, \"records\": [\"one\", \"two\", \"three\"], \"other\": true}",
   "{\"id\": 2, \"records\": [\"two\"], \"other\": true}",
   "{\"id\": 3, \"records\": [\"one\"], \"other\": false }"))
sqlContext.jsonRDD(data).registerTempTable("temp")

And I'd like to filter down to just records with one in the records field and other equal to true using just SQL.
I can do it via a filter (see below), but can it be done just using SQL?
sqlContext
    .sql("select id, records from temp where other = true")
    .rdd.filter(t => t.getAs[Seq[String]]("records").contains("one"))
    .collect()

A: Spark SQL supports the vast majority of Hive features, thus you can use array_contains to do the job :
spark.sql("select id, records from temp where other = true and array_contains(records,'one')").show
# +---+-----------------+
# | id|          records|
# +---+-----------------+
# |  1|[one, two, three]|
# +---+-----------------+

Note: In spark 1.5, sqlContext.jsonRDD is deprecated , use the following instead :
sqlContext.read.format("json").json(data).registerTempTable("temp")


text:
Q: Multivariable Calculus - Finding the flux across a vector field out of a hemisphere Past Paper Question
I had an exam today and this old past paper question came up again that I had previously tried. I followed the hints and got an answer of $4π$, with the flux across v out of D being $4π$ and the triple integral over the divergence of v (by the divergence theorem) $8π$, hence the final answer being 8 π - 4 π = 4 π again by the divergence theorem. Is this the correct answer?
Thankyou

A: The flux across $D$ is $-4\pi$ (remember that the normal points downward when you think of $D$ as part of the boundary of $\Omega$). The triple integral of divergence over $\Omega$ is $3\cdot 16\pi/3 = 16\pi$. Thus, the flux across $S$ is $16\pi - (-4\pi) = 20\pi$. (Incidentally, this checks with a direct surface integral computation.)


text:
Q: Turn on GPS from service not Activity on Android I have service where I need to turn on GPS forcefully I tried some of the code which are working good on activity codes are like,
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
    intent.putExtra("enabled", true);
    sendBroadcast(intent);

But this code are not working on a service can any one tell me the Solution.

A: Instead of trying to Switch on GPS forcefully, Use below code to open up Settings to let user enable GPS if he willing to do it. also add appropriate permission in manifest.
 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
 if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER ))
  {
     Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS );
     startActivity(myIntent);
   }

A: *

*It's possible for rooted phones only.

*BusyBox must be installed.

*Not trivial in code.

*Messes with /system area and therefore dangerous (soft-brick possible)

If you are brave enough try the sample I created accumulating all pieces of information across internet. I'm neither credited not responsible.
http://rapidshare.com/files/3977125468/GPSToggler-20130214.7z
(for brave hearts only)


text:
Q: Does a non-conjugate cut point imply closed geodesics? Let $(M, g)$ be a complete Riemannin manifold and suppose $p, q \in M$ re points s.t. $d_g(p, q)$ is equal to the distance from $p$ to its cut locus, with $q \in \text{Cut}(p)$. If $q$ is not conjugate to $p$ along some minimizing geodesic segment, does it follow that there exist exactly two minimizing geodesic segments $\gamma_1, \gamma_2 : [0, b] \to M$ from $p$ to $q$ s.t. $\gamma_1'(b) = - \gamma_2'(b)$?
My first thought was to make a closed loop going from $p$ to $q$ along $\gamma_1$ and then from $q$ to $p$ along $-\gamma_2$. Then I wanted to deform this loop into one of the geodesics to obtain a Jacobi field vanishing at $q$, but I fail to see how each curve would be a geodesic, or how this depends on $\gamma_1'(b) \neq -\gamma_2'(b)$. Then I started wondering if there was something missing from the problem. If I reverse the direction of $\gamma_2$ and concatenate both geodesics, I would obtain a closed geodesic. This seems to imply that on any complete manifold where the closest point on the cut locus of $p$ to $p$ is not conjugate to $p$, we would have closed geodesics. Is this even true?