text:
Q: How to save data to mysql after looping a multidimensional array I am new to PHP and i'm having a multidimensonal array. S i dug around about how to loop through the said array. Fortunately i got around that, but cannot seem to get each individual value separately. Let me show you what i mean:
This is my array:

Array
(
    [0] => Array
        (
            [city] => Nairobi
            [email] => dummy@email.com
            [land_mark] => dummylandmark
            [order_at] => dummytime
            [payment_mode] => dummymode
            [phone] => dummyphone
            [receipt_code] => dummycode
            [shipping_mode] => dummymode
            [user_name] => dummyuser
            [products] => Array
                (
                    [0] => Array
                        (
                            [amount] => 2000
                            [name] => dummyname
                            [p_id] =>
                            [quantity] => 1
                            [subtotal] => 1
                        )

                    [1] => Array
                        (
                            [amount] => 2500
                            [name] => dummyname1
                            [p_id] =>
                            [quantity] => 1
                            [subtotal] => 1
                        )

                )

        )

)

JSON Array:

[

  {
    "receipt_code": "2016-12-17_23:09:55_obpekqaqdn",
    "payment_mode": "Cash On Delivery",
    "city": "Nairobi",
    "email": "admin@buyathome.com",
    "phone": "0715611306",
    "order_at": "2016-12-17 23:09:55",
    "user_name": "Admin",
    "shipping_mode": "I'll Collect Myself",
    "land_mark": "Postal office"
  },
  {
    "products": [
      {
        "amount": 9000,
        "description": "Experience with the Itel phone ",
        "id": 45,
        "quantity": "1",
        "title": "Itel"
      },
      {
        "amount": 200,
        "description": "Do BBS fee r be ft gr",
        "id": 46,
        "quantity": "1",
        "title": "The he hd"
      }
    ]
  }
]

And the snippet:

//  Multi-dementional Source Array
//convert json object to php associative array
 $data = json_decode(preg_replace('/\s+/', '', $jsondata), true);
//  Output array
displayArrayRecursively($data);

/**
 * Recursive function to display members of array with indentation
 *
 * @param array $arr Array to process
 * @param string $indent indentation string
 */
function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output should be inserted into mysql database
                //but this method outputs all values into a single string
                echo "$value";

            }
        }
    }
}

This outputs:

Nairobi
dummy@email.com
dummylandmark
dummytime
dummymode
dummyphone
dummycode
dummymode
dummyuser
2000
dummyname

1
1
2500
dummyname1

1
1

My code for insertion:

$sql_query="insert into purchases (user_name, city, p_id,p_name,sub_total,quantity,email,landmark,order_at,payment_mode,phone,receipt_code,shipping_mode ) values ('$user_name','$city','$p_id','$p_name','$sub_total','$quantity','$email','$landmark','$order_at','$payment_mode','$phone','$receipt_code','$shipping_mode');";

if(mysqli_query($conn,$sql_query)){
 //echo "
 Data Insert success
";
    $response["success"]=true;
 $response["message"]="Purchase created successfully";
 echo json_encode($response);
}
else{
  $response["success"]=false;
  $response["error"]=mysqli_error($conn);
 $response["message"]="Creating purchase failed, please retry";
 echo json_encode($response);
}

As one string. But i wanted to add each individual value into mysql database. Any suggestions?

A: Solved it by using:

foreach($data['products'] as $key => $val)
{
 $product_id = $val['p_id)'];
 $product_name = $val['name'];
 $product_subtotal = $val['amount'];
 $product_quantity = $val['quantity'];

print_r ($product_name);
    //insert into mysql table
    $sql_query="insert into purchases (user_name, city, p_id,p_name,sub_total,quantity,email,landmark,order_at,payment_mode,phone,receipt_code,shipping_mode ) values ('$user_name','$city','$product_id','$product_name','$product_subtotal','$product_quantity','$email','$landmark','$order_at','$payment_mode','$phone','$receipt_code','$shipping_mode');";

if(mysqli_query($conn,$sql_query)){
 //echo "
 Data Insert success
";
    $response["success"]=true;
 $response["message"]="Purchase created successfully";
 echo json_encode($response);
}
else{
  $response["success"]=false;
  $response["error"]=mysqli_error($conn);
 $response["message"]="Creating purchase failed, please retry";
 echo json_encode($response);
}
}

Will update function with sql injections

A:         //Code by :: GM

    //REPLACE $data with your data source and include your DB connection

        $data = ['city' => 'Nairobi', 'email' => 'dummy@email.com', 'products' => [array('amount' => 2000, 'name' => 'dummy_product_name', 'p_id' => 1, 'quantity' => 1, 'subtotal' => 1), array('amount' => 2500, 'name' => 'second_dummy_product_name', 'p_id' => 2, 'quantity' => 7, 'subtotal' => 1)]];

        $insert_query_int = 'INSERT INTO purchases SET ';
        $insert_query = $insert_query_int;
        $query_statement_array=[];
        $part_1_store='';
        foreach ($data as $key => $value) {

            //checks if value is string or an array
            if (!is_array($value)) {
                //if value is string

                $part_1 = "$key = '".$value."', ";
                $part_1_store.=$part_1;
                $insert_query.= $part_1;

            } else {
                //if value is an array
                //FOR EACH PRODUCT
                $product_index = 0;
                foreach ($value as $key2 => $value2) {

                    foreach ($value2 as $key3 => $value3) {
                        //add product details to the query statement
                        $insert_query .= "$key3 = '" . $value3 . "', ";

                    }

                   //PRIMING THE LOOP
                    if($product_index!=0){
                       //add product details to the query statement
                        $insert_query = $insert_query_int.$insert_query;
                    }

                    //Remove last comma from query string
                    $insert_query = rtrim(trim($insert_query),',');
                    //Store query statement in an array
                    $query_statement_array[] =$insert_query;
                    $insert_query = $part_1_store;

                    $product_index++;
                }

            }

        }

        //INSERT DATA TO DB
        if (!$conn->multi_query(implode($query_statement_array,';'))) {
           //fail response
            $response["success"]=false;
            $response["error"]=mysqli_error($conn);
            $response["message"]="Creating purchase failed, please retry";
            echo json_encode($response);
            die();
        }

        do {
            if ($res = $conn->store_result()) {
                $res->free();
            }
        } while ($conn->more_results() && $conn->next_result());

        //success response
        $response["success"]=true;
        $response["message"]="Purchase created successfully";
        echo json_encode($response);

// you should consider normalizing your tables


text:
Q: Symfony dependency injection to modify service argument I'm trying to add a prefix to all the doctrine tables based on these pages:
docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/sql-table-prefixes.html and
stackoverflow.com/questions/7504073/how-to-setup-table-prefix-in-symfony2
I'm also using dependency injection to use the configuration for the prefix definition. symfony.com/doc/current/service_container/definitions.html and symfony.com/doc/current/bundles/configuration.html
Unfortunatly I'm not able to have the tables prefixed using the value defined in the configuration.
But when I manually change the value of the argument in the service definition, it is working.
My project is hosted here: https://github.com/GrenobleSwing/API
See files:

*

*src/GS/ApiBundle/Resources/config/services.yml

*src/GS/ApiBundle/EventSubscriber/TablePrefixSubscriber.php

*src/GS/ApiBundle/DependencyInjection/Configuration.php

*src/GS/ApiBundle/DependencyInjection/GSApiExtension.php

Thanks in advance for your help.
Julien

A: I cloned your repository, run app in containers and found out what's wrong.
Remove that line.
Why?
Now it loads the same configuration twice, and the one loaded in config was used to register event subscribers for Doctrine. So your modifications inside GSApiExtension were omitted.
Checked by myself, and it works now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cámara en espejo cuando se piden permisos para ingresar desde un navegador Estoy diseñando una web con un plugin llamado THREECAMERA en el cual primero se abre desde el navegador (puede ser Chrome o Safari), y que al entrar le solicita al usuario permiso para ingresar a la cámara. El problema es que al darle los permisos, la cámara está en modo espejo, o sea que refleja todos los movimientos que hace el usuario.
Hay alguna manera de arreglar esto? Me ha pasado tanto en iOS como en Android. Estuve buscando y solo encontré la manera de arreglarlo desde la app nativa de la cámara, pero no me está sirviendo.
Mi sitio es el siguiente: https://www.kickads.mobi/ar/final/public/sunglasses/
El código del sitio:

        <canvas width="600" height="600" id='detectedFaceCanvas'></canvas>

        <canvas width="600" height="600" id="takedPhoto"></canvas>


text:
Q: Wordpress Shortcodes not working right with NEXTGEN gallery I am building a wordpress template from scratch for my web. Everything was going so smoothly until I decided to add gallery functionality to it. Naturaly my pick was NEXTGEN gallery plugin which I already had used before in other web projects.
Problem appeared when I wanted to add slideshow to my static frontpage named index.php nothing happened. I used do_shortcode function and echoed result, but all I got was unfiltered text like [ slideshow id=1 ].
It was driving me crazy so I tried next:

*

*adding shortcode to content of another page (which again failed like example above)

*adding echo apply_filters('the_content', $post->post_content) to template file and add_filter('the_content', 'do_shortcode', 11) to functions.php file (which resulted in image list showing, which got me thinking that shortcodes were in fact working)

*registering dynamic sidebar and adding NEXTGEN default widgets to it using old fashioned widgets functionality (slideshow widget still not working only loading.gif appears but never loads anything)

My question is do I need to initialize short-code functionality somewhere for custom build themes? Since I really needed some hooks to get it up and working.
Does anyone know for some incompatibility issues with new WP and NEXTGEN?
WP version 3.4.2
NEXTGEN version 1.9.7
I've tried disabling and re-enabling plugins and that didn't do any good...
Thanks in advance,


text:
Q: How do I make jar files available to ant in a Jenkins pipeline? I've put together a basic Jenkins pipeline and it does what I expect for the most part.
However, I'm using ant and it requires access to specific jar files. I've specified the build step like so:
stage('Build') {
  // Build the project
  env.PATH = "${tool 'ant'}/bin:${env.PATH}"
  sh 'ant -f dita-tools/build_all.xml -lib $WORKSPACE/dita-ot/lib:$WORKSPACE/dita-ot/lib/saxon'
 }

The build I run through this pipeline fails and generates the following error:
java.lang.ClassNotFoundException: org.dita.dost.module.GenMapAndTopicListModule

From what I can tell, this is due to ant not having access to dost.jar that is in the dita ot. I've tried defining this argument a number of ways including specifically referencing dost.jar (I have a number of jars to include) but every time it fails with the same error.
When I put together a stand-alone ant project in Jenkins, ant has no problem accessing the jar by way of the argument I provide above. Is there a better way for me to supply this argument/dependency in a pipeline?
UPDATE:
I added an echo statement for the classpath to my build script and was able to verify that adding the jars to the classpath in the build script does in fact work. So, for all intents and purposes, ant has access to all the relevant base toolkit jars for the target but the error persists. At this point, it appears that the problem has something to do with how the jenkins pipeline works as opposed to the dita ot itself?

