text:
Q: Setup 3 Sites To Connect To 1 Database and Share Data How do I setup 3 different Wordpress installations on 3 different servers, all of which connect to a single database and also share the same data?
I'd like to set up 3 different servers. One for development, QA/Staging, and Production. Each site should be isolated from the other and they are simply used to display the same data from the database, meaning:

*

*Developers will be working in the development server, meaning that this installation will be in a state of constant change.

*The QA/Staging server will be in less of a state of change as QA folks will be testing functionality added from the development team.

*Production will only be updated periodically from tested and working code thats vetted through the QA/Staging server

Please not that sharing "upload" resources is not an issue as I plan on using AWS S3 service to store all of my resources (ex. images), while also using AWS CloudFront to act as a CDN to serve all said resources.

A: You can use subdomains for your dev and QA installs. Such as qa.domain.com and dev.domain.com. When the subdomains are created sub directories are usually created too. You can install an additional wordpress in each subdomains directory. Then create 2 additional databases. Backup the production database and load it to the 2 new databases. Set up your config.php files for these new database and you have 2 new servers. You will have to make some updates to the databases. At least two location home and site_url in the _options table. I usually open the .sql file in a text editor and seek and replace domain.com with sub.domain.com.

A: To elaborate on my suggestion, here is some working code:
// hook in before theme is loaded
add_action('plugins_loaded','custom_maybe_switch_themes');
function custom_maybe_switch_themes() {
    if (!is_user_logged_in()) {return;}
    if (!current_user_can('manage_options')) {return;}

    // check for query request eg. ?usertheme=theme-slug
    if (isset($_REQUEST['usertheme'])) {
        // sanitize request
        $usertheme = strtolower(sanitize_title($_REQUEST['usertheme']));
        global $current_user; $current_user = wp_get_current_user();

        // maybe reset user meta stylesheet
        if ($usertheme == 'reset') {delete_user_meta($current_user->ID,'stylesheet'); return;}

        // validate theme
        $theme = wp_get_theme($usertheme);
        if ($theme->exists()) {
             delete_user_meta($current_user->ID,'stylesheet');
             add_user_meta($current_user->ID,'stylesheet',$usertheme);
        }
    }
}

// add filter to stylesheet option
add_filter('pre_option_stylesheet', 'get_user_stylesheet');
function get_user_stylesheet($stylesheet) {
    if (!is_user_logged_in()) {return $stylesheet;}
    if (!current_user_can('manage_options')) {return $stylesheet;}

    // check user meta stylesheet
    global $current_user; $current_user = wp_get_current_user();
    $userstylesheet = get_user_meta($current_user->ID,'stylesheet',true);
    // if we have a value use it instead
    if ($userstylesheet) {return $userstylesheet;}
    return $stylesheet;
}

To switch to a theme on a user basis, use ?usertheme=theme-slug
...and to reset just use ?usertheme=reset
Since all the theme code is loaded dependant on the stylesheet used, you could set up Child Themes directories for Live, Staging and Development (with the same Parent Template) and switch between themes really easily as a developer and see the results immediately on the same domain. :-)
The only caveat I can think of is testing major plugin updates, you would still need a development environment for that purpose and maybe sync the database across to test them with the current database content. This is only because you don't know if they will change their options database table structure (though rare, there is no going back so you could break a live site that way.)
Something further would be needed to test the site output for logged out users, but that could be done with a different querystring for one-off loads, or with cookies instead of user meta for a similar persistent result.
Anyway, the advantage of being able to have code snippets organized in files for testing in development and staging on the same domain, making pushing new changes between them really easy, and to not have to worry about database syncing all the time (though that's another workable approach) makes this a very convenient way of doing things I think.


text:
Q: Nodejs reading image and sending it to a graphql server with multipart/form-data I need to read a locally stored image, embed the image to a form with form-data using the GraphQL multipart request specification, then perform a POST request to a graphql server with the body of the request being the form data itself.
I read the image using fs.readFile, and use the data as an argument to my post data function:
fs.readFile('./location/to/image/image.jpg', (err, data) => {
    if (err) {
        throw (err);
    }

    postData(data);
});

My postData function goes as follows:
function postData(readable) {
    /** Create form data */
    const requestBody = new FormData();

    /** Define the query */
    const sdl = `
        mutation ($image: Upload!) {
            testUpload(image: $image){
            code
            success
            message
            }
        }
    `;

    /** Follow instructions according to graphql multipart request specification
     * https://github.com/jaydenseric/graphql-multipart-request-spec */
    requestBody.append(
        'operations',
        JSON.stringify({
            query: sdl,
            variables: { image: null },
        })
    );

    requestBody.append(
        'map',
        JSON.stringify({
            0: ['variables.image'],
        })
    );

    requestBody.append('0', readable);

    /** Submit the form */
    return new Promise((resolve, reject) => {
        requestBody.submit('http://localhost:4000/api/graphql', (err, res) => {
            if (err) {
                console.error(err);
                reject(err);
            } else {
                let body = '';
                res.on('readable', () => {
                    body += res.read();
                });

                res.on('end', () => {
                    resolve(JSON.parse(body));
                });
            }
        });
    });
}

What happens is, I successfully hit my API and my resolver, but the file's mimetype is received as application/octet-stream.
I am assumming that I am not reading the data correctly, or something else entirely.
I would truely appreciate any help. Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ItextSharp/PDF - image border appears in PDF file I really need your help! I have an issue creating a PDF file. I did the research, but found nothing that can help me. When I insert an image to PDF - a border appears around the image. I do not set ANY border and an image doesn't have any borders. When I resize the PDF page - the border can disappear and after other resizing it appears again. When I print a PDF page - there is no any border around the image. My code in VB.NET:
theImage = iTextSharp.text.Image.GetInstance(screenShotPath)

width = currentPageObjectsListSortedByZIndex(j)(9).Substring(0,
 currentPageObjectsListSortedByZIndex(j)(9).Count - 2)

height = currentPageObjectsListSortedByZIndex(j)(10).Substring(0, currentPageObjectsListSortedByZIndex(j)(10).Count - 2)

width = convertPixelsToPoints(width)
height = convertPixelsToPoints(height)

Dim x = Convert.ToDouble(currentPageObjectsListSortedByZIndex(j)(8).Substring(0, currentPageObjectsListSortedByZIndex(j)(8).Count - 2)) + Convert.ToInt32(padding)

Dim y = Convert.ToDouble(currentPageObjectsListSortedByZIndex(j)(7).Substring(0, currentPageObjectsListSortedByZIndex(j)(7).Count - 2)) + Convert.ToInt32(padding)

x = convertPixelsToPoints(x)
y = convertPixelsToPoints(y)
y = Doc.PageSize.Height - y - height

theImage.SetAbsolutePosition(x, y)
Doc.Add(theImage)

This is the example of a PDF page:

Do you have any idea how to fix this issue? Thank you for any answer!
Sorry if my question looks weird.


text:
Q: Am I using window.location.replace right? (also am I writing commands right?) I kind of get all my coding information from the internet rather than a class, and certain answers I can't really understand so hopefully I'll get a simple answer to a possibly stupid question.
In a part of my website, I've got a button which brings up a window.prompt and it asks the viewer if they would like to go to one page (I've called it Timeline because it's a timeline of my art portfolio) or to the other. The prompt works perfectly fine, and I attempted to code it so that if, for example, the user typed in "Timeline" the webpage would automatically redirect them to the Timeline page (which for me is empty at the moment) and vice versa if they typed in "Term 1" (the name of the other page.) I found out about window.location.replace and assumed that it would work if I tried to get it to redirect the user, but when I run my webpage nothing happens after I type in the prompt window. I checked the Developer Tools on Chrome and it didn't report any errors, so is it just me typing some stuff wrong?
   function promptFunction() {
    var choice = window.prompt ("Would you like to go to the Timeline or to Term 1?")

    if (choice === "Timeline")
        function redirTime() {
        window.location.replace() ("Timeline.html");
        }

    else if (choice ==="timeline")
        function redirTime() {
        window.location.replace() ("Timeline.html");
        }

    else if (choice ==="Term 1")
        function redirFirstTerm() {
        window.location.replace() ("Term 1.html")
        }

    else if (choice ==="term 1")
        function redirFirstTerm() {
        window.location.replace() ("Term 1.html")
        }

    };

This again is probably me looking for an answer that's right under my nose, so if the answer is something obvious, sorry ^^'
Edit: I've got an answer now; thank you very much! (I did think it was something to do with the way I was typing it, sorry)

A: The code you posted creates, based on choice a function, but the function is never executed (or you omitted this code).
Additionally the window.location.replace()("...") part is wrong. It calls the replace function on window.location with no arguments and uses the result of this function call again as function an passes e.g. "Timeline.html" as argument.
If all you want to do is setting the location, assign it directly, e.g. window.location = "https://stackoverflow.com" or in your case window.location.href = "Timeline.html" (see https://developer.mozilla.org/en-US/docs/Web/API/Window/location).


text:
Q: Equivalence Relation Quotient I would like to solve Problem 1.7.6 from Dugundji's Topology:

Let $S$, $R$ be two equivalence relations in $A$, with $S \subset R$. Let $1^* : A/S \to  A/R$ be the map induced by relation preserving map $1_A$. Define $(S a) R/S (Sb)$ if $1^*(S a)=1^*(Sb)$.
Show that $R/S$ is an equivalence relation, and there is a bijection of $(A/S)/(R/S)$ onto $A/R$

A: If $f:X\rightarrow Y$ is a function then the relation $\sim$ defined
by $x\sim x'\iff f\left(x\right)=f\left(x'\right)$ is always an equivalence
relation.
Verification:
reflexive: $f\left(x\right)=f\left(x\right)$,
symmetric: $f\left(x\right)=f\left(x'\right)\Rightarrow f\left(x'\right)=f\left(x\right)$
transitive: $f\left(x\right)=f\left(x'\right)\wedge f\left(x'\right)=f\left(x''\right)\Rightarrow f\left(x\right)=f\left(x''\right)$.
The map $\phi:\left(A/S\right)/\left(R/S\right)$ defined by $\left[\left[a\right]_{S}\right]_{R/S}\mapsto\left[a\right]_{R}$
is welldefined and is a bijection.


text:
Q: subprocess.check_output() fails to return command results when pinging ip's I am trying to use subprocess module in python to ping ip addresses. Here is the code.
command = ['ping', '-c', '1', 1.1.1.1]

print((subprocess.check_output(command)).decode("utf-8"))

This would return the proper ping result for 1.1.1.1.
Ping statistics for 1.1.1.1:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 4ms, Maximum = 4ms, Average = 4ms

However, if were to ping an invalid ip, like 0.0.0.0
command = ['ping', '-c', '1', 0.0.0.0]

subprocess.call(command)

print((subprocess.check_output(command)).decode("utf-8"))

Then subprocess.call(command) would return
Pinging 0.0.0.0 with 32 bytes of data:
PING: transmit failed. General failure.

Ping statistics for 0.0.0.0:
    Packets: Sent = 1, Received = 0, Lost = 1 (100% loss)

However once the code reaches subprocess.check_output, it will not return anything and all subsequent code following it will not run. How can I have subprocess.check_output() return the full ping statement thrown by subprocess.call()?

A: subprocess.check_output() raises an exception if the command returns a non-zero exit status, and ping does this when it doesn't get a response to the pings.
Instead of using subprocess.call() and subprocess.check_output(), you should use subprocess.run().
command = ['ping', '-c', '1', '1.1.1.1']
print(subprocess.run(command, stdout=PIPE, stderr=STDOUT, encoding="utf-8").stdout)


text:
Q: Matlab model: Continuous & Discrete-Time behaviour of a Switched-Cap. Integrator circuit I would have the following question at the end of this text. To bring everyone to a common understanding, I need to first develop it a bit and make some statements. I tried to be as precise and short as possible, but as long as necessary. I also posted my question in the forum "https://designers-guide.org/forum/YaBB.pl?board=behavioral" which also helped me further (many thanks again to Ken Kundert), but on this point now I am stuck. Therefore, I try it here, which are following possible more people and one of you might have a good (= intuitive, explaining, not 10 pages of equations, pls.) answer for me (hopefully). So many thanks in advance!
#1) A Zero-Order-Hold ("ZOH") (Sample & Hold "S&H") block stand-alone:
First, we watch the Bode plot for this block stand-alone (s=j2pi*f ; Ts=sample time). We notice:
*) The envelope of the transfer-function goes "DOWN" (with -20dB/dec).
*) The nulls go down to –INFINITY (only because of resolution, not as much in this graph).
*) At half the sampling frequency "fs/2", in this example 500 Hz, the magnitude is down by approx. -4 dB.