A: I assume you use custom plugins, if yes, please make sure, you correctly defined your jars in the plugin.xml like so:
<feature extension="dita.conductor.lib.import" file="lib/my.jar"/>

UPDATE
java.lang.ClassNotFoundException: org.dita.dost.module.GenMapAndTopicListModule

This error means, that the main DITA-OT jar is not found on your classpath. So this indicates, that this is not a plugin issue.
Usually you don't have to setup the classpath, Ant does that for you. Please also read Creating an Ant build script.
Please try a snippet like this one:
node {
    try {
        checkout scm
        stage('Build') {
            sh '''
                dir=$(pwd)
                curl [your-dita-ot-url] --output dita-ot.zip
                unzip -qq "$dir/dita-ot.zip"
                rm dita-ot.zip
                chmod +x ${WORKSPACE}/dita-ot/bin/ant
                ${WORKSPACE}/dita-ot/bin/ant -f ${WORKSPACE}/build.xml -Ddita.dir=$dir/dita-ot -Dbranch.name=$BRANCH_NAME
            '''
        }
    } catch (e) {
        currentBuild.result = "FAILED"
        throw e
    } finally {
        notifyBuild(currentBuild.result)
    }
}


text:
Q: Prolog puzzle baker, meatman and carpenter This is a very simple puzzle I found on the web, I don't find any solution on internet. The rules are simples:

*

*There are 6 artisans, M.Baker and his son, M.Carpenter and his son and M.Meatman and his son

*Each artisan can be baker, carpenter or meatman

*Son and father cannot do the same job

*The lastname couldn't be the job name (M.Baker and his son cannot be baker)

We know that:
- M.Meatman's son is baker
- M.Baker do the same job than M.Carpenter's son
I implemented this predicates:
% swipl prolog
% M.Meatman's son is baker
% M. Baker do job of M. Carpenter's son

% jobs
job(baker).
job(meatman).
job(carpenter).

% fathers
artisan(fatherbaker).
artisan(fathercarpenter).
artisan(fathermeatman).

% sons
artisan(sonbaker).
artisan(soncarpenter).
artisan(sonmeatman).

% some links
father(fatherbaker, sonbaker).
father(fathermeatman, sonmeatman).
father(fathercarpenter, soncarpenter).

son(S, F) :- father(F, S).

same_name(fathercarpenter, soncarpenter,  carpenter).
same_name(fathermeatman, sonmeatman, meatman).
same_name(fatherbaker, sonbaker, baker).

% rules:
do_job(Artisan, Job) :-
    Artisan==sonmeatman,!,
    artisan(Artisan),
    job(Job),
    Job=baker. % M.Meatman's son is baker (rule 1)

do_job(Artisan, Job) :-
    Artisan==fatherbaker,!,
    artisan(Artisan),
    job(Job),
    do_job(soncarpenter, Job). % M.Baker do M.Carpenter's son job

% not relevant...
%do_job(Artisan, Job) :-
%        Artisan == soncarpenter,!,
%   job(Job),
%   artisan(Artisan),
%        do_job(fatherbaker, Job). % rule 2 inverted

% checking if father job is not the same and name are not forgotten
do_job(Artisan, Job) :-
    artisan(Artisan),
    job(Job),
    father(Father, Artisan),
    do_job(Father, JobFather),
    Job \== JobFather,
    not(same_name(Artisan,_,Job)).

% checking if son job is not the same and name are not forgotten
do_job(Artisan, Job) :-
    artisan(Artisan),
    job(Job),
    son(Artisan, Son),
    do_job(Son, JobSon),
    Job \== JobSon,
    not(same_name(_, Artisan, Job)).

Then I try:
swipl
?- do_job(sonmeatman, X).
X = baker ;
false.
?- do_job(fatherbaker, X).
false.

Can you please tell me where I'm wrong.

*

*Note: I'm a newbie in Prolog. I never used this language before (I'm Golang, Python, C programmer...).

*Note 2: Excuse my english, I've just translated my example that was in french, maybe jobnames or verbs are not corrects...

*Note 3: I've already tried to implement zebra puzzle and I realize that was simpler to resolve than this one... strange ?

A: You're overengineering, and reifying too much of the problem (a typical Prolog beginner's error). What you need to write is a six-argument predicate
jobs(BakerSrJob, BakerJrJob,
     CarpenterSrJob, CarpenterJrJob,
     MeatmanSrJob, MeatmanJrJob) :-
    ...

and in the body, constraints on those variables. E.g.
member(BakerJrJob, [carpenter, meatman])

expresses that Baker jr. is either a carpenter or a meatman, and
BakerJrJob \= BakerSrJob

expresses that father and son Baker have different jobs. A couple of these member calls and \= constraints should be enough to encode all the knowledge necessary. (Just hardcode the identity of the persons in the variable name, instead of representing and inspecting the names as atoms. Don't try to write a generic puzzle solver if you're just starting out.)

A: I think you have an error here
...
son(Artisan, Son),
...

as you defined son/2 relation as son(Son,Father)
edit that said, I would solve in entirely different way
solve(Puzzle) :-
    % There are 6 artisans, M.Baker and his son, M.Carpenter and his son and M.Meatman and his son
    Puzzle = [N1/F1/S1, N2/F2/S2, N3/F3/S3],

    % Each artisan can be baker, carpenter or meatman
    Symbols = [baker, carpenter, meatman],
    permutation([N1,N2,N3], Symbols),
    permutation([F1,F2,F3], Symbols),
    permutation([S1,S2,S3], Symbols),

    % Son and father cannot do the same job
    foreach(member(_/F/S, Puzzle), F\=S),

    % The lastname couldn't be the job name
    foreach(member(N/F/S, Puzzle), (N\=F, N\=S)),

    % M.Meatman's son is baker
    member(meatman/_/baker, Puzzle),

    % M.Baker do the same job than M.Carpenter's son
    member(baker/J/_, Puzzle),
    member(carpenter/_/J, Puzzle).

foreach/2 it's a tricky predicate, you could try to replace with your own (recursive) definition. permutation/2 it's simpler, and could be easily replaced...
A last note: "Note 3: I've already tried to implement zebra puzzle and I realize that was simpler to resolve than this one... strange ? " yes it's strange, I think zebra puzzle is by far more complex than this one


text:
Q: Bring bottom View to Top View while touchesMoved I have a grid of views, which are being added as subviews to a main view. When I drag a view which was added prior to the next one, and try to drag it underlays the view rather than overlay that view. How can I fix that content while the view are being dragged on touchesMoved?

A: [self.view bringSubviewToFront:yourView];

Hope this helps...

A: There is also another way, You can import
#import <QuartzCore/QuartzCore.h>

and each of view set zPosition like this
view.layer.zPosition = z;


text:
Q: Extended display not working for Lenovo Thinkcentre (Intel Xeon) I've recently purchased a second-hand Lenovo Think Centre M73 to use as my linux workstation. Everything was going fantastic until I tried hooking up my second monitor. The ThinkCentre has 1 VGA port and 1 DisplayPort, yet Ubuntu will not recognize both inputs simultaneously. That is, if the DisplayPort is connected, Ubuntu will show on that monitor ONLY when booted. If I disconnect the DisplayPort and leave the VGA connected, then it shows on the second monitor. But I cannot get it display on both monitors simultaneously.
Here's the result of sudo lshw -C display:
  *-display UNCLAIMED
       description: VGA compatible controller
       product: Xeon E3-1200 v3/4th Gen Core Processor Integrated Graphics Controller
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 06
       width: 64 bits
       clock: 33MHz
       capabilities: msi pm vga_controller bus_master cap_list
       configuration: latency=0
       resources: memory:f7800000-f7bfffff memory:e0000000-efffffff ioport:f000(size=64) memory:c0000-dffff

I wonder if this some kind of issue with the Intel drivers. Additionally, I notice that even though Ubuntu doesn't "recognize" the second monitor, that if I unplug its VGA connection from the ThinkCentre, the sleeping monitor will wake-up. Any thoughts on how to fix this? It's a fresh install of 20.04 LTS Desktop and I was really looking forward to the extended display setup.
Edit: results of lsb_release -a:
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.2 LTS
Release:    20.04
Codename:   focal

and uname -r
5.8.0-44-generic

A: The Intel integrated graphics drivers are usually installed automatically when they're found, as they're part of the xserver-xorg-video-intel package, but you can confirm they're in place by trying to install the package again:

*Open Terminal (if it's not already open)

*Install the drivers:
sudo apt install xserver-xorg-video-intel

Note: You may see a message like "xserver-xorg-video-intel is already the newest version". If you do, then carry on to the next step.

*If the driver is installed but Ubuntu can't see it, you may need the mesa-utils package as well:
sudo apt install mesa-utils

*Reboot

*Confirm the UNCLAIMED message is gone:
sudo lshw -C display

So long as the video device is properly loaded — and the total resolution of both displays does not exceed the maximum for the video card — then you should be able to extend your desktop across both displays


text:
Q: Jquery Slider: How do I achieve the min and max icons? Please any one can help me with jquery Slider range?
I am new to jQuery and trying to achieve min (right arrow icon) and max(left arrow icon) in the dragging left/right range.
Price range: 0 - 1000
==(>)========(<)===
I want to replace these icons with my personal images with right and left arrow. Is it possible?
I have also attached the image.
$(function() {
    var values = [0,25,50,100,200,400,700,1000];
    $( "#slider-range" ).slider({
        range: true,
        min: 0,
        max: 1000,
        step:50,
        orientation: "horizontal",
        values: [ 0,1000 ],
        slide: function( event, ui ) {
            $( "#amount" ).val( "£" + ui.values[ 0 ] + " - £" + ui.values[ 1 ] );
            console.log("From: "+ui.values[0],"To: "+ui.values[1]);
            $( "#min" ).val( ui.values[ 0 ] );
    $( "#max" ).val( ui.values[ 1 ] );
        }
    });
    $( "#amount" )
    .val( "£" + $( "#slider-range" )
    .slider( "values", 0 ) + " - £" + $( "#slider-range" )
    .slider( "values", 1 ));
});
$( "#slider-range a").hide();

A: After having a quick look at the mark-up, it appears that jQuery-UI doesn't differentiate between the 2 sliders. That isn't a huge problem; what I would recommend doing, upon constructing your slider is adding a min-value and max-value to the ui-slider-handles accordingly. Something like this should do the trick:
$('#slider-range').slider({
     range: true,
     min: 0,
     max: 1000,
     step:50,
     orientation: "horizontal",
     values: [ 0,1000 ],
     slide: function(event, ui) {
          $('#amount').val( "£" + ui.values[ 0 ] + " - £" + ui.values[ 1 ] );
          $('#min').val( ui.values[ 0 ] );
          $('#max').val( ui.values[ 1 ] );
     }
}).find('.ui-slider-handle')
     .eq(0).addClass('min-slider').end()
     .eq(1).addClass('max-slider');

With these classes in place, you can then setup the CSS to target them and manipulate how they look as you wish. :)

A: The slider handle(s) can be identified by the class ui-slider-handle. You could try putting a background-image on those using CSS:
#my-slider .ui-slider-handle { background-image: url(min.png); }

You may need to set other background-* properties to get things working properly.
Putting a different background image on the second slider (which comes right after the first in the HTML) is left as an exercise for the poster.


text:
Q: Adding two complex numbers using classes So, I have found this code in a book:
class complex
{
    public:
        float x,y;
        complex(float a, float b) // CONSTRUCTOR
        {
            x=a; y=b;
    }
    complex sum (complex z)
    {
        ***complex c;*** // i get the error here
        c.x=x+z.x;
        c.y=y+z.y;
        return c;
    }
};

This code is supposed to help me sum 2 complex numbers, like this:
int main ()
{
    complex a(1,2),b(1,1),c; // first number in paranthesis is the real part, the
                             // second one is the imaginary part
    c=a.sum(b) ; // c should get the value of a+b (c.x=2, c.y=3)
    return 0;
}

But everytime I try to compile it I get this error:
"no matching function for call to complex::complex()"
Why? What should I do ?

A: You defined your own constructor, therefore the default constructor is defined as complex() = delete;. You either need your own constructor or force the default one to be created
class complex
{
public:
    float x = 0;
    float y = 0;

    complex() = default; // Compiler will generate the default constructor
    complex(float a, float b): x(a), y(b) {}

    complex sum (complex z)
    {
        complex c;
        c.x=x+z.x;
        c.y=y+z.y;
        return c;
    }
};

Instead of creating sum member function, I would create non-member operator+
// No need to make it friend because you declared x and y as public
complex operator+(complex const& a, complex const& b) {
    return complex(a.x + b.x, a.y + b.y);
}

and use it like this
complex a(3, 4), b(5, 6);
complex c = a + b;


text:
Q: Jsch ssh to Rasperry Pi does nothing I have been searching all over the internet for answers and I keep ending up with the same results, but all I want to do is send command line instructions to my raspberry pi via ssh. Forgive me if I have completely missed something really obvious, but I know I am able to connect because if I type in the incorrect username or password I get an auth failure. So I am connected, but nothing seems to be happening on my raspberry pi. This following is my current code:
package com.name.app.prynsofpi;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.ByteArrayOutputStream;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new AsyncTask<Integer, Void, Void>(){
            @Override
            protected Void doInBackground(Integer... params){
                try {
                    executeRemoteCommand("pi", "green1", "10.1.1.47", 22);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

        }.execute(1);

    }

    public static String executeRemoteCommand(String usrname, String passwd, String hostname, int Port) throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(usrname, hostname, 22);
        session.setPassword(passwd);

        Properties prop = new Properties();
        prop.put("StrictHostKeyChecking", "no");
        session.setConfig(prop);

        session.connect();

        ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        channelssh.setOutputStream(baos);

        channelssh.setCommand("ls");
        channelssh.connect();
        channelssh.disconnect();
        return baos.toString();
    }
}

Can someone please show me what is wrong??? Should I see the commands on the raspberry pi in terminal?

A: You won't see the commands on the pi's terminal. When you establish an ssh connection you are creating a new terminal process, the terminal running on your pi's screen won't show typing or commands, that's not how ssh works. You will need to capture the output and display it on your Android device.
You can run who on your pi to see what accounts are connected via ssh.

A:
Can someone please show me what is wrong???

I don't see anything wrong.

Should I see the commands on the raspberry pi in terminal?

Like ChrisStillwell said, you are creating a new terminal process and the terminal running on your pi's screen won't show the sent commands. If you're trying to see the result of your sent command, you can store it in a String variable (To later display it on a TextView or Toast):
@Override
            protected Void doInBackground(Integer... params){
                try {
                    String result = executeRemoteCommand("pi", "green1", "10.1.1.47", 22);
                    Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }


text:
Q: Detecting a template function of a class Given
class A {
public:
    template <typename U, typename V, typename W>
    void foo (const U&, V*, const W*) const {}
    template <typename R, typename U, typename V, typename W>
    R bar (const U&, V*, const W*) const {return R{};}
};

we want a traits class that will determine if A has foo and bar with suitable arguments.  Detecting foo is working, but I'm stuck trying to detect bar because of its template return type:
#include <iostream>
#include <type_traits>

class A {
public:
    template <typename U, typename V, typename W>
    void foo (const U&, V*, const W*) const {}
    template <typename R, typename U, typename V, typename W>
    R bar (const U&, V*, const W*) const {return R{};}
};

template <typename...> struct voider {using type = void;};

template <typename... Ts>
using void_t = typename voider<Ts...>::type;

template <typename T, typename U, typename V, typename W, typename = void_t<T>>
struct HasFoo: std::false_type {};

template <typename T, typename U, typename V, typename W>
struct HasFoo<T, U, V, W,
    void_t<decltype(std::declval<const T&>().foo(std::declval<const U&>(), std::declval<V*>(), std::declval<const W*>()))>>
    : std::true_type {};

template <typename T, typename U, typename V, typename W, typename = void_t<T>>
struct HasBar: std::false_type {};

template <typename T, typename U, typename V, typename W>
struct HasBar<T, U, V, W,
    void_t<decltype(std::declval<const T&>().bar(std::declval<const U&>(), std::declval<V*>(), std::declval<const W*>()))>>
    : std::true_type {};

int main() {
    std::cout << std::boolalpha << HasFoo<A, int, bool, char>::value << '\n';  // true
    std::cout << HasBar<A, int, bool, char>::value << '\n';  // false (want it to be true)
}

How to fix HasBar so that the last output evaluates to true?


text:
Q: Three.js: is using a RenderTarget as a mesh the most direct way put a scene back into a WebGLRenderer after an EffectComposer? I'm attempting to use the Magnify-3d package after using an EffectComposer to apply a bokeh effect to a scene. Magnify-3D takes in a renderer, so I cannot simply pass in the EffectComposer after applying passes.
The intended result would work like a microscope, with the ability to independently adjust the plane of focus by adjusting the BokehPass effect, and the magnification using Magnify-3d.
The only way I've gotten this to work so far has been like so:

*

*Create a temporary scene containing actual scene I want to render.

*Create an EffectComposer that applies BokehPass and renders the temporary scene to renderTarget.

*Create a PlaneBufferGeometry and a mesh that maps renderTarget.texture (the output of the temporary scene) to the plane, and add this to a new scene.

*Render the new scene that effectively is just a camera staring at a mesh of the original scene.

*Pass the renderer into magnify3d, which creates a lens effect around the scene I want to render.

This seems to work OK (though there appears to be some fuzziness and distortion of the original scene I'm still working out), but I began to wonder -- is this really the best way to use something rendered to a RenderTarget? Is there a more direct way than effectively taking a picture of a picture that I can use to take the output of an EffectComposer, feed it back into a renderer so my final scene is rendered in a WebGLRenderer, and pass it into a library? Any other way I can think to do this, the EffectComposer would not be able to run (since Magnify3d takes in a renderer, not an EffectComposer and I need to run the EffectComposer before passing it into a renderer).
Here's a screenshot of the final result
Here's some code below:
// create initial scene
const renderTarget = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
const rtScene = new THREE.Scene();
const rtCamera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000000000 );

// add a sample cube to the new scene and move the camera back
const geometry = new THREE.BoxGeometry( 10, 10, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );

rtScene.add(cube);

rtCamera.position.z = 500;

// initialize renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xffffff, 1 );
document.body.appendChild( renderer.domElement );

// initialize EffectComposer and apply BokehEffect.
// Note that composer renders its output to RenderTarget.
const composer = new EffectComposer( renderer, renderTarget );
composer.renderToScreen = false;

const renderPass = new RenderPass( rtScene, rtCamera );
composer.addPass( renderPass );
const bokehValues = {
    focus: 500,
    aperture: .00025,
    maxblur: 1,
    width: window.innerWidth,
    height: window.innerHeight
}

export const bokehPass = new BokehPass( rtScene, rtCamera, bokehValues);
composer.addPass( bokehPass );

// create final scene to render before passing to Magnify3D
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000000000 );
const scene = new THREE.Scene();
camera.position.z = 100;

// make a plane geometry, a mesh that maps renderTarget.texture, and add it to the scene
const planeGeometry = new THREE.PlaneBufferGeometry( window.innerWidth, window.innerHeight );
const planeMaterial = new THREE.MeshBasicMaterial( { map: renderTarget.texture } );
const plane = new THREE.Mesh( planeGeometry, planeMaterial );
scene.add( plane );

function animate() {
    // first render temporary scene
    renderer.setClearColor( 0xffffff, 1 );
    composer.render(); // now composer has rendered to renderTarget

    renderer.setClearColor( 0x141414, 1 ); // create a black background for outside of microscope
    renderer.render( scene, camera ); // render final scene with meshed plane

    // Finally use Magnify3D to render final scene with microscope
    magnify3d.render({
        renderer: renderer,
        pos: {
            x: window.innerWidth/2,
            y: window.innerHeight/2
        },
        renderSceneCB: (target) => {
            if (target) {
                renderer.setRenderTarget(target);
            } else {
                renderer.setRenderTarget(null);
            }
            renderer.render(scene, camera);
        },
        radius: window.innerWidth/5,
        exp: 150,
        zoom: state.magnification,
    });

    requestAnimationFrame( animate );
}


text:
Q: How to make a float that is not labelled 'Figure' but 'Listing' I would to include my listings as floats, pretty much as Figures, but I don't want to call them Figures. I want to call them listings. How can I do that?

A: It would be possible to re-purpose the figure environment and associated macros, but it may make the code harder to read. For example,
\begin{figure}[..]
  % <contents>
  \caption[..]{...}
\end{figure}

would then serve the (possibly) dual purpose of posting a listing or a figure. Additionally, what should be contained within \listoffigures?
The float package allows for the easy definition of new floats. Here's a minimal example declaring a new float listing, as well as the appropriate \listoflistings command to display a "List of Listings":

\documentclass{article}
\usepackage{float}% http://ctan.org/pkg/float
% Create new "listing" float
\newfloat{listing}{tbhp}{lst}%[section]
\floatname{listing}{Listing}
\newcommand{\listoflistings}{\listof{listing}{List of Listings}}
\begin{document}
\tableofcontents
\listoffigures
\listoflistings
\begin{figure}
  \centering\rule{150pt}{100pt}
  \caption{This is a figure}
\end{figure}
\begin{listing}
  \begin{verbatim}
Here is some code.
  \end{verbatim}
  \caption{This is a listing}
\end{listing}
\end{document}

For more information on the user interface, consult the float package documentation.

A: There are two packages that let you format your listings and are able to let them float.

*

*listings