I compared the Bode diagram of this ZOH above, to the "SAMPLE & Hold (S&H)" from Ken Kundert ("sqrt( (sinc(f*Ts)).^2 );" f=frequency). The result: The MAGNITUDES are completely IDENTICAL (proof not shown here). However, the phase information from Kundert's S&H is missing ( = constantly 0°). => As a result, I say: "Approx., a ZOH = S&H".
#2) Reference circuit to be modelled: A switched-cap (SC.) integrator:
The following circuit shall be my reference, which I want to model with Matlab at a later stage: It shows a (parasitic-sensitive), lossy switched-cap. integrator, operated at sampling frequency fs = 1 kHz. As input stimulus, I put an AC source with 1V magnitude. (I thought about replacing the schematic details just by the block diagram, but maybe the details are important, it is often the case to know what was done exactly!)

To obtain the following Bode plot, I do the "PAC sampled" analysis (at rising edge) in the Cadence SpectreRF simulator, since I am interested in its Discrete-Time (DT) behaviour:

We notice:
*) As requested by theory, the DT (Discrete-Time) answer of the sampled output node of the circuit is symmetrical around fs/2 (500 Hz), at fs (=1kHz), the magnitude goes up again to the DC value (+80 dBV). (If one would do a linear frequency axis plot, one would see the symmetry around fs/2 better.)
*) So the "nulls" at multiples of fs go up only to the DC gain of +80 dBV, not to +infinity. (Because of resolution some are not even reaching +80 dBV, but this is an artefact I have understood and shall not be a topic for further discussion here.)
*) At fs/2 at 500 Hz, the magnitude is -6 dBV.
So far, so good.
#3) Try: Matlab model of integrator from #1  …
#3a) ... try model over Discrete-Time (DT):
Everything here is clear and there is no question from my side. I just wanted to list it for completeness. So if I model over the following Matlab commands "z=exp(jwTs);   Aol=10000;   f=1-1/Aol;   Int_z=-z^-0.5/(1-z^-1*f);", I get the following bode plot which is fine and exactly what I expected.

We see from the above cyan graph that at fs/2, we also get -6 dBV, further, it is symmetrical around fs/2 (500 Hz) and so, at fs (1 kHz), the magnitude gets up to +80 dBV again.
So far, so good.
#3b) ... try model over Continuous-Time (CT) with subsequent sampling:
Now I would like to model the real circuit from #2 over a CT model with subsequent sampling applied.
Because then, it allows me to also model the speed limit of the opamp for instance (and for more reasons (noise)).
I expect the same results as from the SpectreRF simulator (shown in #2 in green color) if I sample the CT integrator output afterwards with a Sample&Hold (ZOH, shown in #1).
We see from below graph:
*) The pink curve shows the Matlab model of the CT integrator (reaching -10 dBV at fs/2).
*) The blue curve shows the Matlab model of the CT integrator DIVIDED     subsequently by the ZOH from #1.
*) The red  curve shows the Matlab model of the CT integrator MULTIPLIED subsequently by the ZOH from #1.