*minted
Here are two simple examples.
\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{listings}

\lstset{
  basicstyle=\small\ttfamily,
  frame=single
}
\begin{document}
  \begin{lstlisting}[
    gobble=4,
    float,
    caption={Dummy Listing},
    label={lst:dummy}
  ]
    \documentclass{scrartcl}

    \begin{document}
      Hello World!
    \end{document}
  \end{lstlisting}
\end{document}

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{minted}

\begin{document}
  \begin{listing}[!ht]
    \begin{minted}[
      frame=single,
      gobble=6
    ]{latex}
      \documentclass{scrartcl}

      \begin{document}
        Hello World!
      \end{document}
    \end{minted}
    \caption{Dummy listing}
    \label{mnt:dummy}
  \end{listing}
\end{document}

The respective manuals have more details about customization of your listings.


text:
Q: Correct text position center in rectangle iText I try to draw text inside rectangle which fit rectangle size, like my previous question, I want text align center in rectangle.
The problem is display text has wrong Y coordinate, look like this one:

And here is my code:
    PdfContentByte cb = writer.getDirectContent();

        Rectangle rect = new Rectangle(100, 150, 100 + 120, 150 + 50);
        cb.saveState();
        ColumnText ct = new ColumnText(writer.getDirectContent());
        Font font = new Font(BaseFont.createFont());
        float maxFontSize;
        // try to get max font size that fit in rectangle
        font.setSize(maxFontSize);
        ct.setText(new Phrase("test", font));
        ct.setSimpleColumn(rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop());
        ct.go();

        // draw the rect
        cb.setColorStroke(BaseColor.BLUE);
        cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
        cb.stroke();
        cb.restoreState();

I even draw text like this:
        cb.saveState();
        cb.beginText();
        cb.moveText(rect.getLeft(), rect.getBottom());
        cb.setFontAndSize(BaseFont.createFont(), maxSize);
        cb.showText("test");
        cb.endText();
        cb.setColorStroke(BaseColor.BLUE);
        cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
        cb.stroke();

And got the result:

So I wonder how can itext render text base on the coordinates? Because I use the same rectangle frame for text and rectangle bound.

A: I'm not sure if I understand your question correctly. I'm assuming you want to fit some text into a rectangle vertically, but I don't understand how you calculate the font size, and I don't see you setting the leading anywhere (which you can avoid by using ColumnText.showAligned()).
I've created an example named FitTextInRectangle which results in the PDF chunk_in_rectangle.pdf. Due to rounding factors (we're working with float values), the word test slightly exceeds the rectangle, but the code shows how to calculate a font size that makes the text fit more or less inside the rectangle.
In your code samples, the baseline is defined by the leading when using ColumnText (and the leading is wrong) or the bottom coordinate of the rectangle when using showText() (and you forgot to take into account value of the descender).


text:
Q: Black screen on Launch: How to support all versions iOS 10 and 13 above in App and Scene Delegate My app supports older versions of iOS 10.0 and above. When I try to launch my app in iOS 13, it shows a black window. It does configure initial ViewController and shows labels when I remove the scene delegate. Everything works in iOS 12 and under with just App delegate.
In my App delegate:
@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        configureInitialViewController()
        return true
    }

    func configureInitialViewController()
    {
        var initialVC: UIViewController
        let mainsb = UIStoryboard(name: "Main", bundle: nil)
        if Auth.auth().currentUser != nil {
            //print("successfully signed in")
            initialVC = mainsb.instantiateViewController(withIdentifier: IDENTIFIER_MAIN_TABBAR)
        } else {
            //print("successfully signed out")
            initialVC = mainsb.instantiateViewController(withIdentifier: IDENTIFIER_WELCOME_NAV)
        }

        window?.rootViewController = initialVC
        window?.makeKeyAndVisible()
    }

    func applicationWillResignActive(_ application: UIApplication) {
        Api.User.isOnline(bool: false)
    }

    // MARK: UISceneSession Lifecycle

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
}

In my Scene delegate:
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
    }

    func sceneWillResignActive(_ scene: UIScene) {
        Api.User.isOnline(bool: false)

    }
}

I also deleted Application Scene Manifest in my info.plist.
Can someone help me check if I'm setting up version supports correctly?
I would really appreciate any help.
Update:
I tested it works in iOS 13.5 but not 13.2 or 14.3. Why is it showing different behaviors in different versions?

A: In your AppDelegate inside didFinishLaunchingWithOptions add this:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    if #available(iOS 13.0, *){}
    else{
        //Load your vc
    }
    return true
}

Then in your SceneDelegate inside willConnectTo add these:
@available(iOS 13.0, *)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let _ = (scene as? UIWindowScene) else { return }
    guard let windowScene = (scene as? UIWindowScene) else {return}
    let window:UIWindow = UIWindow(windowScene: windowScene)
    self.window = window
    self.window?.rootViewController = // set you VC
    self.window?.makeKeyAndVisible()

}


text:
Q: biblatex backref – how to add spaces around the dash? I am using biblatex with backref=true, which generates ranges as e.g. 34–37. How can I make it e.g. 34 – 37? The spaces should be non-breakable.
I have tried to redefine \bibrangedash, but with no success.

A: Although the OP's question is about adding non-breakable spaces, I suggest a solution differing in two respects:

*

*As an en-dash surrounded by (full) spaces denotes the start/end of an insertion rather than a range, I'd use thin spaces instead.

*Because "line-breaking in the bibliography is often more difficult than in the body text
and [...] you can not resort to rephrasing a sentence" (biblatex manual, section 3.8.4), the space following the en-dash should be associated with a high, but finite (for TeX, i.e., <10,000) penalty rather than unbreakable.
The corresponding biblatex commands are \addnbthinspace and \addhpthinspace. See section 4.7.4 of the manual for details.
\DefineBibliographyExtras{english}{
  \renewcommand*{\bibrangedash}{\addnbthinspace\textendash\addhpthinspace}
}

A: I was inattentive and misinterpreted a bit of the documentation. The following works, should someone need the same:
\DefineBibliographyExtras{english}{
\renewcommand*{\bibrangedash}{~\textendash~}
}


text:
Q: Create multiple relationships in Neo4j using array of integers using Cypher I'm new to Neo4j and Cypher and have just imported two csvs - one is a list of places and the other is a list of people.
Each place has multiple peopleIDs for the people that have visited it stored as integers in an array.
Similarly, Each person has multiple placeIDs for the places they have visited stored as integers in an array.
I'm struggling when creating the relationships between the people and place nodes in my graph. I have tried the following, which works for individual IDs, but it doesn't create any relationships from an array of IDs:
MATCH (p1:People),(p2:Place)
WHERE p1.placeID = p2.placeID
CREATE (p1)-[:VISIT]->(p2)

The headers for the People csv file are as follows:

The headers for the Places csv file are as follows:

I guess that I need to use FOREACH or UNWIND or both but I can't find any good examples of how to achieve what I'm after

A: You did not use the optimal strategy for importing the data. In a graph DB, it is not good practice to store data (like lists of IDs) that would only be used to create relationships later. That would leave you with a lot of redundant data that would never be used again (and ideally should be deleted).
A better strategy would involve 3 steps:

*

*Import the nodes from the People file - but ignore the Place ID lists

*Import the nodes from the Place file - but ignore the People ID lists

*Import the relationships from one of the files (I assume it does not matter which). For example, I'll assume we pick the Place file, and that each file row has an id field with the ID of a Place and a people field containing a semicolon-delimited collection of People IDs. A query like this would then create all the needed relationships (and avoid creating duplicates):
LOAD CSV WITH HEADERS FROM 'file:///places.csv' AS row
MATCH (place:Place) WHERE place.id = row.id
MATCH (person:People) WHERE person.id IN SPLIT(row.peopleIds, ';')
MERGE (person)-[:VISIT]->(place)

A: I've managed to track down a similar question to my one here, which provides an answer here
To solve my question I've used the following:
MATCH (p1:People)
UNWIND p1.placeID as pID
MERGE (p2:Place{placeID: pID})
MERGE (p1)-[AT]->(p2)


text:
Q: UIView not resizing, is there a property I'm missing? I'm trying to make a subview for a view and have it be a smaller size, however, the subview isn't resizing. I wonder if I'm missing something. The View Controller's 'viewDidLoad' code is like this:
[_testView setBackgroundColor:[UIColor greenColor]];

CGRect frame = self.testView.frame;
frame.size.height -= 500;
// self.testView.frame = frame;
[_testView addSubview:_testSubView];

[_testSubView setFrame:frame];

But no change in the subview's height is seen. Any ideas why?

A: If you're using the "viewDidLoad" method, it's safe to assume that you are initializing this view in a nib file. If there are any constraints on this view, it is in fact possible for them to be applied to a view after the viewDidLoad method, because the final size of the view is not determined completely until the "viewWillAppear" method.
Long story short, try moving your frame change to the "viewWillAppear:animated:" method.

A: Did setup autoresizingMask on your subview ?
_testSubView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;

Check that autoresizesSubviews is set on your parent view too.
_testView.autoresizesSubviews = YES;

I think you should have a look at autolayout too.
Regards,


text:
Q: Chapter, section, etc. numbers on left margin, aligned left In the memoir class, the "hangnum" chapterstyle puts the section numbers on the left margin, aligned right. How do I change it so that it is aligned left?
Here's an MWE with the original definition of the "hangnum" chapterstyle copied from the manual:
\documentclass[12pt]{memoir}

\usepackage[usehighlevels]{alnumsec}
\alnumsectionlevels{1}{section,subsection,subsubsection,paragraph}
\alnumsecstyle{aaaa}
\surroundarabic[{.}][]{}{}
\otherseparators{1}
\alnumsecstyle{aaaa}

\makechapterstyle{myhangnum}{%
\renewcommand*{\chapnumfont}{\chaptitlefont}
\settowidth{\chapindent}{\chapnumfont 999}
\renewcommand*{\printchaptername}{}
\renewcommand*{\chapternamenum}{}
\renewcommand*{\chapnumfont}{\chaptitlefont}
\renewcommand*{\printchapternum}{%
\noindent\llap{\makebox[\chapindent][l]{%
\chapnumfont \thechapter}}}
\renewcommand*{\afterchapternum}{}
}

\chapterstyle{myhangnum}
\hangsecnum

\begin{document}

\section{All these section numbers}
\subsection{should be aligned on the left}
\subsection{so that all the first digits}
\subsubsection{which is 1 in this case}
\paragraph{are underneath each other}\

Moreover, is it possible to decrease the space between
the numbers and the titles? I rarely have paragraphs,
but I have a lot of subsubsections.

\end{document}

I tried adding \hfill inside the makebox, altering the makebox parameters, but both to no avail:
\noindent\llap{\makebox[3cm][l]{%
\chapnumfont \thechapter \hfill}}}

I also tried altering the macro \chapternamenum (manual: is defined to be a space, is called between printing the chapter name and the number), but even if I enter a string in there, it does not shop up in the finished document.

A: Here is a possibility, though it is very dirtily hacked:
\documentclass{memoir}
\usepackage[usehighlevels]{alnumsec}
  \alnumsectionlevels{1}{section,subsection,subsubsection,paragraph}
  \alnumsecstyle{aaaa}
  \surroundarabic[{.}][]{}{}
  \otherseparators{1}
  \alnumsecstyle{aaaa}
\usepackage{marginnote}
  \reversemarginpar
\usepackage{xpatch}

\chapterstyle{hangnum}

\makeatletter
\xpatchcmd\M@sect{\protected@edef}{\protected\def}{}{}
\xpatchcmd\@mn@@@marginnote{\@tempswatrue}{\@tempswafalse}{}{}
\marginparwidth 45\p@
\renewcommand{\printchapternum}{%
  \raisebox{5\p@}{\marginnote{\raggedright\chapnumfont\thechapter}}
}
\def\@seccntformat#1{\marginnote{\raggedright\csname the#1\endcsname}}
\makeatother

\begin{document}
\chapter{Some chapter}
\section{All these section numbers}
\subsection{should be aligned on the left}
\subsection{so that all the first digits}
\subsubsection{which is 1 in this case}
\paragraph{are underneath each other}
\end{document}

A: Erh, one can just do this via
\setsecnumformat{\llap{%
    \makebox[\chapindent][l]{%
      \csname the#1\endcsname\hfill%
    }%
  }}