We further notice:
If we DIVIDE the CT response (pink) of the Matlab model by the S&H (ZOH, orange, see #1) transfer-function, we get the blue curve. Doing so, yields:
*) A PERFECT match at fs/2 at least of the Matlab model (blue) to the DT response of the Cadence circuit (green): The -10 dB from the pink DIVIDED by the ZOH (thus +4dB), gives together the blue curve, which has also the -6 dBV at fs/2. So from this point of view, the procedure, what I do, is good ( = divide the CT tf. by the ZOH).
*) However, what is not matching so well, is, that the result is not completely symmetrical around fs/2. Ok, the "nulls" at multiples of fs go up also here, but not just to the DC gain limit of +80 dBV, but to theoretically +infinity (since the ZOH from #1 shows -infinity nulls). So from this point of view, the procedure, what I do, is not so good.
#4) Questions:
Now, there come my 2 questions:
If I try to model the real Cadence switched-cap. (SC.) integrator circuit (in green color from #2) by a Continuous-Time (CT) integrator Matlab model (in "s") (in #3b) which is then sampled by a ZOH (S&H) to get the DT response:
Q1 ==> Why the hell it seems I have to DIVIDE by the ZOH (S&H) transfer-function and NOT to MULTIPLY by it to get somehow matching results (blue curve) to the Cadence SC circuit (green)??
To account equivalently for the "_SAMPLED" option of the Cadence PAC analysis in the real circuit, also in this model, for me, this means (maybe I am wrong here??) I logically would have to subsequently MULTIPLY the integrator output by the S&H transfer function. This is my interpretation, because the strange thing is (= above question), obviously, I have to DIVIDE the integrator output by the ZOH transfer function, and not to multiply by it in order that the "nulls" go also up, and not down, as in the S&H stand-alone case. Then the Bode diagram of this result (blue color) matches approx. the real Cadence SC. circuit (green), apart from the nulls going up higher than just to the +80 dB DC gain limit, as said. Of course, then, there is no symmetry around fs/2 anymore (ok, I also probably do not have a DT signal which is valid only at 1/fs time points but still a CT signal whose value is held constant until the next point in time). So,
Q2 ==> Which mathematical operation I do have to for the CT Matlab model in order to also get out the DT response ?? Just sampling (with the S&H or ZOH) seems to be too less!
Thanks for any hint in advance,
bernd2700


text:
Q: using and displaying object data, PHP and json/jquery I am running into a brick wall when passing object data from jquery to PHP.  I'm still trying to get my head around OOP.
Code follows:

<input type="button" id="regSubmit" class="button" value="Register!" />

The above code does 3 things.  Catches a button click, and then: eclares a variable (jsonvar1), and performs an ajax request on that variable to a PHP backend.
Now the code in the PHP backend:
if (filter_has_var(INPUT_POST, "regemail")) {

    $data = $_REQUEST["regemail"];

    //echo "
I got some data!
";

    //print_r($data);

    //echo $data->skillz;

    //echo $data;

    var_dump($data);

} else {

echo "No Data.";
}

(safely ignore all the echoes and dumps in the above PHP. That would be me flailing about trying to use the data in some fashion)
Question:  How can I pull data from the object in PHP into variables or an array, or if you prefer, how can I work directly with the values in that object?  (assuming it is an object, and that I'm not making some other unrelated mistake)
I'm wondering if I've neglected to tell my request that it is JSON...  http://api.jquery.com/jQuery.getJSON/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Edit:
I've attempted to add
    echo json_decode($data);
to my PHP code, but it returns a blank dataset.
I also attempted to put
    dataType: 'json',
in my ajax query.
Still not having any luck it seems.

A: You have run into a rather simple error which is easy to overlook: jsonvar1 contains an object, and when you concatenate it to "regemail=" with the + operator, it is turned into a string - but not in the way you intended. The resulting string is "[object Object]" because JSON conversion is not done automatically for you. Instead, the line should be
data: 'regemail=' + JSON.stringify(jsonvar1),

In your PHP file, the line
$data = json_decode( $data );

will give you an object to work with, as @sirlancelot has already said.

A: You'll want to use json_encode for that on the server side.
if (filter_has_var(INPUT_POST, "regemail")) {
    $data = $_REQUEST["regemail"];

    //echo "
I got some data!
";
    //print_r($data);
    //echo $data->skillz;

    echo json_encode($data);
} else {
    echo "No Data.";
}


text:
Q: Display Data one at a time using Jquery I need to display data one at a time but my code is displaying the data all at once, what am I missing ?
Here is my HTML/PHP CODE

    <?php for ($i=1; $i < 1000; $i++) {
    ?>
    <p id="<?php echo $i; ?>" style="position: absolute; display:none; ">Name <?php echo $i; ?>

    <?php
    }
    ?>

And here is my Javascript Code

I'm using jquery version 3.2.1

A: You have to do this to show data one at a time.

One click to show all data one at a time with 500 ms delay:

A: I'm using jquery to append 1000 div inside a wrapper instead using PHP.
Ref my code if it's useful.

$(document).ready(function() {
  for (var i = 0; i <= 1000; i++) {
    $(".wrapper").append("
" + i + "
");
  };
});
var step = 0;

function hideItemFunc() {
  var interval = setInterval(function() {
    $("#" + step).animate({
      opacity: 1
    }, 500);
    step += 1;
  }, 500);
}
.item {
  width: 20px;
  height: 20px;
  display: inline-block;
  margin: 3px;
  font-size: 9px;
  background: #aaa;
  text-align: center;
  line-height: 20px;
  opacity: 0;
}

<button class="btn2" onclick="hideItemFunc()">Run</button>

A: You can use setInterval instead of setTimeout. That will call the function repeatedly. SetTimeout executes only once while setInterval is repetitive.
Also, the execution sequence you need repeated should inside the function body of setInterval.
var count = 1;
var delayMillis = 5000; //5 second

$(document).ready(function(){
    $("#btn2").click(function(){
            setInterval(function() {
                //your code to be executed after 5 second
                $("#" + count).show();
                count++;
            }, delayMillis);

        });
    });

The current code displays each of the p records after a 5 seconds one after another. anything else you need to do will be inside the setInterval Block


text:
Q: Mapping an object's projected 3D path to a pre-defined top-down 2D path. The title of the question may be misleading and the context simpler. Please suggest more appropriate tags for this question.
Consider looking at a plane from two different perspectives.

*

*Perspective 1 $(P1)$: Looking straight down from a height with everything in 2D. $(P1)$ is through a viewport ($VP1$) such that the absolute coordinates are known e.g. $(-100,-100),(100,100)$. That makes the centre of our image $(0, 0)$. Nothing in this context needs to go beyond these boundaries. These are absolute coordinates.

*Perspective 2 $(P2)$: Standing on the plane and looking at things in 3D. $(P2)$ is through a viewport $(VP2)$ that is actually a surveillance camera mounted on a pole at say $(-90,-90)$ looking at the most of what was visible through $(VP1)$.

Now, using $(VP1)$, I create a number of arbitrary points on the plane such that the order in which points are created is preserved along with the coordinates. You can consider this as a one-way path that objects can legally travel on. Let's also assume that paths do not overlap hence they are unique.
This next step is a little hard to explain. I take the live image (2D of course) from $(VP2)$ and project the paths above onto this image. I already have the projection formula worked out.
So far so good. I then process the image from $(VP2)$ and detect moving objects. These objects are detected in the form of rectangles which move over time. Please ignore speed, velocity, etc. We are only interested in an ordered set of points (implying direction). For the sake of simplicity, let us also assume that these objects will always enter the image and leave without being stationary.
What I need to find out is

*

*Has the object travelled on a legal path?

*Which of the paths maps best to the objects movement?

Now I do have a conceptual idea of what to do here i.e. take each point of an object's movement and check to see if it falls within a threshold of the projected path points. Also, check to see if subsequent points follow the general direction of the path drawn via $(VP1)$.
The concept is fine but a lot of corner cases arise such as the size of the detected rectangles and their distance from the camera (which is easy to calculate if they are on a path etc.). How could I express this mathematically?


text:
Q: How do I completely uninstall and old version of Redis? I'm trying to upgrade to redis version 2.6.13 and I want to remove all old versions on my ubuntu 12.04 system.

A: There is a make-command but no make-install-command. Because of this, I think it is enough to delete just the main-folder (where you executed the make-command) and every file you copied to any location on your filesystem according to the guide.


text:
Q: parsing the date object in javascript Date.parseWeird=Date.prototype.parseWeird=function(d)
{
    return new Date(Date.parse(d));
};

var d = /Date(-65424600000)/

How can i parse this date and show in MM/DD/YY format.
16/09/1956

A: I remove the extra:
Date.parseWeird=Date.prototype.parseWeird=function(d)
{
    return new Date(parseInt(/-?\d+/.exec(d)[0], 10));
};

var x = Date.parseWeird('/Date(-65424600000)/');
alert((x.getMonth()+1) + "/" + x.getDate() + "/" + x.getFullYear());

The express is looking for 0 or 1, ?, negative sign, followed by any number, + ,  of digits, \d.

A: Instead of fixing it on the client, fix it on the server
http://james.newtonking.com/archive/2009/02/20/good-date-times-with-json-net.aspx

JsonConverters
With no standard for dates in JSON, the number of possible different
  formats when interoping with other systems is endless. Fortunately
  Json.NET has a solution to deal with reading and writing custom dates:
  JsonConverters. A JsonConverter is used to override how a type is
  serialized.

public class LogEntry
{
  public string Details { get; set; }
  public DateTime LogDate { get; set; }
}

[Test]
public void WriteJsonDates()
{
  LogEntry entry = new LogEntry
  {
    LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
    Details = "Application started."
  };

  string defaultJson = JsonConvert.SerializeObject(entry);

  // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}

  string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());

  // {"Details":"Application started.","LogDate":new Date(1234656000000)}

  string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());

  // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

}

If not, does this work for you?
DEMO HERE
Date.parseWeird=Date.prototype.parseWeird=function(d) {
  // remove anything not a digit or - and convert to number
  return new Date(parseInt(d.replace(/[^\-\d]/g,""),10));
};

var d = "\/Date(-65424600000)\/"
var newDate = Date.parseWeird(d);
var mm = newDate.getMonth()+1;
if (mm<10) mm="0"+mm;
var dd = newDate.getDate();
if (dd<10) dd="0"+dd;
document.write(""+mm+"/"+dd+"/"+newDate.getFullYear())


text:
Q: How do I open the door southwest of Snowdin?
I've tried a variety of things, including checking the door with every possible combination of lit mushrooms, but none worked. The only thing that happened here was a random encounter with (IIRC) Glaze, who killed me very quickly. I never managed to get a rematch, however.

A: You must complete the game and dodge every name in the special thanks section of the credits
When you reach the end of the game, there will be one last bit of the game where you are given infinite health with which to try and dodge all of the names in the Special Thanks portion of the credits. If you successfully manage to dodge every name in the credits in a single run, you will be able to pass through the door in your screenshot.


text:
Q: cakephp 2.5.7 login->Auth always false even password is correct I was stuck in this problem for almost a week. Even going through all the solutions in the internet doesn't help me to solve my problem. So I decided to ask my problem here and hope I will get solution.
My problem is why i always get Auth FALSE even my password is correct? I manage to add a new user and it stores the encrypted password, but when I try to login using that username and `password, it displays "Invalid username or password, try again"
Here is my code.
Thank in advance

A: I had some troubles with this part of cake as well, here is the way that I ended up using which works for me
public function login() {
    if ($this->request->is('post')) {
        $options = array(
            'conditions' => array(
                'User.username' => $this->request->data['User']['username'],
                'User.password' => Security::hash($this->request->data['User']['password'], 'sha256', true)
            ),
            'fields' => array(
                'User.id',
                'User.username',
                'User.group_id',
                // other fields you need
            )
        );

        $userData = $this->User->find('first', $options);
        if (!empty($userData) && $this->Auth->login($userData['User'])) {
            $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Session->setFlash(__('Username, and/or password are incorrect'));
        }
    }
}

so, the bottom line is to manually check if the user with the given username and password exists, and then login them. Btw, pls pay attention that to login() function I am passing an array like this
array(
    'id' => 1,
    'email' => 'test@gmail.com',
    'group_id' => 2
);

and not
    array(
        'User' => array(
            'id' => 1,
            'email' => 'test@gmail.com',
            'group_id' => 2
        )
    );

also, you do not want to pass the password to the login function if you are using cake 2.x, from cake docs
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in

In 2.x $this->Auth->login($this->request->data) will log the user in
  with whatever data is posted, whereas in 1.3
  $this->Auth->login($this->data) would try to identify the user first
  and only log in when successful.

so, first of all no need to pass the password, but you should be careful to check the valid user password before using login because if as it mentioned above, cake will login the user with any data.
About the password hashing part, please be sure you are using the same hashing algorithm with exact same salt (if you use it and you should) that you used during registration.
edit:
try using this in the model's beforeSave
public function beforeSave($options = array()) {
    parent::beforeSave($options);

    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = Security::hash($this->data[$this->alias]['password'], 'sha256', true);
    }
}

For the last thing it is better practice to save a unique salt per user(salt should be saved in db along with user's password). In cake only one application side salt is being used for all passwords, and if the db and the app are compromised attacker can generate just one custom rainbow table for all passwords, but if the salt is unique for each user, then the bad guy should create custom rainbow table for each user separately, which is a lot more work/time/money.


text:
Q: display price from two tables without eliminate products I have this Query:
 select ItemName,FrgnName,OnHand,Price as Regular_Price from ITM1, OITM
 where exists
 (select null from OSCN
 where oitm.ItemCode=oscn.ItemCode
 and itm1.ItemCode=oscn.ItemCode
 and oscn.CardCode='test'
 and itm1.PriceList=2)

this query is to get all the products linked to a certain customer with regular price (7 products).
Now I want to add fourth table (sprecial_prices table) which has only 6 products with special price for this customer.
the problem is if i add the special_price table to the query my result will be 6 products and i want to display all customer's items with both prices even though one of them is 0.
Thank you

A: I think your query can be re-written in SQL92 syntax this way:
select
   i.ItemName,FrgnName,o.OnHand,i.Price
from
  ITM1 i
  inner join OITM o on i.ItemCode = o.ItemCode
  inner join OSCN os on o.ItemCode = os.ItemCode
where
  o.CardCode = 'test'
  and i.PriceList = 2

To add the 4th table you want to use a left join so that all records are shown even if there are no results in the 4th table:
select
   i.ItemName,FrgnName,o.OnHand,i.Price
from
  ITM1 i
  inner join OITM o on i.ItemCode = o.ItemCode
  inner join OSCN os on o.ItemCode = os.ItemCode
  left join special_price sp on o.ItemCode = sp.ItemCode  --or whatever column joins to special_price
where
  o.CardCode = 'test'
  and i.PriceList = 2


text:
Q: What do you call a text we append at the end of a work after it was published? Sometimes, news articles, scientific articles and other works add a small text to correct certain things that were said, but happened to be wrong, so how do you call this type of text we append like that after it was initially published? I am not sure if the definition depends on the content, which in this case are corrections.

A: If it's to correct errors, then it is an errata. Some would insist that you should only use that if there are multiple errors, and if there's just one error it would be erratum, but that comes from a bizarre insistence of maintaining the grammar of Latin words when used in English - and there is a long, long convention of use in English that the separately-published or added-after-printing item that corrects errors is called an errata.
If it's not just correcting errors, there are various options. Personally, I favour addendum.
Both terms come from Latin, obviously, but they are normal English words now.


text:
Q: Create a new div and move the existing div I have to create a new div and move the existing div into the newly created div.
This is my current div structure

some text1

some text2

some text3

some text4

I want to create a new div

 and move the input-wrapper div inside. So the new structure should look like this

some text1

some text2

some text3

some text4

I have used the following script
function create_structure(){
   $(".input-wrapper").append('

');
   $(".form-group").appendTo(".input-wrapper");
};
window.setTimeout( create_structure, 2000 ); // 2 seconds

I am not getting the desired structure.
Anything I am missing in the code?
Any suggestions would be appreciated. Thanks in advance

A: how about using wrap method in jquery?

for (let i = 0; i < $(".input-wrapper").length; i++) {
    $($(".input-wrapper")[i]).wrap("

");
}

some text1

some text2

some text3

some text4

A: Use the build-in .each in JQuery :

$(".input-wrapper").each(function(i) {
   $(this).wrap("

");
});

some text1

some text2

some text3

some text4

for your second Question about adding  you can achieve this by modifying my code to
$(".input-wrapper").each(function(i) {
   $(this).append("");
   $(this).wrap("

");
});


text:
Q: Rails dump and load only specific tables between environments I found a lot of documentation on how to dump the whole database and load it in a different environment but I don't want the whole database.
I need to dump and load only specific tables between environments.
For instance I need the results table from production in my testing environment but I don't want the users table.

A: Use yaml_db gem
rake db:data:dump_dir
   ->   Dump contents of database to curr_dir_name/tablename.extension (defaults to yaml)
remove the unnecessary table files from the dir and then
rake db:data:load_dir   ->   Load contents of db/data_dir into database


text:
Q: How to make an Android version for a web site I have a website and i need to make an Android version for it.
How to do with web langages (Not Java :s) ? i think it's possible with HTML5.
So what do i need to do ?
Thank you

A: Its very easy to develop a web apps for mobiles if you use something like
http://jquerymobile.com/ (uses Html5, JavaScript and CSS)
Or
http://jqtouch.com/ (uses HTML, JavaScript and CSS)
There are loads of others if you search, just the above two are the ones I am most familiar with and have found very easy to use.


text:
Q: Prove that a cyclic semigroup is either finite or isomorphic to $\langle \mathbb{N},+ \rangle$ A semigroup $G$ is cyclic if $G$ is generated by a single element.
I know that a finite cyclic group generated by $a$ is necessarily abelian, and can be written as $\{1, a, a^2, . . . , a^n−1\}$ where $a^n = 1$, or in additive notation, $\{0, a, 2a, . . . , (n − 1)a\}$, with $na = 0$. Thus a finite cyclic group with $n$ elements is isomorphic to the additive group $\mathbb{Z}_n$ of integers modulo $n$. If $G$ is an infinite cyclic group generated by $a$, then $G$ must be abelian and can be written as $\{1, a^±1, a^±2, . . . \}$, or in additive notation as $\{0,±a,±2a, . . . \}$. In this case, $G$ is isomorphic to the additive group $\mathbb{Z}$ of all integers.
Q: Prove that a cyclic semigroup is either finite or isomorphic to $\langle \mathbb{N},+ \rangle$.

A: In a semigroup, an element does not (necessarily) have an inverse, so it does not make sense to write $a^{-1}$. You have constructed an isomorphism from a semigroup ($G$) to a group ($\mathbb{Z}$) which is not possible unless $G$ is actually a group.
Now assume that $G$ is cyclic and infinite. Since it's cyclic, there is a $g \in G$ such that for each $h \in G$ there is $n \in \mathbb{N}$ such that $h = g^n$. Now define $\phi: \mathbb{N} \to G$ by
$$\phi(n) = g^n.$$
This is a homomorphism since $\phi(n+m) = g^{nm} = g^n g^m$, so to prove that $\mathbb{N} \cong G$ we need to show that $\phi$ is bijective. From $G$ being cyclic with generator $g$, we already know that it is surjective (given $h \in G$ we know that there is an $n \in \mathbb{N}$ such that $\phi(n) = g^n = h$).
To prove injectivity, assume for contradiction that there is $n,m \in \mathbb{N}$ with $n \neq m$ such that $phi(n) = \phi(m)$, ie. $g^n = g^m$. Now without loss of generality we may assume that $m >n$ and we let $m = n + k$ for some $k \in \mathbb{N}$. Then
$$g^n = g^{n+k} = g^n g^k.$$
Note that multiplying by $g^k$ on the left hand side gives us $g^n g^k = g^n$, and on the right hand side gives us $g^n g^k g^k = g^n g^{2k}$. Thus we can multiply with $g^k$ as many times as we want without changing the left hand side, so for any integer $q \geq 0$ we have
$$g^n = g^n g^{qk} = g^{n + qk}.$$
Now by integer division with residue we have for each $l \geq 0$ that there are $q \geq 0$ and $r = 0,1,\ldots,q-1$ such that $l = qk + r$, so
$$g^{n+l} = g^{n + qk + r} = g^{n+qk} g^r = g^r.$$
Now this proves that $\phi(n+l) \in \{g^0, g^1, \ldots, g^{q-1}\}$ for all $l \geq 0$, so the image of $\phi$ is finite. We have already proved that $\phi: \mathbb{N} \to G$ is surjective, so this must imply that $G$ is finite which is a contradiction. So $\phi$ is injective and hence an isomorphism.

A: Hint and observations The standard proof of cyclic group is either finite or isomorphic to $\mathbb{Z} $ will work fine.
You have to note that a "cyclic semigroup" (denoted $ S $) can't be uncountable,  just because there exists a generator $ g \in S$ together with the operation "power" ^ $: \mathbb{N} \to S \ \ n \mapsto g^n$  which generate all the elements. So they can't be more than countable.


text:
Q: Compare text in column A and J and delete matching cells Im trying to compare text in two columns.
If the text in column A exactly match any text in column B then delete the cells in both columns.
Any help is greatly appreciated.

A: here is something to get you started
Option Explicit
Sub Macro1()
    Columns("A:B").Select
    ActiveSheet.Range("$A$1:$B$16").RemoveDuplicates Columns:=Array(1, 2)
End Sub


text:
Q: React native Horizontal Picker Flatist I wanted to create a list like this
In which i want the user just scrolling the list and item which will be in center stays selected and  highlighted I also use  some packages but they don't perform well  so i wanted to make it from scratch.

A: You can develop it yourself or use the packages below
https://www.npmjs.com/package/react-native-list-slider/v/1.1.1
https://www.npmjs.com/package/react-native-swiper


text:
Q: How to browse data in MySQL database on Amazon EC2? I deployed my Rails app to Amazon EC2 server (Ubuntu), but I am thinking how to connect to MySQL database from terminal (SSL) and manually check data in database.
How to do that? I see in the database.yml file some credentials, but don't know how to connect/log in into MySQL on EC2 instance.
Thanks

A: There's no special magic involved here.  An EC2 server is just... a server.  This is not hosting like heroku or godaddy where your database is going to be hosted on a different db server.
Unless you explicitly setup a separate db server (which I don't think you did), you've got an entire virtual machine running Ubuntu, and the db server is most likely running on the same machine.
So you can ssh into the machine and just run the standard mysql client.  Docs here: http://dev.mysql.com/doc/refman/5.6/en/mysql.html.
If you want to use some gui software such as sequel pro mentioned in one of the comments, you'll need to open up the ports in the aws console.  Amazon closes all the ports by default.  Do this to open up the port:

*

*Open up the AWS control panel

*Go to 'Security Groups'

*Select the security group in the panel (you probably only have one).

*Click the 'Inbound' tab.

*Select Mysql from the dropdown list

*Save the rule

This will open up port 3306 and enable you to use an external tool to see the server.

A: If you just want to call some sql to the database just to verify small amount of data, you can try doing these:
sql_statement = 'SELECT * FROM users'
ActiveRecord::Base.connection.execute(sql_statement).to_a


text:
Q: Allow user to connect using SSH or SFTP but limit to home dir (Centos7) I'm configuring a web server which should have multiple domains & users.
I'm trying to limit users only to their home dir & allow them to connect with SSH or SFTP.
So far I followed some guides & managed to restrict the user to a specific directory & connect with SFTP, but when I try to connect using SSH I get:

Could not chdir to home directory /home/username: No such file or directory
  /bin/bash: No such file or directory

My end of /etc/ssh/sshd_config looks like this:
Subsystem sftp internal-sftp

Match Group sftp
    ChrootDirectory %h
    X11Forwarding no
    AllowTcpForwarding no
    ForceCommand internal-sftp

*I added the user 'username' to group 'sftp'.
*If I comment the "Match Group ..." Block & change "Subsystem sftp internal-sftp" back to "Subsystem sftp /usr/libexec/openssh/sftp-server" I can connect with SSH, but I have no folder restriction.
-- Any idea?

Sub question:
I also mounted the domain from the /var/www/ dir to the user home dir to make it accessible, is that how it's usually done on shared hosting?

A: You need to set up correct chrooted environment per each user you want to let in via SSH.
Each chrooted home dir would have to have its own minimal set of Unix executables and device files to be able to launch the shell etc. The command set would be limited to whichever commands you copy into user's "own root". This is the main trickiness of chrooted environments -- users will endlessly complain that a particular command is missing.
There's a bunch of manuals on how to set up chrooted SSH, this one looks sane: Chrooted SSH/SFTP Tutorial (Debian Lenny).
Cheers!


text:
Q: Getting this error messages when starting the development server using 'yarn start' after 'npx create-react-app on Ubuntu Starting the development server...

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/NormalModule.js:417:16)
    at handleParseError (/home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/NormalModule.js:471:10)
    at /home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/NormalModule.js:503:5
    at /home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/NormalModule.js:358:12
    at /home/akj/Desktop/Social-Media-App/client/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/home/akj/Desktop/Social-Media-App/client/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at iterateNormalLoaders (/home/akj/Desktop/Social-Media-App/client/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
/home/akj/Desktop/Social-Media-App/client/node_modules/react-scripts/scripts/start.js:19
  throw err;
  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/NormalModule.js:417:16)
    at /home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/NormalModule.js:452:10
    at /home/akj/Desktop/Social-Media-App/client/node_modules/webpack/lib/NormalModule.js:323:13
    at /home/akj/Desktop/Social-Media-App/client/node_modules/loader-runner/lib/LoaderRunner.js:367:11
    at /home/akj/Desktop/Social-Media-App/client/node_modules/loader-runner/lib/LoaderRunner.js:233:18
    at context.callback (/home/akj/Desktop/Social-Media-App/client/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at /home/akj/Desktop/Social-Media-App/client/node_modules/babel-loader/lib/index.js:59:103 {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.12.0
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I used npx create-react-app and installed few dependencies and then when I try to start the react development server. I keep geeting this error message in CLI and on browser tab


text:
Q: Extracting data from binary files with php I have to extract some data from a binary file. the data begin with a hex marker.
I have first to find this marker and then extract the x bytes after.
PHP is good for text file manipulation.
Someone have a good idea to do that with binary data ?
Thanks !

A: You should look at the unpack() and pack() functions.
Here are a sample that reads a entire file into a buffer and uses unpack() to get the values of the two first chars:
$fp = fopen("binary.txt", "r");
fseek($fp, 0, SEEK_END);
$fs = ftell($fp);
fseek($fp, 0, SEEK_SET);
$binary = fread($fp, $fs);
fclose($fp);
$unpacked = unpack("c2", $binary);

A: You don't need any special functions like pack or unpack etc...although pack may be useful for specifying the needle to search for.
php doesn't apply any character encoding to strings, it leaves them as is, so it's binary friendly by default.
$hexMarker = 0x70000000;// or whatever
$binaryData = file_get_contents($filename);
$x = 5;
$pos = strpos($binaryData, $hexMarker);
if ($pos !== false) {
    $start = $pos + strlen($hexMarker);
    echo substr($binaryData, $start, $x);
}

you may consider using fopen and fread in an iterative fashion if the size of the file is large, as file_get_contents would consume a lot of memory in that case. But that's a separate question anyway.


text:
Q: Linear Transformation of points Could you help me solve this: For projective coordinate system on the line $l$ are given points $A (2,1)$, $B (1,1)$, $C (0,1)$, $A_1 (0,1)$, $B_1 (1,5)$ and $C_1 (2,1 )$. Find a linear transformation where the points $A, B$ and $C$ go respectively at  $A_1$, $B_1$, and $C_1$.
I tryed to solve it but I dont know what to do.
Here is what I tryed:
\begin{equation}
ρ_1 * \begin{pmatrix}0 \\ 1 \\ \end{pmatrix} = \begin{pmatrix}m & n \\ p & q \\ \end{pmatrix}* \begin{pmatrix} 2 \\ 1 \\ \end{pmatrix}
\end{equation}
\begin{equation}
ρ_2 * \begin{pmatrix}1 \\ 5 \\ \end{pmatrix} = \begin{pmatrix}m & n \\ p & q \\ \end{pmatrix}* \begin{pmatrix} 1 \\ 1 \\ \end{pmatrix}
\end{equation}
\begin{equation}
ρ_3 * \begin{pmatrix}2 \\ 1 \\ \end{pmatrix} = \begin{pmatrix}m & n \\ p & q \\ \end{pmatrix}* \begin{pmatrix} 0 \\ 1 \\ \end{pmatrix}
\end{equation}
2m + n = 0
2p + q = $ρ_1$
m + n = $ρ_2$
p + q = 5*$ρ_2$
n = 2*$ρ_3$
q = $ρ_3$
Is that the right way ? I got some equations for m, n, p, q but I dont think they are right. What should I do now ?


text:
Q: Help solving an improper integral The assignment is to solve:
$$
\int_{0}^{\infty}f(x) dx
$$
where
$$f(x) = \frac{4}{(x+1)^2(x+3)} $$
.
I did partial fraction on the indefinite integral of $f(x)$ and got:
$$
f(x) = \frac{A}{x+1} + \frac{B}{(x+1)^2} + \frac{C}{x+3}
$$
$$
4=(A+C)x^3 + (5A+B+3C)x^2 + (7A+4B+3C)x + (3A + 3B + C)
$$
and put the last three functions inside a matrix:
$$
\begin{bmatrix}
5 & 1 & 3 & 0 \\
7 & 4 & 3 & 0 \\
3 & 3 & 1 & 4 \\
\end{bmatrix}
$$
gauss elimination:
\begin{bmatrix}
1 & 0 & 0 & -9 \\
0 & 1 & 0 & 6 \\
0 & 0 & 1 & 13 \\
\end{bmatrix}
Replace $A$, $B$ and $C$ with the result in $f(x)$:
$$
f(x) = \frac{-9}{x+1} + \frac{6}{(x+1)^2} + \frac{3}{x+3}
$$
Calculate the definite integral from 0 to $\infty$:
$$
\lim_{b \to \infty} \int_{0}^{b} f(x)dx = \lim_{b \to \infty} (-9 \log|b+1|- \frac{6}{b+1} + 13 \log|b+3| + 6 - 13\log(3))
$$
Separate into several limits:
$$
\lim_{b \to \infty}(-9 \log|b+1|- \frac{6}{b+1} + 13 \log|b+3|) + 6 - 13\log(3)
$$
L'Hopital:
$$
\lim_{b \to \infty}(\frac{9}{b+1} + \frac{6}{(b+1)^2} + \frac{13}{b+3}) + 6 - 13\log(3)
$$
All limits are zero, so we're just left with the constants:
$$
6 - 13\log(3)
$$
which is not the correct answer.

A: You found the partial fractions incorrectly
$$\frac4{(x+1)^2(x+3)}=\frac1{x+3}-\frac1{x+1}+\frac2{(x+1)^2}$$
So the integral becomes
$$\lim_{t\to\infty}\left(\ln{(t+3)}-\ln{(t+1)}-\frac2{t+1}-\ln{(3)}+2\right)=2-\ln{(3)}$$
Also, you cannot apply L'Hopitals rule unless you have an indeterminate form of
$$\frac00 \text{ or } \frac{\pm\infty}{\pm\infty}$$

A: Your mistake was that this equation
$$4=(A+C)x^3 + (5A+B+3C)x^2 + (7A+4B+3C)x + (3A + 3B + C)$$
was wrong. You start from
$$\frac4{(x+1)^2(x+3)}=\frac{A}{x+1}+\frac{B}{(x+1)^2}+\frac{C}{x+3}$$
Hence, assuming that $x\neq-1$ or $x\neq-3$, you have that
$$4=A(x+1)(x+3)+B(x+3)+C(x+1)^2\\
\iff (A+C)x^2+(4A+B+2C)x+3A+3B+C=4$$
Thus the system to be solved is
$$A+C=0,\quad 4A+B+2C=0,\quad 3A+3B+C=4$$
what gives the solutions $A=-1,\, B=2$ and $C=1$.


text:
Q: PAC Learning for OLS and noisy regression Hi guys I would like to get some references on PAC Learning for the following settings:

*

*PAC Learning type results for OLS. Most materials that tackle OLS are from a statistical point of view, i.e. assume $y=w^\top x+\epsilon$ where $\epsilon$ is Gaussian. In this regime, we can talk about parameter estimation error and in-sample/out-of-sample estimation error. In the PAC setting, there are many results that give uniform convergence for all linear functions $w$, but what about results specifically for OLS? For example, algorithmic stability approach looks at algorithms particularly, but I believe it only works for regularized OLS because it's strongly-convex.

*What if I want to get a PAC bound on linear regression where the data has noise? Say we observe $x+\epsilon$. Most results I found are for classification with Massart noise. What if I want to look at regression? The issue here is the training data and test data have different (but only slightly shifted) distribution.
Thanks for any suggestions!

A: Check out Rui Castro's class notes:
https://www.win.tue.nl/~rmcastro/2DI70/files/2DI70_Lecture_Notes.pdf
or Rob Nowak's lecture notes:
https://nowak.ece.wisc.edu/SLT09.html


text:
Q: nullPointerException with Retrofit library I'm using retrofit to access a API,but i can't get the data of this API
API Link
I was able to make my code work with this API: (This), but when I redo the code to use the previous one, I get the nullPointer error in the ActivityMain in the first foreach line that i use to displays the results.
Code:
MainActivity:

public class MainActivity extends AppCompatActivity {

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

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(UdacityService.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    UdacityService service = retrofit.create(UdacityService.class);
    Call<CharacterCatalog> requestCatalog = service.listCatalog();

    requestCatalog.enqueue(new Callback<CharacterCatalog>() {
        @Override
        public void onResponse(Call<CharacterCatalog> call, Response<CharacterCatalog> response) {
            if(!response.isSuccessful()){
                Log.e("ERRO", "Erro no servidor (" + response.code() + ")");
            }
            else {
                CharacterCatalog catalog = response.body();
                for (Result c : catalog.results){
                    Log.i("RESULT", String.format("id; %s, name: %s\n",c.id, c.name));

                    for (Origin o : c.origins){
                        Log.i("RESULT", String.format("nome; %s, url: %s\n",o.name, o.url));
                    }
                    Log.i("RESULT", "/////////////////////////////////////////");
                }
            }

        }

        @Override
        public void onFailure(Call<CharacterCatalog> call, Throwable t) {
            Log.e("ERRO", "Verifique a conexão com a internet (" + t.getMessage() + ")");
        }
    });
}}

Interface retofit:

public interface ApiService {
public static final  String BASE_URL = "https://rickandmortyapi.com/api/";

@GET("character")
Call<CharacterCatalog> listCatalog();
}

List results:
public class CharacterCatalog {
public List<Result> results;
}

Class Result
public class Result {
public String id;
public String name;
public String status;
public String species;
public String gender;

public List<Origin> origins;
}

Class Origin:
public class Result {
public String id;
public String name;
public String status;
public String species;
public String gender;

public List<Origin> origins;
}

Can someone help me with this error?

A: Please verify that you have tu use this format for you data class
@SerializedName("id")
private Integer id;
@SerializedName("name")
private String name;
@SerializedName("status")
private String status;
@SerializedName("species")
private String species;
@SerializedName("type")
private String type;
@SerializedName("gender")
private String gender;
@SerializedName("origin")
private Origin origin;
@SerializedName("location")
private Location location;
@SerializedName("image")
private String image;
@SerializedName("episode")
private List<String> episode = null;
@SerializedName("url")
private String url;
@SerializedName("created")
private String created;

Check this URL to create POJOS: http://www.jsonschema2pojo.org/
And please make sure you are actually connecting to the server, and do please verify you are getting a 200 answer from the server

A: Thanks for the help folks, but i solved the problem... in my class result i was using a list of origin but the API returns only one object ... i only removed the List type.


text:
Q: What are the best practices of custom application Wordpress development? I have a mid size project that I need to implement on Wordpress. I am fimiliar with MVC but don't know if I can use it in conjunction with Wordpress?
I intent to use wordpress loaded images, Menus and theme only from the wordpress every thing else particularly pages ( that are going to be linked with menus) isolated from wordpress. So whenever a page is requested WP controller delagates control to my controller. This is getting me headache !!!

A: You can merely use everything in conjunction with Wordpress, however, if you tightly couple with Wordpress you can't:

*

*Unit-Test your code.

*Integration-Test you code (in a practically successful way).

*Manage and automate staging of your code.

While you speak about MVC I assume you use it as a term for the high-level-design of a software. As long as you're able to decouple your project from Wordpress itself, the answer is yes.
If you're not able to do so, the answer is no. Wordpress itself does not offer anything that you could re-use easily to bring in MVC, it's own design is something totally different.
However as Wordpress is a software with a level of legacy introduced complexity, you need to think twice if it is actually worth to completely de-couple from Wordpress or if it's not just the technical debt it comes with that you need to legacy-align your code as well.
I highly suggest to use a decentralized version control system like git to create whatever you do. You can find a github mirror of Wordpress here: https://github.com/WordPress/WordPress
I'd say for small to mid-size projects this is the tool of choice. Keep design decisions low, as you're integrating with an existing platform so that you can't do anything greenfield anyway.


text:
Q: Counterexample to Uniform Convergence of Convex Functions It is stated here that if a sequence $f_n : [a,b] \to \mathbb{R}$ of convex continuous functions converges pointwise to a continuous function $f$, then the convergence is in fact uniform.
The answers given seem me to be correct proofs of the statement, however I was able to construct a counterexample pretty easily. Consider the functions
\begin{equation*}
 f_n = \begin{cases} -nx, & \text{if } 0 \leq x \leq \frac1n, \\
-2 + nx,  &\text{if } \frac1n \leq x \leq \frac2n,\\
0, &\text{otherwise}.
 \end{cases}
\end{equation*}
It's clear that $f_n$ is convex and continuous, and moreover converges pointwise to $f \equiv 0$. However, the convergence is not uniform, since $\sup |f_n| = 1$.
I'm not sure whether there's I overlooked something when constructing this counterexample or the original statement about uniform convergence of convex functions is incorrect.

A: Try plotting your functions, are they actually convex? (Hint: you need to specify the domain of your $f_n$)


text:
Q: how to return two values(1.Collection, 2.Single Boolean value) from a method in java with less expense? I have one Main class and VOCollection Class.
in main class there is a method called getStatus(), from this method only i am getting some status(true,false), if the status is true, i need to return a collection.
at present i have two ideas, but both are expensive.

*

*return map, it's expensive because setting Boolean for collection make confusion in code, and only one Boolean value is enough (but we are returning multiple).

*creating an instance variable in VOCollection class, and having getter & setter to get & set the Boolean value. this is also expensive. (creating a variable in another class).
give me less expensive solution.

A: There are a number of ways to do this:

*

*Return null to indicate that there is nothing present like java.util.Map.get()

*Create a custom class to return both parameters. (See other answer)

*Use a 1 element array for one of the return values.
boolean method(List[] result) {
result[0] = answer;
return flag;
}

*Use a library like Google Guava that has a Pair/Tuple class:
Pair method() {
return new Pair(flag, answer);
}

*Change your code so that it isn't necesssary, this is usually the right answer. See the exception comment or change the way things are passed around.

A: The desire to return either an object or a boolean is smelly. You see this kind of "flag" very often in code of starters who don't fully understand how to handle exceptional or "nothing" outcomes.
If the boolean represents an exception, just let it go or rethrow it in another exception. E.g. IllegalArgumentException, IllegalStateException, UnsupportedOperationException, etc depending on the functional requirement. You can put the calling code in a try-catch and handle it accordingly.
Or if the boolean represents a state of "nothing", just return null or an empty collection. You can handle it by testing the return value after calling the method.

A: You can introduce an class like this
class StatusResult
{
    public final bool status;
    public final VOCollection result;

    ...
}

and change the signature of getStatus() to
StatusResult getStatus()

A: I have come across the same situation in my past.
Both the solutions which you have mentioned are feasible as you said they may be expensive.
In fact, Java doesnot support the multiple return values from a method.
Solution Which I implemented was
I will try to parse/create/encode the string in such a way, after decoding i should be able to know what i need to do.
In your case, I would have choosen the following path
Create a string like returnValue, let that string start with either 0 or 1, if its 1 its true, else false.
and append the second return value to that.
For example you are trying to return like "returnValue1" and "true"
for true let us keep it 1 and for false lets keep it 2
when you do this, your return value will become "1returnValue1"

A: Simply return the collection when 'status is true'. Otherwise return null.
But:
Getting a collection with calling a method named "getStatus()" is not what I would expect.
"getStatus()" sounds getting some constant value indicating internal state. (like enum constant, int status code whatever)
In your scenario I would recommend having one method returning a boolean indicating that "i have something or not" and another method returning the collection - that what you have or null when not.
The boolean-method can then be easy implemented by calling the collection-method checking != null.
public boolean isXyz() {
    return getXyz() != null;
}

public Collection getXyz() {
    return yourCollection; //maybe null
}

A: The simplest approach may be to always return a VOCollection.  For the situation where there is no data you could return a collection with no data i.e. isEmpty() is true, or a collection which has a flag (but I prefer the first option).
To avoid creating an object each time, create a single instance of an immutable VOCollection with no entries. This is what you can return when you have no data.


text:
Q: Need help filtering the chat, the code doesn't work I write words from bad_list, but the bot doesn't delete them ,what did I do wrong ?
bad_list = ['toy', 'hack']
@client.event
async def on_message( message ):
    await client.process_commands( message )

    msg = message.content.lower()

    if msg in bad_list:
        await message.delete()
        await message.author.send(embed = discord.Embed(description = f'{message.author},такие слова не допустимы!',color = 0xff0000))

there are no errors in the command line
enter image description here

A: You compare the complete message, which is stored in msg to the words in your bad_list. This will only ever be true if a comment consists solely of one of the words in your list.
Instead, you should check, whether any of the bad words appear within the message. For this purpose, you would have to change the if-statement:
    is_bad = False
    for w in bad_list:
        if w in msg: is_bad=True
    if is_bad:
        await message.delete()
        await message.author.send(embed = discord.Embed(description = f'{message.author},такие слова не допустимы!',color = 0xff0000))

Using this modification, the program searches for any bad word within the message and switches to deleting as soon as a bad word is detected.
One problem remains, though. If the message contains a word that only contains these strings without being a bad word, it will also be deleted (e.g.: shackles, latoya). You'd better search for the words preceded by a blank. So, it will only remove hacking, hacked, hacker...
if ' '+w in msg: is_bad=True


text:
Q: Reading pdf from url with node.js using PDF.js I'm trying to extract the text of a pdf from the pdf's url. Following the example on the pdf.js website, i understand how to render a pdf on client-side, but I'm running into issues when I do this server-side.
I downloaded the package using  npm i pdfjs-dist
I tried the code below as a simple example to load the pdf:
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf';
var pdfjsLib = require("pdfjs-dist")
var loadingTask = pdfjsLib.getDocument(url);

loadingTask.promise.then(function (pdf) {
    console.log(pdf);
}).catch(function (error){
    console.log(error)
})

But when I run this, I get the following error:
  message: 'The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. `ReadableStream` and/or `Promise.allSettled`); please use an ES5-compatible build instead.',
  name: 'UnknownErrorException',
  details: 'Error: The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. `ReadableStream` and/or `Promise.allSettled`); please use an ES5-compatible build instead.'

Any ideas on how to go about doing this? All I'm trying to do is extract the text of a pdf from it's URL. And I'm trying to do this server side using nodejs. Appreciate any input!

A: You need to import the es5 build of pdf.js. The code below should work:
var pdfjsLib = require("pdfjs-dist/es5/build/pdf.js");
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf';
var loadingTask = pdfjsLib.getDocument(url);

loadingTask.promise.then(function (pdf) {
    console.log(pdf);
}).catch(function (error){
    console.log(error)
})

Also check out https://github.com/mozilla/pdf.js/blob/master/examples/node/getinfo.js for a working example with node.js

A: I had the same problem (The browser/environment lacks native support for critical functionality used by the PDF.js library (e.g. ReadableStream and/or Promise.allSettled); please use an ES5-compatible build instead.) but with Angular 8 so here I leave the solution in case someone needs it:
packaje.json configuration:

*

*Angular versión: 8.2.14

*pdfjs-dist: 2.4.456
component:
import * as pdfjs from 'pdfjs-dist/es5/build/pdf';
import { pdfjsworker } from 'pdfjs-dist/es5/build/pdf.worker.entry';

pdfjs.GlobalWorkerOptions.workerSrc = pdfjsworker;

A: I've also faced the same issue in latest version of pdfjs-dist (2.8.335) while using it in a node js project and as mentioned in other answers that we need to change path to fix this.
But in my case path - pdfjs-dist/es5/build/pdf didn't work.
In latest version it got changed to pdfjs-dist/legacy/build/pdf.js


text:
Q: Access Google Calendar From Web App Events Without Users Logging In I have a website in which I am hitting the Google Calendar API and successfully pulling the events from a specified calendar. I am just now realizing, however, that I was only able to see the events because I was signed into that Google account while on the webpage using Chrome browser. When I logged out of the account on Chrome I could no longer see the event data. I guess not just anyone is authorized.
Here's the question: Can any user, without logging in, view my Google Calendar's events on my webpage?
I know there's something called server accounts but it looks really heavy for what I'm trying to accomplish. I do not need to access any Google user information nor do I need to access any application data. I simply want to display information from my Google Calendar using the Google Calendar API. I don't even need to use the API, honestly. I am successfully pulling data from a public Google Sheets and figured the calendar would work better, but then ran into this problem.


text:
Q: passing js object to mvc action in non ajax manner I have working example of calling mvc action from javascript using jquery.
$.ajax({
            type: 'POST',
            traditional: true,
            contentType: 'application/json',
            url: '/Data/CreateMyData',
            data: JSON.stringify({ newData: myObj}),
            success: function () {
                alert("complete");
            }
        });

this is async call, I wonder how can call same url /Data/CreateMyData and pass myObj javascript object in tradiotional (non async) manner.

A: just an async: false will  make the ajax call to be run synchronously
More details here and here


text:
Q: SymPy: lambdify with 2-D inputs I'm computing a square matrix V, each element of which is an integral that I compute with sympy. I compute only one definite integral V_nm, the result of which is a numerical expression with symbolic indices m and n. Say V_nm looks like this:
>>> V_nm
sin(3*n)*cos(m)

Now I wish to make a 2-D numerical (not symbolic!) matrix out of V_nm using m and n as indices of the array. Say for a 2 x 2 matrix, the result for the given V_nm would be:
[[sin(3)cos(1) sin(3)cos(2)]
 [sin(6)cos(1) sin(6)cos(2)]]

i.e., n specifies the column and m specifies the rows. (Note: I start m and n at 1 and not 0, but that's no concern).
How do I achieve this?
I know I can use V_nm.subs([(n, ...), (m, ...)]) in a list comprehension followed by evalf() but that's the long route. I wish to achieve this using lambdify. I know how to use lambdify for 1-D arrays. Can you please tell me how to implement it for 2-D arrays?

A: There is sympy's FunctionMatrix which is intended for this kind of case. Note that it uses zero-based indexing:
In [1]: m, n, i, j = symbols('m, n, i, j')

In [2]: V_nm = FunctionMatrix(m, n, Lambda((i, j), 100*(i+1) + (j+1)))

In [3]: V_nm
Out[3]: [100⋅i + j + 101]

In [4]: V_nm.subs({m:2, n:3}).as_explicit()
Out[4]:
⎡101  102  103⎤
⎢             ⎥
⎣201  202  203⎦

In [5]: lambdify((m, n), V_nm)(2, 3)
Out[5]:
array([[101., 102., 103.],
       [201., 202., 203.]])

A: What you're asking doesn't look like a standard functionality. But in two steps it's possible. First lambdify the expression, and then create a function that generates the intended 2D array via numpy's broadcasting:
from sympy import sin, cos, lambdify
from sympy.abc import m, n
import numpy as np

V_mn = sin(3 * n) * cos(m)

V_mn_np = lambdify((m, n), V_mn)
# using list comprehension:
# V_mn_np2D = lambda m, n: np.array([[V_mn_np(i, j) for j in range(n)] for i in range(m)])
# using numpy's broadcasting (faster for large arrays):
V_mn_np2D = lambda m, n: V_mn_np(np.arange(m)[:, None], np.arange(n))

V_mn_np2D(2, 2)

To have the numbering start at 1 instead of 0, use np.arange(1, m+1) and np.arange(1, n+1).
As a test, a function such as 100 * m + n makes it easy to verify that the approach works as intended.
W_mn = 100 * m + n

W_mn_np = lambdify((m, n), W_mn)
W_mn_np2D = lambda m, n: W_mn_np(np.arange(1, m+1)[:, None], np.arange(1, n+1))

W_mn_np2D(2, 3)

Output:
array([[101, 102, 103],
       [201, 202, 203]])


text:
Q: Variable length array parameter size expression with side effects This question arose from a remark Eric Postpischil made in another thread.
I have a hard time understanding the use of variable length arrays (VLAs) as function parameters:

*

*The array size is not checked.

*The array size is not recoverable from the array because the standard type adjustment array -> pointer applies for VLAs as well, as the sizeof() calls below demonstrate; even though it would be perfectly possible to pass the whole array on the stack, just as VLAs are created on the stack when they are defined.

*The size must be passed as an additional parameter, as with pointers.

So why does the language permit to declare function with VLA parameters if they do not offer any advantage and are adjusted like any other array argument to a pointer? Why is the size expression evaluated if it is not used by the language (e.g. to check the size of the actual argument) and is not obtainable inside the function (one still has to pass an explicit variable for that)??
In order to make clearer what I'm baffled about consider the following program (live example here). All function declarations are apparently equivalent. But as Eric pointed out in the other thread, the parameter size expression in the function's declaration is evaluated at run time. The size expression is not ignored.
It is unclear to me what benefit that would have because the size and its evaluation has no effect (beyond possible side effects). In particular, to repeat myself, that information cannot be used by code inside the function. The most obvious change would have been to pass VLAs on the stack like structures. They are, after all, usually also on the stack on the caller side. But like with arrays of constant length the type is adjusted already at declaration time to a pointer — all declarations below are equivalent. Nonetheless the useless and discarded array size expression is evaluated.
#include <stdio.h>

// Nothing to see here.
extern void ptr(int *arr);

// Identical to the above.
extern void ptr(int arr[]);

// Still identical. Is 1 evaluated? Who knows ;-).
extern void ptr(int arr[1]);

// Is printf evaluated when called? Yes.
// But the array is still adjusted to a pointer.
void ptr(int arr[printf("Call-time evaluation of size parameter\n")]){}

// This would not compile, so the declarations above must be equivalent.
// extern void ptr(int **p);

int main()
{
    ptr(0);
    ptr(0);

    return 0;
}

A:
... possible to omit the size variable and ... the size which will be evaluated at run time, ...; but to which avail?

The top level size info is lost  , in the array argument is now a pointer parameter.  Yet with 2D VLA function arguments  which turn into pointer to a 1D array, code knows about that array dimension.
void g(size_t size, size_t size2, int arr[size][size2]) {
  printf("g: %zu\n", sizeof(arr));
  printf("g: %zu\n", sizeof(arr[0]));
}

int main(void) {
  int arr[10][7];
  g(10, 7, arr);
}

Output
g: 8   pointer size
g: 28  7 * int size

Alternatively, pass a pointer to the array.
void g2(size_t size, size_t size2, int (*arr)[size][size2]) {
  printf("g2: %zu\n", sizeof(arr));
  printf("g2: %zu\n", sizeof(*arr));
}

int main(void) {
  int arr[10][7];
  g2(10, 7, &arr);
}

Output
g2: 8    pointer size
g2: 280  10 * 7 * int size

A: C 2018 6.9.1 discusses function definitions and tells us in paragraph 10:

On entry to the function, the size expressions of each variably modified parameter are evaluated…

Per 6.7.6 3, a variably modified type is one that has a variable length array type in its declarators, possibly nested. (So int a[n] is variably modified since it is a variable-length array, and the fixed-length int (*a[3])[n] is also variably modified since nested within it is a variable-length array type.)
In the case of void foo(int n, int a[][n]), we see the n must be evaluated because the compiler needs the size to calculate addresses for expressions such as a[i][j]. However, for void foo(int n, int a[n]), this need does not exist, and it is not clear to me whether the text quoted above applies to the type of the parameter before adjustment (int a[n]) or after adjustment (int *a).
As I recall, when this first came to my attention a few years ago, I found both a compiler that did evaluate the expression and a compiler that did not, for a direct array parameter. Calling foo which had been defined with void foo(int a[printf("Hello, world.\n")]) {} would or would not print the string depending on the compiler. Currently, compiling with Apple LLVM 10.0.0 and clang-1000.11.45.5 on macOS 10.14.2 does print the string. (As mentioned above, for a nested array type, the expression must be evaluated, and all compilers I tried exhibited that. Unfortunately, I do not currently recall which compilers these were.)
It is not clear the array size is useful to the compiler. This aspect of the C standard might not have been completely worked out. There is a feature that adds some meaning to the size; if the size is declared with static:
void foo(int a[static SomeExpression]) { … }

then, per 6.7.6.3 7, a must point to at least SomeExpression elements. This means a must not be null, which the compiler can use to optimize some things. However, I do not have any examples of how the number itself can assist with optimization or other aspects of compilation.

A: I do not see any practical use of the VLAs as function parameter.
Only pointers to the the arrays make sense as make traversing the arrays easier and give correct size information
int foo(int (*p)[2])
{

    printf("sizeof int = %zu\n", sizeof(int));
    printf("p + 0:%p\n", (void *)p);
    printf("p + 1:%p\n", (void *)(p + 1));
}

void g(size_t size, size_t size2, int (*arr)[size][size2])
{
  printf("g: %zu\n", sizeof(*arr));
  printf("g: %zu\n", sizeof(*arr[0]));
}

int main()
{
    foo(0);
    g(5,5,0);

    return 0;
}

sizeof int = 4
p + 0:(nil)
p + 1:0x8
g: 100
g: 20


text:
Q: Why can't I cd to my home directory? I am user anupam and when grep anupam /etc/passwd:
anupam:x:1001:1001::/home/anupam:/bin/sh

I have found my home directory is /home/anupam but when I tried cd /home/anupam:
sh: 1: cd: can't cd to /home/anupam

What is the actual reason and problem behind this?


text:
Q: How to expand rows based on a particular row value in a dataframe? I have a dataframe as follows:
Col1     Col2     Col3     Col4
AB       2i       2j|2k    2y
CD       3j       3k|3p|3e 3x

So, for those rows which have pipeline separated values, I want to expand the rows as follows: (This should be the final dataframe)
Col1     Col2     Col3     Col4
AB       2i       2j       2y
AB       2i       2k       2y
CD       3j       3k       3x
CD       3j       3p       3x
CD       3j       3e       3x

So, the pipeline separated values have to be expanded into their own rows and the other field values have to be copied in. How to do that in pandas dataframe?

A: Use for pandas 0.25.0+ Series.str.split with DataFrame.assign for column filled of lists and then DataFrame.explode, last for default index DataFrame.reset_index with drop=True:
df = df.assign(Col3 = df['Col3'].str.split('|')).explode('Col3').reset_index(drop=True)
print (df)
  Col1 Col2 Col3 Col4
0   AB   2i   2j   2y
1   AB   2i   2k   2y
2   CD   3j   3k   3x
3   CD   3j   3p   3x
4   CD   3j   3e   3x

EDIT: If column name has space:
print (df)
  Col1 Col2    my col Col4
0   AB   2i     2j|2k   2y
1   CD   3j  3k|3p|3e   3x

df['my col'] = df['my col'].str.split('|')
df = df.explode('my col').reset_index(drop=True)
print (df)
  Col1 Col2 my col Col4
0   AB   2i     2j   2y
1   AB   2i     2k   2y
2   CD   3j     3k   3x
3   CD   3j     3p   3x
4   CD   3j     3e   3x

Solution for oldier versions:
c = df.columns
s = (df.pop('Col3')
       .str.split('|', expand=True)
       .stack()
       .reset_index(drop=True, level=1)
       .rename('Col3'))

df = df.join(s).reset_index(drop=True)[c]
print (df)
  Col1 Col2 Col3 Col4
0   AB   2i   2j   2y
1   AB   2i   2k   2y
2   CD   3j   3k   3x
3   CD   3j   3p   3x
4   CD   3j   3e   3x


text:
Q: Title of a fantasy trilogy where a group of children is transported to different worlds? In my early teens (in the late 90's) I borrowed a series of fantasy books from the public library. I remember getting annoyed when the next book in the series wasn't in, so this series has at least 3 books. The story line is still very vague to me: a group of children is transported to different worlds, I think 2 ended up in a world with highly advanced technology. Another, a boy, in a medieval type of world with swords and magic. His name was Rohan (or Rolan, Rogan, Rodan or something in that same vein that starts with an "R") and he ends up becoming The Knight of the Red Rose or has something to do with a red rose. And if I remember correctly, all these worlds are somehow connected to each other.
I originally read this series in Dutch but I'm pretty sure it's translated from English
Please help me out with finding this fantasy series. I never finished it and it has been bothering me lately.

A: I have alo been searching for this series and just found it. It's Diadem by John Peel.

A: Am not sure but there is a children's fantasy book called The Hounds of the Morrigan by Pat O'Shea, but I'm pretty sure it is a stand-alone, not a series.
And there is Secret Country trilogy which includes The Secret Country and The Whim of the Dragon and The Hidden Land by Pamela Dean.
Am not sure about these though..what do you think?


text:
Q: Shared Uploads (assets) across three models? Working on a music cataloging app.
I have three models (or levels) that make up each entry; Release, Product, Tracks.

*

*Releases can have many Products

*Products can have many Tracks
I want to upload files at the Release level that can be shared amongst its products.
For example, as user sets up a release I want them to be able to upload all related files (or assets - audio files and images) for that release. Then at the next stage, setting up a product, I want them to be able to pick and build the product from uploaded files....there is already a form for text input for the product.
Then for that product's tracklisting, again the user should be able to build this from files uploaded at the release level.
My reasoning for this approach is to avoid duplicating uploads across similar products. I could make them inherit everything from the release level but I must have the facility to alter tracklistings and images for things like limited editions. It would be great if by default they could inherit the release level files/assets and then have options to amend.
Anyway, looking for some guidance on how best to approach this?
Thanks!

A: Here is a comparison between Paperclip, Carrierwave and Dragonfly - CarrierWave vs. Paperclip vs. Dragonfly comparison
If you choose Carrierwave, this will help you - Multiple files upload with carrierwave and nested_form


text:
Q: How do Perl Cwd::cwd and Cwd::getcwd functions differ? The question
What is the difference between Cwd::cwd and Cwd::getcwd in Perl, generally, without regard to any specific platform? Why does Perl have both? What is the intended use, which one should I use in which scenarios? (Example use cases will be appreciated.) Does it matter? (Assuming I don't mix them.) Does choice of either one affect portability in any way? Which one is more commonly used in modules?
Even if I interpret the manual is saying that except for corner cases cwd is `pwd` and getcwd just calls getcwd from unistd.h, what is the actual difference? This works only on POSIX systems, anyway.
I can always read the implementation but that tells me nothing about the meaning of those functions. Implementation details may change, not so defined meaning. (Otherwise a breaking change occurs, which is serious business.)
What does the manual say
Quoting Perl's Cwd module manpage:

Each of these functions are called without arguments and return the absolute path of the current working directory.

*

*getcwd
my $cwd = getcwd();
Returns the current working directory.
Exposes the POSIX function getcwd(3) or re-implements it if it's not available.

*cwd
my $cwd = cwd();
The cwd() is the most natural form for the current architecture. For most systems it is identical to `pwd` (but without the trailing line terminator).

And in the Notes section:

*

*Actually, on Mac OS, the getcwd(), fastgetcwd() and fastcwd() functions are all aliases for the cwd() function, which, on Mac OS, calls `pwd`. Likewise, the abs_path() function is an alias for fast_abs_path()

OK, I know that on Mac OS1 there is no difference between getcwd() and cwd() as both actually boil down to `pwd`. But what on other platforms? (I'm especially interested in Debian Linux.)

1 Classic Mac OS, not OS X. $^O values are MacOS and darwin for Mac OS and OS X, respectively. Thanks, @tobyink and @ikegami.
And a little meta-question: How to avoid asking similar questions for other modules with very similar functions? Is there a universal way of discovering the difference, other than digging through the implementation? (Currently, I think that if the documentation is not clear about intended use and differences, I have to ask someone more experienced or read the implementation myself.)

A: Generally speaking
I think the idea is that cwd() always resolves to the external, OS-specific way of getting the current working directory. That is, running pwd on Linux, command /c cd on DOS, /usr/bin/fullpath -t in QNX, and so on — all examples are from actual Cwd.pm. The getcwd() is supposed to use the POSIX system call if it is available, and falls back to the cwd() if not.
Why we have both? In the current implementation I believe exporting just getcwd() would be enough for most of systems, but who knows why the logic of "if syscall is available, use it, else run cwd()" can fail on some system (e.g. on MorphOS in Perl 5.6.1).
On Linux
On Linux, cwd() will run `/bin/pwd` (will actually execute the binary and get its output), while getcwd() will issue getcwd(2) system call.
Actual effect inspected via strace
One can use strace(1) to see that in action:
Using cwd():
$ strace -f perl -MCwd -e 'cwd(); ' 2>&1 | grep execve
execve("/usr/bin/perl", ["perl", "-MCwd", "-e", "cwd(); "], [/* 27 vars */]) = 0
[pid 31276] execve("/bin/pwd", ["/bin/pwd"], [/* 27 vars */] <unfinished ...>
[pid 31276] <... execve resumed> )      = 0

Using getcwd():
$ strace -f perl -MCwd -e 'getcwd(); ' 2>&1 | grep execve
execve("/usr/bin/perl", ["perl", "-MCwd", "-e", "getcwd(); "], [/* 27 vars */]) = 0

Reading Cwd.pm source
You can take a look at the sources (Cwd.pm, e.g. in CPAN) and see that for Linux cwd() call is mapped to _backtick_pwd which, as the name suggests, calls the pwd in backticks.
Here is a snippet from Cwd.pm, with my comments:
unless ($METHOD_MAP{$^O}{cwd} or defined &cwd) {
    ...
    # some logic to find the pwd binary here, $found_pwd_cmd is set to 1 on Linux
    ...
    if( $os eq 'MacOS' || $found_pwd_cmd )
    {
        *cwd = \&_backtick_pwd;  # on Linux we actually go here
    }
    else {
        *cwd = \&getcwd;
    }
}

Performance benchmark
Finally, the difference between two is that cwd(), which calls another binary, must be slower. We can make some kind of a performance test:
$ time perl -MCwd -e 'for (1..10000) { cwd(); }'

real    0m7.177s
user    0m0.380s
sys     0m1.440s

Now compare it with the system call:
$ time perl -MCwd -e 'for (1..10000) { getcwd(); }'

real    0m0.018s
user    0m0.009s
sys     0m0.008s

Discussion, choice
But as you don't usually query the current working directory too often, both options will work — unless you cannot spawn any more processes for some reason related to ulimit, out of memory situation, etc.
Finally, as for selecting which one to use: for Linux, I would always use getcwd(). I suppose you will need to make your tests and select which function to use if you are going to write a portable piece of code that will run on some really strange platform (here, of course, Linux, OS X, and Windows are not in the list of strange platforms).


text:
Q: when A prticular column has been added in table I have one table employees where a new column named "new_emp" has been added few days back. I want to know when this column has been added. This column change may be or may not be the last alteration in the table.
I know we have all_objects table, where we can get last_ddl time. But that is not helpful for me. I want to know when exactly this "new_emp" column has been added in the employees table.
Is it possible to get the details?

A: Such a direct mechanism(Select from some table) does not exists in the Oracle database.
You can use

*

*DDL trigger to track the DDL changes on the table. (You can create the system level trigger for all DDL changes)

*Using the Oracle's Audit feature

Cheers!!


text:
Q: Function returning itself instead of str value I am using PyQt5 in conjunction with cfscrape and BeautifulSoup in an attempt to display the baby name of the day as a label. However, the function I am using to grab and return the baby name is returning itself instead of the name. Here is my code:
import sys
import cfscrape
from bs4 import BeautifulSoup
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication

class Scraper():
    def getNameOfTheDay():
        spider = cfscrape.CloudflareScraper()

        with spider:
            nameData = spider.get("https://www.babynames.com/").content

            soup = BeautifulSoup(nameData, "lxml")
            nameContainer = soup.find("div", {"class": "notd-name"})
            name = nameContainer.text
            return name

class NameScraper(QMainWindow):
    def __init__(self):
        super(NameScraper, self).__init__()
        self.setWindowTitle("Name Scraper")
        self.setFixedSize(644, 591)

        self.nameScraperUI()

        font = QtGui.QFont()
        font.setFamily("Segoe UI")
        font.setPointSize(10)

    def nameScraperUI(self):
        self.nameOfTheDayLbl = QtWidgets.QLabel(self)
        self.nameOfTheDayLbl.setGeometry(50, 50, 300, 15)
        self.nameOfTheDayLbl.setText("Name of The Day")

        self.scrapeBtn = QtWidgets.QPushButton(self)
        self.scrapeBtn.setGeometry(QtCore.QRect(230, 500, 181, 41))
        self.scrapeBtn.setText("Scrape Names")
        self.scrapeBtn.setObjectName("pushButton")
        self.scrapeBtn.clicked.connect(partial(self.updateLbl, self.nameOfTheDayLbl, Scraper.getNameOfTheDay))

    def updateLbl(self, label, text):
        label.setText(str(text))

def window():
    app = QtWidgets.QApplication(sys.argv)
    mainWin = NameScraper()
    mainWin.show()
    sys.exit(app.exec_())

window()

A: I don't see the need to use partial since you can do the following:
    self.scrapeBtn.setObjectName("pushButton")
    self.scrapeBtn.clicked.connect(self.updateLbl)

def updateLbl(self):
    self.nameOfTheDayLbl.setText(Scraper.getNameOfTheDay())

But if you still want to use partial then you should evaluate the function:
self.scrapeBtn.clicked.connect(partial(self.updateLbl, self.nameOfTheDayLbl, Scraper.getNameOfTheDay()))

But even so it would generate an error since it needs a parameter so you must use the @staticmethod decorator:
class Scraper():
    @staticmethod
    def getNameOfTheDay():
        # ...

With the previous change, a problem still arises: The GUI freezes because the scraper task is very time consuming, so to avoid that problem it must be implemented in another thread. Considering all of the above, the solution is:
import sys
import threading

import cfscrape

from bs4 import BeautifulSoup

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication

class Scraper:
    @staticmethod
    def getNameOfTheDay():
        spider = cfscrape.CloudflareScraper()

        with spider:
            nameData = spider.get("https://www.babynames.com/").content

            soup = BeautifulSoup(nameData, "lxml")
            nameContainer = soup.find("div", {"class": "notd-name"})
            name = nameContainer.text
            return name

class QScraper(QtCore.QObject):
    nameSignal = QtCore.pyqtSignal(str)

    def start(self):
        threading.Thread(target=self._execute, daemon=True).start()

    def _execute(self):
        self.nameSignal.emit(Scraper.getNameOfTheDay())

class NameScraper(QMainWindow):
    def __init__(self):
        super(NameScraper, self).__init__()
        self.setWindowTitle("Name Scraper")
        self.setFixedSize(644, 591)

        self.q_scraper = QScraper()

        self.nameScraperUI()

        self.q_scraper.nameSignal.connect(self.nameOfTheDayLbl.setText)

    def nameScraperUI(self):
        self.nameOfTheDayLbl = QtWidgets.QLabel(self)
        self.nameOfTheDayLbl.setGeometry(50, 50, 300, 15)
        self.nameOfTheDayLbl.setText("Name of The Day")

        self.scrapeBtn = QtWidgets.QPushButton(self)
        self.scrapeBtn.setGeometry(QtCore.QRect(230, 500, 181, 41))
        self.scrapeBtn.setText("Scrape Names")
        self.scrapeBtn.setObjectName("pushButton")
        self.scrapeBtn.clicked.connect(self.q_scraper.start)

def window():
    app = QtWidgets.QApplication(sys.argv)
    mainWin = NameScraper()
    mainWin.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    window()

Note: The @dahanraz solution is incorrect since getNameOfTheDay() is running when creating the GUI and not when pressing the button.


text:
Q: Auth-mode in floggy For auth-mode we may use the following code in RecordStore
rs = RecordStore.openRecordStore( "myrs", true,authMode, writable );

In Floggy how we may use the auth-mode?
Can anyone help me in using auth-mode in Floggy?
If possible please include the example code