instead of issuing \hangsecnum, which by default is the same as
\setsecnumformat{\llap{\csname the#1\endcsname\quad}}}

@Ruben
Does this still fail at your end? I should be using the same memoir version, but is using TeLive 2015
\documentclass{memoir}

\hangsecnum
\setsecnumformat{\llap{\makebox[\chapindent][l]{\csname
      the#1\endcsname\hfill}}}

\chapterstyle{hangnum}

\begin{document}

\chapter{A chapter}

\section{All these section numbers}
\subsection{should be aligned on the left}
\subsection{so that all the first digits}
\subsubsection{which is 1 in this case}

\end{document}


text:
Q: Homotopy between two morphisms in $Top(2)$ category Let $(X,A),(Y,B)$ be topological paris and $f,g:(X,A)\rightarrow (Y,B)$ be continuous functions. (i.e. $f(A)\subset B$ and $g(A)\subset B$)
Assume that $f,g$ are homotopic so that there exists a continuous function $F:X\times I \rightarrow Y$ such that $F(x,0)=f(x)$ and $F(x,1)=g(x)$. Then, does there exist a continuous function $G:X\times I \rightarrow Y$ such that $G(x,0)=f(x)$ and $G(x,1)=g(x)$ and $G(A\times I)\subset B$?
What would be a terminology to call such homotopy $G$ and the relation of $f,g$ that admits the existence of such $G$? $G$ is definitely not "a homotopy relative to $A$". Is there some good terminology to call this?

A: Regarding the first question, the answer is (almost) clearly no: As a special case, consider $(X, A)=(I, \partial I)$ (unit interval and its boundary) and $(Y, B)=(\mathbb{C}\setminus \{1\}, \{0\})$ the punctured plane with a basepoint. Thus, all the cont. maps respecting the distinguished subspaces are loops in the punctured plane with a common basepoint ($=\{0\}$).
In this case, the condition you impose on $G$ is being a homotopy relative to $\partial I$ (because $B=\{0\}$ is one element set). If the claim in your question holds, that would translate to the statement that the fundamental group of the punctured plane is trivial (since all the curves in the punctured plane are homotopic if no basepoint is fixed), which does not hold.
(As for the second question, I do not know a good terminology for it, but I agree that it seems (at least to me) more natural definition than the usual notion of relative homotopy.)

A: The existence of your $G$ is, I believe, the standard defintion of being homotopic in the category of pairs. See e.g. Definition 2.2.5 here.
I don't think that it is equivalent to the existence of your $F$ in general. For a counter-example, think of $X=[0,1]$, $A=\{0,1\}$, $Y=S^1$, $B=\{1\}$, $f(x)=e^{2\pi i x}$, $g(x)=1$.
The notation "homotopy relative to $A$" usually refers to a situation where $G(a,t)$ is independent of $t$ for each $a\in A$. So, for your $G$, just call it "homotopy". Your $F$ is something nonstandard, I believe.


text:
Q: Discord JS "Unknown Member" although being properly cached I'm trying to assign and remove roles but i get the DiscordAPIError: Unknown Member error. I am quite sure that I properly cached the member and I don't know why the error is showing up. When I console log the member, it outputs GuildMember { <a lot of data> } as it should.
    async function refreshAllRanks() {
        var allMembersIndex = await verifiedUsers.distinct('customstats.index')
        for (var i = 0; i < allMembersIndex.length; i++) {
            var userData = await verifiedUsers.where('customstats.index').equals(allMembersIndex[i]).select('memberid') as any
            var userID = userData[0].memberid
            let user = guild.members.fetch(userID);
            const index = allMembersIndex[i]
            if (index < 175) {
                var role = '964653007117627453'
            }
            else if (index >= 175 && index < 250) {
                (await user).roles.remove("964653007117627453");
                var role = '964652871113142282'
            }
            else if (index >= 250 && index < 350) {
                (await user).roles.remove("964653007117627453");
                (await user).roles.remove("964652871113142282");
                var role = '964652446154633256'
            }
            else if (index >= 350) {
                (await user).roles.remove("964653007117627453");
                (await user).roles.remove("964652871113142282");
                (await user).roles.remove("964652446154633256");
                var role = '964651864052334683'
            }
            (await user).roles.add(role)
        }
    }
    refreshAllRanks()


text:
Q: Remove headers from a GuzzleHTTP request in Laravel I am trying to send a request using the code snippet below:
$response = $client->request('POST','http://pesamoni.com/api/live/v1/transactions', [
         'form_params'   => [
         'method'        => 'acreceive',
         'apiusername'   => '1276539738zx3287',
         'mobile'        => str_replace('+', '',$this->senders_contact),
         'chanel'        => 'TIG',
         'referral'      => str_replace('+', '',$this->referer),
         'apipassword'   => 'hddjaslasdasdwe',
         'amount'        => '500',
         'reference'     => 'adasd',
         'genericmsg'    => 'test',
         'token'         => '545345345',
         'metadata'      => 'something',
         'callback'      => 'http://church.pahappa.com/'
                            ]
]);

I want to send this request with no headers, I have tried using:
$response->removeHeader('User-Agent');

but it is not working.
How can I remove headers from the request?

A: As per the Guzzle Documentation

// Will disable adding in default headers.
$client->request('GET', '/get', ['headers' => null]);

So set headers to null in your request.


text:
Q: can't connect to wifi using Xubuntu Everytime i try to connect to internet using wifi i type the password, Xubuntu tries to connect for a little while and then asks me the password again. I'm using a D-Link modem/router.
Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8191SEvA Wireless LAN Controller [10ec:8171] (rev 10)
 Subsystem: Hewlett-Packard Company Device [103c:1467]
 Kernel driver in use: rtl8192se

Please guys i really need some help here, if i don't get this working i will have to go back to Windows.

A: When asked for the password the second time, the D-Link modem-router is asking you for its password.  You'll have to find that password in order to continue and connect.


text:
Q: duplicate post issue on pages i've this problem since last month
let me show what's happens on my implementation of graph api using PHP:
skippin' on standard php graph api workflow to retrive basic user info such as
user access token, page access token and required permission, when i'm calling the
(example)
$facebook->api(PAGE_ID/feed,post, access_token, message, link)
i've got 2 posts on target page wall.
First one is a complete post with link and message objects,second one, created 3-4 seconds after the first one, only with message object.
The strange thing is that the Graph api return to my framework  the message id of the second one post only.
Since yesterday i'm getting always an Facebook exception like #506 duplicate post message.
I did see on Facebook issue tracker that a similar issue was reported las year and i'm getting serious problem with my customers if i do not find a valid solution to prevent:

*

*double post

*post without all object in the api call such as
picture, link, name, caption

*incorrect id

Anyone has the same problem?

A: You do not need to prevent these dupe posts, when Facebook prevent them. Just "ignore" that error.
To prevent incorrect id => if this really happens, it's problem on their side and you should post a bug tracker

A: About incorrect ID, I've noticed that the Graph API's returns a different ID from that used to get access to the post by browser. I try to discovering what's going on before report a problem. Did someone else note?
I've got this dupes too, but I don't have a clue about what could be.


text:
Q: Can't open my channel on youtube from application I use this code for open my channel:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.youtube.com/user/myChannel"]];

If I paste this string to Safary, everything is great. If Safary was opened everything is great Too. And I can see this:

BUT if Safary wasn't opened before. I can see only proposition for download Youtube application from the app store:

I tested it on iOS 7,8. There are the same behavior. But on iOS 9 betta 4 it looks different behavior(Back button in top left corner) and absolutely no problems:

I think it is not my problem. But maybe some of you had/have the same problem with youtube or some another service. In the nearest time I am going to send mail to youtube support, but may be there is simple solution and i don't know about it =(
PS
Any way. Tank for your attention =)


text:
Q: CKEditor - preventing users from pasting images I would like giving my users a limited editor, using the great CKEditor.
I was trying to prevent people from adding images, therefore I've blocked the "Source" view and disabled the "paste" button (leaving only the Paste as Text button).
However, it is still possible to paste images (copied from web page).
Is there a way to prevent that as well ?
Thanks.

A: I know its been a while but if anyone else comes across this same problem.
You should use a plugin as described here to check for all images and if user tries to insert an image, then he is alerted that "images" are not allowed.
Please note that the plugin is not available to download so we might have to create our own plugin. Its pretty simple. We just have to copy and paste his code in plugin.js file.
CKEDITOR.plugins.add( 'blockimagepaste',
{
    init : function( editor )
    {

    function replaceImgText(html) {
            var ret = html.replace( /<img[^>]*src="data:image\/(bmp|dds|gif|jpg|jpeg|png|psd|pspimage|tga|thm|tif|tiff|yuv|ai|eps|ps|svg);base64,.*?"[^>]*>/gi, function( img ){
                        alert("Direct image paste is not allowed.");
                        return '';

                     });
            return ret;
        }

        function chkImg() {
            // don't execute code if the editor is readOnly
            if (editor.readOnly)
                return;

            setTimeout( function() {
                editor.document.$.body.innerHTML = replaceImgText(editor.document.$.body.innerHTML);
            },100);
        }

        editor.on( 'contentDom', function() {
            // For Firefox
            editor.document.on('drop', chkImg);
            // For IE
            editor.document.getBody().on('drop', chkImg);
        });

        editor.on( 'paste', function(e) {

        var html = e.data.dataValue;
            if (!html)
                return;

        e.data.dataValue = replaceImgText(html);
        });

    } //Init
} );

Another option is explained here (which I believe only works on paste event doesn't do anything when image is dragged ! )

A: You can use the 'paste' event, that way you can remove anything that you don't like. And of course, you should also verify the content at the server before saving.

A: that was useful, I used the solution of Nis. but the problem is that if you drop a image, the paste event is lost. I made a change to prevent this situation.
(function(){
    var pluginName = 'blockimagepaste';
    function replaceImgText(html) {
        var ret = html.replace( /<img[^>]*src="data:image\/(bmp|dds|gif|jpg|jpeg|png|psd|pspimage|tga|thm|tif|tiff|yuv|ai|eps|ps|svg);base64,.*?"[^>]*>/gi, function( img ){
            alert("Direct image paste is not allowed.");
            return '';
        });
        return ret;
    };

    function chkImg(editor) {
        // don't execute code if the editor is readOnly
        if (editor.readOnly)
            return;

        setTimeout( function() {
            editor.document.$.body.innerHTML = replaceImgText(editor.document.$.body.innerHTML);
        },100);
    };

    CKEDITOR.plugins.add( pluginName, {
        icons: pluginName,
        init : function( editor ){

            editor.on( 'contentDom', function() {
                // For Firefox
                editor.document.on('drop', function(e) {chkImg(editor);});
                // For IE
                editor.document.getBody().on('drop', function(e) {chkImg(editor);});

                editor.document.on( 'paste', function(e) {chkImg(editor);});

                // For IE
                editor.document.getBody().on('paste', function(e) {chkImg(editor);});
            });

        } //Init
    });

})();

A: If you want to be able to prevent this in the Source view as well, just add this code to your plugin:
editor.on('key', function(e) {
    var html = CKEDITOR.currentInstance.getData();
    if (!html) {
        return;
    }
    CKEDITOR.currentInstance.setData(replaceImgText(html));
});


text:
Q: Symfony, how to keep the declaration of entities repository after re-import my table The structure of the database I am using for my project is constantly changed by another team. So I have to import regularly this structure into Symfony. To do so I use the following command:
php app/console doctrine:mapping:import --force EgBundle yml [--filter="Table"]
php app/console doctrine:generate:entities [Company/EgBundle/Entity/Table]

Every time I run those command I loose the declaration of my repositories and I have to had them manually:
repositoryClass: Company\EgBundle\Entity\TableRepository

Is there any way to keep this declaration?

A: There is no way for Doctrine to know what the repository class shall be when importing a mapping from database. The information can't be obtained from the database schema.
A possible solution for your use-case would be extending\overriding the doctrine:mapping:import command to add a Repository to the mapping information automatically using a naming convention.


text:
Q: mysql query getting all fields in table 1 and partial in from table two Coming back to my very old mysql skills I have need of the following query.
I have two tables
One is a table of all items called products with cols item name, item num
Two is a table of purchased items with cols item num, date
What I need as a result is something like this
ITEM-----PURCHASED
item1-------0
item2-------0
item3-------0
item4-------1  This item purchased
item5-------0
item6-------1  This item purchased
item7-------0
item8-------0
.
.
.
itemX-------0

Output contains all items and a 1 in the purchased col if the item exist in the purchased items table
and a 0 if it has NOT been purchased.
I am sorry if this is easy my brain is in meltdown mode currently and it has been a long time I have needed something like this

A: Using a LEFT JOIN and a CASE to test for NULL in the joined table, you can return a zero or 1 accordingly (I used CASE but you could also do IFNULL() in MySQL):
SELECT
  products.name,
  products.item_num
  /* items that have no related rows in `purchased` will be NULL */
  CASE WHEN purchased.item_num IS NULL then 0 ELSE 1 END AS purchased
  /* Could also just do:
       (purchesd.item_num IS NULL) AS purchased
     because MySQL will return a 0 or 1 from the boolean condition,
     but the CASE is more portable */
FROM
  products
  LEFT JOIN purchased ON products.item_num = purchased.item_num


text:
Q: Async generator, previous iterations await a future iteration? I want to generate an enumerable of tasks, the tasks will complete at different times.
How can I make a generator in C# that:

*

*yields tasks

*every few iterations, resolves previously yielded tasks with results that are only now known

The reason I want to do this is because I am processing a long iterable of inputs, and every so often I accumulate enough data from these inputs to send a batch API request and finalise my outputs.
Pseudocode:
IEnumerable<Task<Output>> Process(IEnumerable<Input> inputs)
{
    var queuedInputs = Queue<Input>();
    var cumulativeLength = 0;
    foreach (var input in inputs)
    {
        yield return waiting task for this input
        queuedInputs.Enqueue(input);
        cumulativeLength += input.Length;
        if (cumulativeLength > 10)
        {
            cumulativeLength = 0
            GetFromAPI(queue).ContinueWith((apiTask) => {
                Queue<BatchResult> batchResults = apiTask.Result;
                while (queuedInputs.Count > 0)
                {
                    batchResult = batchResults.Dequeue();
                    historicalInput = queuedInputs.Dequeue();
                    var output = MakeOutput(historicalInput, batchResult);
                    resolve earlier input's task with this output
                }
            });
        }
    }
}

A: One approach is to use the TPL Dataflow library. This library offers a variety of components named "blocks" (TransformBlock, ActionBlock etc), where each block is processing its input data, and then propagates the results to the next block. The blocks are linked together so that the completion of the previous block in the pipeline triggers the completion of the next block etc, until the final block which is usually an ActionBlock<T> with no output. Here is an example:
var block1 = new TransformBlock<int, string>(item =>
{
    Thread.Sleep(1000); // Simulate synchronous work
    return item.ToString();
}, new()
{
    MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded,
    EnsureOrdered = false
});

var block2 = new BatchBlock<string>(batchSize: 10);

var block3 = new ActionBlock<string[]>(async batch =>
{
    await Task.Delay(1000); // Simulate asynchronous work
}); // The default MaxDegreeOfParallelism is 1

block1.LinkTo(block2, new() { PropagateCompletion = true });
block2.LinkTo(block3, new() { PropagateCompletion = true });

// Provide some input in the pipeline
block1.Post(1);
block1.Post(2);
block1.Post(3);
block1.Post(4);
block1.Post(5);

block1.Complete(); // Mark the first block as completed
await block3.Completion; // Await the completion of the last block

The TPL Dataflow library is powerful and flexible, but is has a weak point in the propagation of exceptions. There is no built-in way to instruct the block1 to stop working, if the block3 fails. You can read more about this issue here. It might not be a serious issue, if you don't expect your blocks to fail very often.

A: The shape of your solution is going to be driven by the shape of your problem. There's a couple of questions I have because your problem domain seems odd:

*

*Are all your inputs known at the outset? The (synchronous) IEnumerable<Input> implies they are.

*Are you sure you want to wait for a batch of inputs before sending any query? What about the "remainder" if you're batching by 10 but have 55 inputs?

Assuming you do have synchronous inputs, and that you want to batch with remainders, you can just accumulate all your inputs immediately, batch them, and walk the batches, asynchronously providing outputs:
async IAsyncEnumerable<Output> Process(IEnumerable<Input> inputs)
{
  foreach (var batchedInput in inputs.Batch(10))
  {
    var batchResults = await GetFromAPI(batchedInput);
    for (int i = 0; i != batchedInput.Count; ++i)
      yield return MakeOutput(batchedInput[i], batchResults[i]);
  }
}

public static IEnumerable<IReadOnlyList<TSource>> Batch<TSource>(this IEnumerable<TSource> source, int size)
{
  List<TSource>? batch = null;
  foreach (var item in source)
  {
    batch ??= new List<TSource>(capacity: size);
    batch.Add(item);
    if (batch.Count == size)
    {
      yield return batch;
      batch = null;
    }
  }

  if (batch?.Count > 0)
    yield return batch;
}

Update:
If you want to start the API calls immediately, you can move those out of the loop:
async IAsyncEnumerable<Output> Process(IEnumerable<Input> inputs)
{
  var batchedInputs = inputs.Batch(10).ToList();
  var apiCallTasks = batchedInputs.Select(GetFromAPI).ToList();
  foreach (int i = 0; i != apiCallTasks.Count; ++i)
  {
    var batchResults = await apiCallTasks[i];
    var batchedInput = batchedInputs[i];
    for (int j = 0; j != batchedInput.Count; ++j)
      yield return MakeOutput(batchedInput[j], batchResults[j]);
  }
}

A: Assuming MyGenerator() returns List<Task<T>>, and the number of tasks is relatively small (even in the hundreds is probably fine) then you can use Task.WhenAny(), which returns the first Task that completes. Then remove that Task from the list, process the result, and move on to the next:
var tasks = MyGenerator();
while (tasks.Count > 0) {
    var t = Task.WhenAny(tasks);
    tasks.Remove(t);

    var result = await t; // this won't actually wait since the task is already done
    // Do something with result
}

There is a good discussion of this in an article by Stephen Toub, which explains in more detail, and gives alternatives if your task list is in the thousands: Processing tasks as they complete
There's also this article, but I think Stephen's is better written: Process asynchronous tasks as they complete (C#)

A: Using TaskCompletionSource:
IEnumerable<Task<Output>> Process(IEnumerable<Input> inputs)
{
    var tcss = new List<TaskCompletionSource<Output>>();
    var queue = new Queue<(Input, TaskCompletionSource<Output>)>();
    var cumulativeLength = 0;
    foreach (var input in inputs)
    {
        var tcs = new TaskCompletionSource<Output>();
        queue.Enqueue((input, tcs));
        tcss.Add(tcs);
        cumulativeLength += input.Length;
        if (cumulativeLength > 10)
        {
            cumulativeLength = 0
            var queueClone = Queue<(Input, TaskCompletionSource<Input>)>(queue);
            queue.Clear();
            GetFromAPI(queueClone.Select(x => x.Item1)).ContinueWith((apiTask) => {
                Queue<BatchResult> batchResults = apiTask.Result;
                while (queueClone.Count > 0)
                {
                    var batchResult = batchResults.Dequeue();
                    var (queuedInput, queuedTcs) = queueClone.Dequeue();
                    var output = MakeOutput(queuedInput, batchResult);
                    queuedTcs.SetResult(output)
                }
            });
        }
    }
    GetFromAPI(queue.Select(x => x.Item1)).ContinueWith((apiTask) => {
        Queue<BatchResult> batchResults = apiTask.Result;
        while (queue.Count > 0)
        {
            var batchResult = batchResults.Dequeue();
            var (queuedInput, queuedTcs) = queue.Dequeue();
            var output = MakeOutput(queuedInput, batchResult);
            queuedTcs.SetResult(output)
        }
    });
    foreach (var tcs in tcss)
    {
        yield return tcs.Task;
    }
}


text:
Q: Is there any reason to upgrade my battery size in Deus Ex: Human Revolution? In Deus Ex: Human Revolution, only your first battery will recharge when having zero energy. So regardless of how many battery packs you have, you'll always need to scarf down energy bars or other nutrients to refill your energy level beyond the first battery. Due to this, I can't see any reason why I would ever want to spend praxis points to upgrade my energy.
What reason is there to upgrade my energy level, or am I correct in thinking it's a waste of points?

A: I upgraded to max and maybe only once benefited from it when I was going for the pacifism when I was

 trying to save Malik.

The first points I spent were on maxing out my energy expecting for my energy to go all the way to the top and recharge. I didn't know that it wouldn't.
Had I of known that I would not have upgraded. Personally I think having 3 bars would be optimal. Allows you to do things without the need of immediately eating bars and you can use packs if you need.

A: I can only imagine one way in which it would be useful.
If you have a CyberBoost Pack, this will recharge two batteries at once. If you only have one discharged battery, half that pack is wasted.
For the jar, it recharges three batteries, which means again if you have less than 4 batteries, you will waste charge.
If you only rely on bars, there is no functional difference.

A: Having a complete battery set is useful for when cloaking and when you need to perform multiple takedowns quickly.
Partially drained cells will recharge to full. For example if you have 4 cells and only use 1 and half cells when cloaked, the cell which was half used will recharge to full.
So unless you're going to play the game in stealthily, spending most of the time the using the cloaking augmentation there is no real need to upgrade your battery size past 3 cells.

A: *

*sometimes extended cloak will buy you enough time to hack some computers (e.g. funicular)

*eliminating wasted energy - if you have only 2 cells and you eat nutrition which restores 3 cells, you'll waste up to 50% of energy

A: Also depending on your difficulty setting and play-style; you may find it useful for multiple take-downs in quick succession without having to wait an extended period of time to recharge (which may or may not put you at risk depending on how you do things).


text:
Q: Standards in P.L. Topology About a week ago, the reading course on PL topology I'm going to follow started. The aim of the reading course is to understand the basics of PL topology and have a reasonable to good understanding of the main results of this field of research (e.g. Kirby-Siebenmann). The main references for this course are the books by Hudson and by Rourke-Sanderson, from the late sixties and the early seventies. (with names that should make it clear they're dealing with PL manifolds)
When comparing the basic definitions, it quickly became clear that there are quite some differences between these books. Polyhedra in the Rourke-Sanderson case may, for instance, be rather 'wobbly'. The question arising from this is whether some standard has been established on these definitions and if so, where to find it. Is there really one book that should be considered the basis for these things?


text:
Q: Hide encryption phrase from disassembler, RAM Lets say I want to encrypt and decrypt texts in my application. Encryption of course uses 'salt',"passphrase"...
How can I securely store it in the app so that people who decompile it won't see it? As you may know you can decompile .net code into perfectly fine source code. So any variable with password can be seen. Any code that creates password can be seen too.
How can you store static passwords so crackers can't get them in RAM or by decompiling the app?

A:
How you store static passwords so crackers cant get them in RAM or by decompiling app?

You can't and you shouldn't.
Instead use a machine-specific or user-specific secret that's secured using a system feature such as the TPM, a client certificate, a user's password, or DPAPI.
DPAPI is the most straightforward to use: https://learn.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection
Using hardware cryptographic features in .NET is easy too: https://learn.microsoft.com/en-us/dotnet/standard/security/how-to-access-hardware-encryption-devices - but not all computers will have them.
Using the TPM is probably the hardest approach: Controlling TPM with C#


text:
Q: Script mypy raise error in imported package importing ruamel.yaml causing mypy error:
Python\Python37-32\lib\site-packages\ruamel\yaml\comments.py:1118: error: Type signature has too few arguments

How can I ignore this error, I have tried:
from ruamel.yaml import YAML  # type: ignore
from ruamel.yaml import YAML  # mypy: ignore

mypy==0.761

A: At your mypy.ini you can specify ignoring by modules:
[mypy-tests.*]
ignore_errors = True


text:
Q: Mysql match on two columns and get count How do I get a count of?
+---------+-------------+
|   col1  |   col2      |
+---------+-------------+
|     Joe | April       |
|    Fred | May         |
|     Sam | April       |
|     Joe | April       |
|    Mark | Jan         |
|     Joe | Dec         |
+---------+-------------+

In MYSQL how do I get a count on Names that match only if Month also match?
IE
Joe    April should be only one...

A: @Abdul's answer just needs HAVING COUNT(*) > 1
The query shold look like this now
SELECT COUNT(*), col1 , col2 FROM test GROUP BY col1,col2 HAVING COUNT(*) > 1;

Here is the execution of it:
mysql> create table test(col1 varchar(20),col2 varchar(20));
Query OK, 0 rows affected (0.33 sec)

mysql> INSERT INTO test VALUES('Joe','April'),('Fred','May'),
    -> ('Sam','April'),('Joe','April'),('Mark','Jan'),('Joe','Dec');
Query OK, 6 rows affected (0.06 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> SELECT COUNT(*), col1 , col2 FROM test GROUP BY col1,col2 HAVING COUNT(*) > 1;
+----------+------+-------+
| COUNT(*) | col1 | col2  |
+----------+------+-------+
|        2 | Joe  | April |
+----------+------+-------+
1 row in set (0.24 sec)

mysql>

If you do not care for the count, remove it from the SELECT clause
mysql> SELECT col1 , col2 FROM test GROUP BY col1,col2 HAVING COUNT(*) > 1;
+------+-------+
| col1 | col2  |
+------+-------+
| Joe  | April |
+------+-------+
1 row in set (0.00 sec)

mysql>

Give it a Try !!!

A: Create a table and insert records
create table test(col1 varchar(20),col2 varchar(20));

INSERT INTO test VALUES('Joe','April'),('Fred','May'),('Sam','April'),('Joe','April'),('Mark','Jan'),('Joe','Dec');

SELECT * FROM test;
+------+-------+
| col1 | col2  |
+------+-------+
| Joe  | April |
| Fred | May   |
| Sam  | April |
| Joe  | April |
| Mark | Jan   |
| Joe  | Dec   |
+------+-------+
6 rows in set (0.00 sec)

Find actual result
SELECT COUNT(*), col1 , col2 FROM test GROUP BY col1,col2;
+----------+------+-------+
| COUNT(*) | col1 | col2  |
+----------+------+-------+
|        1 | Fred | May   |
|        2 | Joe  | April |
|        1 | Joe  | Dec   |
|        1 | Mark | Jan   |
|        1 | Sam  | April |
+----------+------+-------+
5 rows in set (0.00 sec)


text:
Q: Does MariaDB support nested transactions? Does MariaDB support nested transactions (not savepoints)?
I want to be able to use nested transactions in stored procedures.  Currently in MySQL I am passing a parameter, "useTransaction" to each stored procedure, which controls if I start a new transaction in the body of that stored procedure.
It would more more convenient if transactions could be nested like this.

A: Nope. But MariaDB has @@in_transaction, which tells you if a transaction is already in progress.

A: No, but both MariaDB and MySQL have chained transactions:
START TRANSACTION;
[do e.g. an insert here]
COMMIT AND CHAIN;
[do e.g. another insert here]
COMMIT AND CHAIN;
[do e.g. yet another insert here]
COMMIT;


text:
Q: R Replace character data containing exponent (e.g. E+11, E+20) with number of 0's that is dynamic I have a dataframe df_before which one of columns contains values such as:
id
123456789
1.11E+2
3.52E+4
5.60E+5
0001112345857RAE

and would like to convert them in df_after to:
id
123456789
111
35200
560000
0001112345857RAE

Basically I want to strip off the period . and replace any E+XX with 0's according to the number/ power of the exponent. This is what I have tried:
 df_after$id <- ifelse(str_detect(df_before$id, "E\\+\\d+$"),
                                gsub("E\\+\\d+",
                                     strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", df_before$id)) - 2),
                                     gsub("\\.", "", df_before$id)),
                                df_before$id)

Each smaller chunk of the above codes worked with 1 single input, for example this:
strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", "6.32E+3")))

results in:
"000" # which is as expected

also:
gsub("E\\+\\d+",
    strrep("0", as.numeric(gsub(".*E\\+(\\d+)$", "\\1", "6.32E+3")) - 2),
    gsub("\\.", "", "6.32E+3"))

gives:
"6320" # as expected and desired

But when I applied it to the whole column using ifelse and str_detect (which also works as expected for those entries containing E+XX, it runs very slowly and returned NA's and some values like 6320NA000NA000NA000NA000....<truncated>
Could someone please assist me in fixing this block of code so it will work with the dataframe column?
Thank you so much!

A: We can use as.numeric to convert the numeric values while the non-numeric becomes NA. Using is.na, then we index and assign those values that are only numeric to the 'id' column
df_after <- df_before
v1 <- as.numeric(df_before$id)
i1 <- !is.na(v1)
df_after$id[i1] <- v1[i1]
df_after
#              id
#1        123456789
#2              111
#3            35200
#4           560000
#5 0001112345857RAE


text:
Q: Java get fraction method I am trying to make a method that returns the fractional value of a decimal number.
//these are included in a class called 'equazioni'

private static long getMCD(long a, long b) {
 if (b == 0)
  { return a; }
 else
  { getMCD(b, a % b); }
 }

public String getFraction(double a) {
 String s = String.valueOf(a);
 int decimali = s.length() - 1 - s.indexOf('.');

 int den = 1;
 for(int i = 0; i < decimali; i++){
   a *= 10;
   den *= 10;
 }

 int num = (int) Math.round(a);
 long mcd = getMCD(num,den);

 return String.valueOf(num/mcd) + "/" + String.valueOf(den/mcd);
}

These 2 methods works perfectly with most of values. For example with a 8.65 it returns a 173/20, or 78.24 it returns a 1956/25. It's called in this way:
equazioni eq = new equazioni(a,b,c);
jTextField4.setText("8.65= " + eq.getFraction(8.65));

I am having troubles with fractions like 2/3, 5/18, 6/45... because the denominator is divisible by 3 and so the fraction is a periodic number. How could I represent it?
My problem is also "How could I recognize that it's a periodic number?". I thought that I could something like this
int test = den % 3;

If the denominator is divisible by 3, then I have to generate a fraction in a particular way. Any suggestion?

A: If I correctly understood your question, I am afraid it does not have a complete solution. Since a float is stored with a finite number of bits, not all fractions can be represented, especially the ones that are not decimal numbers like 2/3. Even for decimal numbers, not all of them can be represented.
In other words, your method will never be called by the float representation of 2/3 as an input, since this representation does not exist. You might be called with 0.66666666 (with whatever the limit of digits would be in Java), but that is not 2/3...
See this link for more details about floating point representation in Java: http://introcs.cs.princeton.edu/java/91float/


text:
Q: Elements and structure of $\text{Gal}(\mathbb Q(\zeta_{21}):\mathbb Q)$
Let $\zeta_{21}$ be a primitive 21st root of 1. Describe explicitly the elements of the Galois group $\text{Gal}(\mathbb Q(\zeta_{21}):\mathbb Q)$ and determine the structure of this group.

From finding the minimal polynomial I know that the order of the Galois group must be 12. So $\text{Gal}(\mathbb Q(\zeta_{21}):\mathbb Q)≅(\mathbb Z/21\mathbb Z)^{\times}$.
I have seen online that $(\mathbb Z/21\mathbb Z)^{\times}$ has the structure $C_2 \times C_6$, how has this been found?
How can I describe the elements of this Galois group?

A: I suppose you mean $U(21)$. This has $\phi(21)=12$ elements, and is not cyclic:
For what $n$ is $U_n$ cyclic?
From $\mathbb{Z}/21\cong \mathbb{Z}/3\times \mathbb{Z}/7$ we see that $U(21)\cong U(3)\times U(7)\cong C_2\times C_6$. Here we have used that $U(p)$ is cyclic of order $p-1$, see the above link.


text:
Q: Scrolling is not working when the container is not visible I have two tabs, first tab is a tab that shows video info, second tab has the comments on that video.
The comments sections has max-width and is scrollable.
I use a scroll function that scrolls to the bottom of the comments every time the component is rendered.
The problem is when I am on the video info tab and switch to the comments tab, the scrolling does not happen, it only happen when I add a new comment.
Why it does not scroll even when I am in the video tab so that when I open the comments tab I found it at the bottom ?
const scrollToBottom = () => {
    animateScroll.scrollToBottom({
        containerId: "blueprint-comments"
    });

}

useEffect(() => {
    scrollToBottom();
});


text:
Q: Can I use ob_clean() without ob_start() before? I am not used to ob_* functions and I began by reading the documentation.
I would like to use ob_clean() in a method but the documentation says:

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

However I tried (just to see how it "wouldn't work"):
echo 'a';
ob_clean();
echo 'b';

Which outputs b. Everything seems working fine here, but following the documentation, it shouldn't, should it ?

*

*Is ob_start() mandatory for ob_* functions ?

*Is there a variable (in the php.ini for example) which default value allows to ommit ob_start() ?

*How should I understand "ob_clean() will not work" ? What should I expect ?

A: The short answer is that yes, you have to turn on output buffering before you can use ob_clean. However, it is possible that you have output buffering enabled for all files through the output_buffering ini parameter (see the manual). The way to check for this is through ob_get_level():
echo ob_get_level();

If the result is non-zero, output buffering is enabled.
If you do use ob_clean() without buffering enabled, you should see an error similar to this:

Notice: ob_clean() [ref.outcontrol]: failed to delete buffer. No
  buffer to delete. in [file-path]


text:
Q: Intuition behind training and test MSE when using regression trees Imagine that we have a supervised learning setting. Training data is given by the input-output pairs $(\mathbf{x}_n, y_n)$ for $n=1,\dotsc,N$ and similarly, the test data $(\mathbf{x'}_n, y'_n)$ for $n=1,\dotsc,N'$. Rather typical setting. Further we can assume that we have $D$ features and that $y_n \in \mathbb{R}$ and $\mathbf{x}_n \in \mathbb{R}^D$. Now, the idea is to employ a recursive binary splitting in order to obtain a nested sequence of regression trees of increasing size.
Now, what would happen if there was NO true relationship between $y$ and $\mathbf{x}$? Say, I currently have a tree of some size $M$, what would happen to training and test MSE if I continued to the tree of size $M+1$? Or if there was a true relationship between $y$ and $\mathbf{x}$ but the relation was not constant (say we don't know how far from constant it is). If I increase the size of the regression tree to $M+1$ in this scenario - can I tell what would happen to training and test MSE?
In general, how does the training and test MSE work in this case? I know that the regression trees are likely to overestimate so in my understanding, if there is a true relation between input and output variables, then when increasing depth of a tree the training MSE should further decrease? But what about the test MSE? Is the MSE curve for that case U-shaped? And how about the case when there is no true relation between inputs and outputs?

A: Here is my hypothesis:
The training MSE will always decrease with increasing tree depth.  Trees are prone to overfitting, and so the test error will increase because each model is highly highly overfit.
I coded something up in python to evaluate this hypothesis for the case where there is not true relationship.  Here are the results. Blue is training error, orange is test error.  In general, we observe what I thought we would.  No surprise there.

I imagine we would see something similar in the case there is a relationship between X and y.  Trees are notorious for overfitting, so the general pattern of more depth leading to more overfitting is going to persist.


text:
Q: How to prove that the sequence $y_{n+1}=1-2y_n$ where $y_1=0$ has no convergent subsequences How to prove that the sequence $y_{n+1}=1-2y_n$ where $y_1=0$ has no convergent subsequences?
I don't know where to even begin with this proof. I'm assuming I need to prove that $|y_n|$ converges to infinity first.

A: We have: $|y_{n+1}| = |2y_n - 1| \ge 2|y_n| - 1\ge 2(2|y_{n-1}| - 1)-1=4|y_{n-1}|-3\ge 4(2|y_{n-2}|-1)-3=8|y_{n-2}|-7\ge 8(2|y_{n-3}|-1)-7=16|y_{n-3}|-15 \ge 2^{n-3}|y_4|-(2^{n-3}-1)=3\cdot 2^{n-3}-2^{n-3}+1=2^{n-2}+1, \forall n\ge 4$. Thus $|y_{n}| \to +\infty$. You can fill the rest of the work.

A: The first few values are
$0, 1, -1, 3, -5,
11, -21
$.
So it looks like it is
growing exponentially
with alternating signs.
Any sequence with
$|y_{n+1}|
\gt |y_n|+a
$
for some $a > 0$
and all large enough $n$
can not have a convergent subsequence.
If it does
and the subsequence is
$(y_{n_k})$,
then,
for any $c > 0$
$|y_{n_{k+1}}-y_{n_k}|
\lt c
$
for all large enough $k$.
Since
$|y_{n+1}|
\gt |y_n|+a
$,
$|y_{n+k}|
\gt |y_n|+ka
$
so,
if $n > m$,
$|y_{n}-y_m|
\gt (n-m)a
$.
Therefore
$|y_{n_{k+1}}-y_{n_k}|
\gt a(n_{k+1}-n_k)
\ge a$.
This implies that
$c > a$
which is false
as we can chose $0 < c < a$.
In our case,
if $|y_n| > 2$
then
$|y_{n+1}|
=|1-2y_n|
\ge 2|y_n|-1
$
so
$|y_{n+1}|-|y_n|
\ge |y_n|-1
\gt 1$
and
$|y_{n+1}|
\gt 2$.
Therefore
$y_n$
does not have a
convergent subsequence.
We can also find
an explicit form.
In this case,
based on experience,
I would try to find a $c$
such that
$y_{n+1}+c
=-2(y_n+c)
$.
From this,
an explicit form is
readily found.
Regrouping this,
$y_{n+1}
=-3c-2y_n
$,
so $-3c=1$
or
$c=-\frac13$.
As a check,
if
$y_{n+1}-\frac13
=-2(y_n-\frac13)$,
then
$y_{n+1}
=1-2y_n
$.
By induction,
$y_{n}-\frac13
=(-2)^k(y_{n-k}-\frac13)$.
Setting $k=n-1$,
$y_{n}-\frac13
=(-2)^{n-1}(y_{1}-\frac13)
=-\frac13(-2)^{n-1}
$
so
$y_{n}
=\frac13(1-(-2)^{n-1})
$.

A: This is a linear recurrence for which you can have an expression for the general term. You can start by solving the homogeneous equation, $y_{n+1} = -2 y_n$, yielding $y_n^h = c (-2)^n$ and then find a particular constant solution. This way you conclude that $y_n = c (-2)^n + \frac 13$. Finally, using the initial condition, $y_n = \frac 16 (-2)^n + \frac 13$. Given the general term for this sequence, the conclusion follows trivially.

A: $y_{n+1}=1-2y_n, y_1=0$. $0,1,-1,3,-5,11,-21,43:1,-2,4,-8,16,-32,64$
$y_n=\frac{(-2)^{n-1}-1}{-3}$. Take consecutive differences and one finds the original sequence is a the geometric series starting with 1 and having common ratio -2. This tells us all the elements of the sequence are distinct integers. The smallest possible difference between two distinct integers is 1. One can use this to prove there are no convergent subsequences.
Suppose some subsequence of the set converges to real  $a$. Then by definition, $\forall \epsilon>0 \exists \ y_n \ s.t. |y_n-a|<\epsilon$
$a-\epsilon<y_n<a+\epsilon$. We must have some $y_m \ s.t. y_n<y_m<a+\epsilon $ else we can select $\epsilon=(a-y_n)/2$ and disprove convergence. On the other hand. $|y_n-a|<|y_m-a|<\epsilon$
$|y_m-y_n|=|y_m-a + a-y_n|\le |y_m-a|+|y_n-a|<2\epsilon$. We can choose any $\epsilon$ because of convergence. Pick $\epsilon=1/4$ and we have $|y_m-y_n|<1/2$, two integers whose difference is less than 1. Another contradiction.


text:
Q: How to build an Angular Plunker locally I have create a new Plunker Angular project and have downloaded the code zip file.
I unzipped it but there no instructions on how to run it locally.
In the project folder I have:
- config.js
- index.html
- readme.md
src
-style.css

How to I set this up to build it locally?

A: Since you have explicitly stated that you require to use SystemJS instead of Webpack, you have three options here:

*

*1 - use older version of Angular CLI, as the early versions used SystemJS;

*2 - use old Angular Quickstart available @GitHub, which is using SystemJS;

*3 - find some tutorial on how to use Angular and SystemJS, such as this one
Note that your Angular code is independent on SystemJS and all your modules, components or whatever is that you created in Plunker should be working in Angular CLI project sporting Webpack. Hence there should be no worries that new Angular CLI versions are using Webpack instead of SystemJS as far as you are interested only in Angular code.
After you have your environment ready, use your Plunker code within it.


text:
Q: join: reference to column is ambiguous I want to join 2 tables with the CONT_ID parameter
 select (case when age_years >= 18 and age_years < 30 then '18-29'
         when age_years < 50 then '30-49'
         when age_years < 70 then '50-69'
          when age_years < 100 then '70-100'
         end) as age_range,
          count(DISTINCT CONT_ID) as num,
       SUM(ACAUT) / COUNT(*) as avg
     from CLIENT c
      left join PAYTB t
       on c.CONT_ID = t.CONT_ID
   group by (case when age_years >= 18 and age_years < 30 then '18-29'
      when age_years < 50 then '30-49'
      when age_years < 70 then '50-69'
      when age_years < 100 then '70-100'
      end)
      order by min(age_years);

Error
SQLCODE = -203, ERROR:  A REFERENCE TO COLUMN CONT_ID IS AMBIGUOUS

A: You have to specify which column CONT_ID to use in COUNT DISTINCT. Instead do
COUNT(DISTINCT c.CONT_ID)