text:
Q: Difference between Payflow Pro and Payflow Link What is the difference between PayPal Payflow Pro and PayPal Payflow link?
Currently, I am using checkout pages from PayPal manager in an iframe. Is this PayPal Payflow Pro or Payflow link?
If both are different then how can I connect my PayPal sandbox account in both scenarios?

A: Payflow Link is a type of Payflow account that can only use hosted pages.  It cannot do direct API or transparent redirect integrations.
Payflow Pro is a type of Payflow account that can make use of any integration type (including hosted pages just like Payflow Link)
The way you link either of these to Sandbox is to set the email identifier of a Sandbox PayPal Business account, within the Payflow Manager configuration settings of Set Up -> Hosted Checkout Pages.

Payflow is a rather old system, some would call it clunky. If you're happy with it and it's working good for you, well great -- but there are some modern alternatives you might consider:

*

*For a simple Debit or Credit Card processing along with PayPal payments, try PayPal Checkout

*For more customization, PayPal has Advanced Credit and Debit Card payments for some countries

*If you need a full gateway like Payflow Pro, switch to Braintree


text:
Q: iPhone grouped table view cell reuse My iPhone programs frequently contain grouped table views.  A typical use might be for settings.  The number of rows in these table views can run anywhere from roughly 2 to 20.  The cells typically don't have a lot of uniformity.
Should I be trying to reuse the cells?  If so, how much commonality do cells need to have to get a shared identifier?  For example, consider two cells with the same size, with one containing a label and a text input field; the other containing two labels and a slider.  Or is this just not worth the bother?
Thanks

A: If you release all your cells properly, you don't need to reuse cells because all your cells are different.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opening a file by passing in absolute file path I'm currently storing a file path for a file I would like to open and read in for my program. However when I put that path into File.OpenText it adds the path to the current directory to the file path and then I get this error:
DirectoryNotFoundException: Could not find a part of the path "/Users/km/Desktop/MP/file:/Users/km/Downloads/PT07E.obj".

The path I want is the one I am passing in, which is file:/Users/km/Downloads/PT07E.obj".
Is there a way to stop File.OpenText from adding to this path I am passing in originally?

A: You have to add a correct absolute path - that means, you forgot to define the drive (normally it's C). So your path would have to be (I'd use backslashes):
@"C:\Users\km\Downloads\PT07E.obj"

However it's a better idea not to use an absolute path for this. I'd use the specialFolder option of c#:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downlads", "PT07E.obj");

And it's always a good  idea to use Path.Combine, that uses the standard path splitter of the OS.

A: If you are operating with paths like file:/{absolute path} (which is actually an URI)
you may use System.Uri class.
As in this answer.
var uri = new Uri("file:/Users/km/Downloads/PT07E.obj");
using (var reader = File.OpenText(uri.AbsolutePath))
{
   ...
}


text:
Q: capitalized short form for month in Spark SQL date SELECT date_format(to_date('08/15/1990 12:03:00 PM', 'MM/dd/yyyy HH:mm:SS a'),"dd-MMM-yy")

is printing  15-Aug-1990. I need a capitalized short form for month in the date like 15-AUG-1990. How to do that using Spark SQL?

A: SELECT UPPER(date_format(to_date('08/15/1990 12:03:00 PM', 'MM/dd/yyyy HH:mm:SS a'),"dd-MMM-yy"))

May help others.


text:
Q: Form variables failing to print when using echo $variablename I'm creating a form that reads in the users name and email, then emails them a voucher via a PHP file, which looks like this:
<?php

  $deal = "offer or discount details";

  $to = "$email";
  $subject = "Tonights wheree voucher - $deal";
  $message = '

        Test email sent to <?php echo $email; ?>.

  ';

  $headers = "From: wheree <no-reply@wheree.co.uk>" . "\r\n" .
             "Content-type: text/html" . "\r\n";

  mail($to, $subject, $message, $headers);

?>

The form:
<form class="cmxform" id="details-form" method="get" action="test.php">
                 <fieldset>

                         <input id="name" name="name" title="Please enter your full name. " size="18" class="tagcheck" minlength="5" maxlength="60" value="Name" onfocus="if(this.value==this.defaultValue){this.value=''};" onblur="if(this.value==''){this.value=this.defaultValue};" />

                         <input id="email" name="email" size="18" title="Please enter a valid email address. " class="required email" value="Email" onfocus="if(this.value==this.defaultValue){this.value=''};" onblur="if(this.value==''){this.value=this.defaultValue};" />

                       <input id="accept-tick" type="checkbox" name="vehicle" class="required" title="You must accept our Terms & Conditions. " /> I accept the voucher usage Terms & Conditions.

                         <input class="submit" type="submit" value="Continue"/>

                 </fieldset>
</form>

This works fine, but doesn't echo the variable $email in the received email? I've also tried using $_GET["email"], but again to no success.
Thanks in advance for your help.

A: You are trying to place an echo statement inside a single quoted string.  Concatenate it in:
  $message = '

        Test email sent to ' . $email . '.

  ';

Or better yet, switch to a double-quoted string for $message, in which $email can be interpolated.
  $message = "

        Test email sent to $email.

  ";

See the PHP manual on strings for more information on variable interpolation and the difference between single and double-quoting.
A third option if you have lots of variables and multiple lines is the HEREDOC syntax, which avoids quoting entirely.
  $message =<<<MESSAGE

        Test email sent to $email.

MESSAGE;
// Note that the MESSAGE; above MUST be at the start of its own line, with no indentation

A: You have $echo inside of single-quotes. Variables are not expanded in single-quotes in PHP. Try putting it in double-quotes.  Or, as also suggested, if you want to use single quotes, concatenate it in.
$foo = "HELLO";
echo 'Foo: $foo';       // Prints 'Foo: $foo'
echo 'Foo: ' . $foo;    // Prints 'Foo: HELLO'
echo "Foo: $foo";       // Prints 'Foo: HELLO'

A: Try this:
<?php

  $deal = "offer or discount details";
  $to = $_GET['email'];
  $subject = "Tonights wheree voucher - $deal";
  $message = '

        Test email sent to '.$to.'.

  ';

  $headers = "From: wheree <no-reply@wheree.co.uk>" . "\r\n" .
             "Content-type: text/html" . "\r\n";

  mail($to, $subject, $message, $headers);

?>


text:
Q: RDP copy paste working unidirectionally I have a windows 10 PC (as the client) through which I RDP to Windows Server 2012 R2. I can copy paste files from the Server to the client, but cannot do so from the client to the Server.
Is there something that I am missing to enable this ?
(As a side note, on some other thread, I read enabling and disabling rdpclip.exe, should help, but that does not work. I cannot see rdpclip.exe listed in the processes tab in task manager).
Additionally, there are other users who have the same rights as me, are successfully able to perform copy paste operation bidirectionally.


text:
Q: PC BSD Warden network interface The documentation for PC BSD's Warden mentions that the configuration of the right network interface is crucial.
However, it doesn't say what the "right" interface is. What interface can I use there? The existing physical NIC one? Should I create a virtual one and use that?
The aim is to have network access in the jails, i.e. be able to access the internet as well as access services running within the jail from the internet.


text:
Q: Android Opengl loading new bitmap object in game cycle, is it a good idea? I am new to opengl i have just learnt to load bitmap using VBO technique. i am
(1)Whether i should create new bitmap object in each cycle of game loop
or
(2)i should create all the bitmap object once at the starting of game and use them through-out the game?
i have been using the 2nd option for canvas technique because loading lot of bitmaps is a bulky task so i don't include in the cylce. But opengl works in different way so i need suggestion on that.

A: Definitely do not load stuff at each game cycle, if you need to change data from a vbo, do that only exacly when you need using glBufferSubData. Also hint opengl about the nature of the data using GL_DYNAMIC_DRAW.


text:
Q: Hibernate, Jetty, H2 and Maven java.lang.NoSuchMethodError: 'javax.persistence.Index[] javax.persistence.Table.indexes()' Im having trouble while trying to connect to server on localhost:
java.lang.NoSuchMethodError: 'javax.persistence.Index[] javax.persistence.Table.indexes()'
Does anyone know what may be the cause of this output?
I was trying to change the persistence version and yet it didnt help any bit.
Below my config files:
Pom.xml
<!--suppress ALL -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.github.Dev</groupId>
    <artifactId>Hello</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>Hello World</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>11</java.version>
        <junit.version>4.12</junit.version>
        <slf4j.version>1.7.25</slf4j.version>

    </properties>

    <dependencies>
        <!--Test-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!--Logger-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!--Servlety-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!--Jetty-->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.22.v20191022</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-annotations</artifactId>
            <version>9.4.22.v20191022</version>
        </dependency>

        <!--DB-->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.200</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.9.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>

    <build>

        <plugins>
            <!--Compiler-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.flywaydb</groupId>
                <artifactId>flyway-maven-plugin</artifactId>
                <version>6.0.8</version>
                <configuration>
                    <url>jdbc:h2:file:./db</url>
                    <user>sa</user>
                </configuration>
            </plugin>

        </plugins>

    </build>

</project>

///////////////////////////Hibernate confi<?xml version='1.0' encoding='utf-8'?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:file:C:\Users\putek\IdeaProjects\_1\db</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"/>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">validate</property>

        <!-- Names the annotated entity class -->
        <mapping class="io.github.Dev.Lang"/>

    </session-factory>

</hibernate-configuration>
//////////////////////////////////////and my HibernateUtil

public class HibernateUtil {
    private static SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().
                configure("hibernate.cfg.xml").build();

        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().
                build();

        SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();

        SessionFactory sessionFactory = sessionFactoryBuilder.build();

        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = buildSessionFactory();
        }
        return sessionFactory;
    }
    static void close() {
        if ( sessionFactory != null )
        {
            sessionFactory.close();
        }
    }
}


text:
Q: How to show FileSystem.DeleteFile dialog as top most or set the parent/owner? When I call the following line, the dialog will show behind any floating dialogs, so I need to be able to set it to top most, or at least set the owner:
FileSystem.DeleteFile(someString, UIOption.AllDialogs, RecycleOption.SendToRecycleBin);

Unfortunately, I haven't found anything online that suggests this is doable. I understand I can create my own window and call into the API directly, but first I wanted to know if there was a way for all FileSystem dialogs to show topmost.

A: No answer, so I just set the messagebox parent to the form that's calling Show and just made API calls to recycle the deleted file:
            string message = string.Format("Are you sure you want to move '{0}' to the recycling bin?", Path.GetFileNameWithoutExtension(path));
            var result = MessageBox.Show(this, message, @"Move To Recycling Bin?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                Send(path, FileOperationFlags.FOF_NOCONFIRMATION | FileOperationFlags.FOF_NOERRORUI | FileOperationFlags.FOF_SILENT);
            }

Where the method "send" is part of a wrapper class exposed here


text:
Q: Why does diffraction happen in cases like these? Diffraction, at least as its commonly explained, happens when light crosses an obstacle "of size in the same order as its wavelength". For example, a small slit. However, in one of my labs, we used ~0,2 mm slits; while using light in the order of 650 nm. That's a difference of 3 orders in magnitude; yet diffraction still happened as expected.
Is the simplistic definition of diffraction wrong? Or is the margin larger than the same order of magnitude?

A: Obstacles of the  same order of magnitude as the wavelength give the biggest diffraction effects, but they shouldn't, in my opinion, enter into the definition of diffraction.
Anything that cuts off part of a wavefront causes diffraction. For example, the ability of an optical telescope to resolve apart two stars of small angular separation is ultimately decided by the diameter of the objective mirror or lens, and the spread of the central maximum of its diffraction pattern. And here we may have 5 or even 6 orders of magnitude difference between the wavelength and the linear dimensions of the aperture!

A: You don't need a slit for diffraction. Photons will diffract at a single edge.


text:
Q: How many breaks does it take to divide a chocolate completely? CodeWars challenges again. Today I have a problem with this one:
"Your task is to split the chocolate bar of given dimension n x m into small squares. Each square is of size 1x1 and unbreakable. Implement a function that will return a minimum number of breaks needed.
For example, if you are given a chocolate bar of size 2 x 1 you can split it to single squares in just one break, but for size 3 x 1 you must do two breaks.
If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer."
For some reason, the output is constantly 0 no matter what sides of the chocolate bar I provide.
What I've already tried:
object breakChocolate {

    var result = 0

    def breakChocolate(n: Int, m: Int) = {

        var t = n*m
        var i =0
        def breaking(y:Int): Unit ={
            if (t ==0 || t ==1)
                result = i
            else {
                breaking(t%2)
                i +=1
            }
        }
        result
    }
}

Here are the tests:

Test Results:
   TestCases
   breakChocolate(5, 5) should return 24
  Test Failed
0 was not equal to 24
   Stack Trace
  Completed in 38ms
   breakChocolate(7, 4) should return 27
  Test Failed
0 was not equal to 27
   Stack Trace
  Completed in 1ms
  Completed in 76ms

A: To solve this problem you don't need recursion at all. Consider the special case of chocolate plate: (1 x n). To divide this plate completely you need (n-1) breaks. Now you have plate m x n. To divide it into m pieces of form (1 x n) you need (m-1) breaks. So the total number of breaks is
(m-1) + m*(n-1) ~
m - 1 + m*n - m ~
m*n - 1

A: If I'm reading the Scala correctly, you've got the basic algorithm wrong.
This is actually a very simply problem, something similar to the old puzzle: if you have 55 teams playing in a single-elimination tournament, obviously some of them have to get byes in the first round, so there won't be a perfect even bracket.  So how many total games will be played?
The answer: 54.  Regardless of how the bracket is made, it's a single-elimination tourney.  Every game reduces the number of remaining teams by one.  So to get 55 participants down to one winner, 54 games will have to be played.
There is a similar argument to be made for your chocolate bar.  At some point, you have p pieces of chocolate in front of you.  Whichever one you select to break, you have taken 1 from the pile and put back 2, which means that the pile now has p + 1 pieces.  So for every split you add one piece to the pile.  This should lead directly to an answer...
...which may actually be wrong because of the need to return 0 in some cases, but it should be easy to special-case that.

A: You get 0 because you are not running breaking.
If you want to use recursion, one option could be to use a tail recursive function.
First decrement a checking it is greater than 1 to get the number of "horizontal" breaks to get the slices. Add 1 to the accumulator while looping.
Then decrement b checking it is greater than 1 to get the number of "vertical" breaks. This time add the starting "horizonal" value because that is the number of times you actually have to break the slices.
object breakChocolate {
  def breakChocolate(n: Int, m: Int): Int = {
    def breaking(a: Int, b: Int, acc: Int = 0): Int = {
      if (a > 1) breaking(a - 1, b, acc + 1)
      else if (b > 1) breaking(a, b - 1, acc + n)
      else acc
    }
    breaking(n, m)
  }
}

Scala demo

A: You can use this code instead:
  function breakChocolate(n,m) {
   if(n > 0 && m > 0) {
      return n * m - 1;
  } else {
    return 0;
  }
  }


text:
Q: CSS - transform divs pushing other divs around I'm trying to do a thumbnail page with a hover transition that zooms and displays a description. EDIT: I do not want to use jquery.
Problem 1. The hovered div pushes the neighbor div out of alignment. All the thumbs should stay in nice neat rows.
Problem 2. The hovered div pushes the bottom of the container down.

.container {
  margin-top: 75px;
  text-align: center;
  border: 2px solid black;
  padding: 5px;
}

.tn-wrapper {
  display: inline-block;
  position: relative;
  border: 0;
  margin: 5px;
  height: 150px;
  overflow: hidden;
  transition: all 200ms ease-in;
  transform: scale(1);
}

.tn-wrapper:hover {
  z-index: 1;
  transition: all 200ms ease-in;
  transform: scale(1.5);
  height: 300px;
}

.thumb-box {
  background: lightgray;
  height: 150px;
  width: 150px;
}

.descr-box {
  background: gray;
  height: 150px;
  width: 150px;
}

      Thumb

      Description

      Thumb

      Description

A: You can update your code like below. You fix the alignment of the inline-block elements (not mandatory but to make sure they will stay at the top) and you adjust the height of the description instead of the parent element.

.container {
  margin-top: 75px;
  text-align: center;
  border: 2px solid black;
  padding: 5px;
}

.tn-wrapper {
  display: inline-block;
  position: relative;
  border: 0;
  margin: 5px;
  height: 150px;
  transition: all 200ms ease-in;
  transform: scale(1);
  vertical-align:top; /* added */
}

.tn-wrapper:hover {
  z-index: 1;
  transition: all 200ms ease-in;
  transform: scale(1.5);
}

.thumb-box {
  background: lightgray;
  height: 150px;
  width: 150px;
}

.descr-box {
  background: gray;
  height: 0;
  width: 150px;
  overflow:hidden;
  transition: all 200ms ease-in;
}
.tn-wrapper:hover  .descr-box{
  height: 150px;

}

      Thumb

      Description

      Thumb

      Description

A: I'm not sure if this is the desired look you're trying to achieve but check out this example
I've added a flexbox to your container, changed your transform-origin and utilized the appropriate margins to keep your spacing.
.container {
 margin-top: 75px;
 text-align: center;
 border: 2px solid black;
 padding: 5px;
 display:flex;
 justify-content:center;
}

.tn-wrapper {
 display: inline-block;
 position: relative;
 border: 0;
 margin: 5px;
 height: 150px;
 transition: all 200ms ease-in;
 transform: scale(1);
 transform-origin:top;
 }

.tn-wrapper:hover {
  z-index: 1;
  transition: all 200ms ease-in;
  transform-origin:top;
  transform: scale(1.5);
  margin:5px 43px 305px 43px;
  }


text:
Q: Maybe I wrote a virus by mistake? When I run below code it works until 3 iterations of simple game but after the 3rd iteration CPU usage shoots to 90% and instantly crashes. Even console is terminated but below programs exe is seen in windows task list. I have to manually delete it for windows CPU to return to 3% levels.
Do you know what causes this? (I use Dev-C++ on windows 7 64 bit machine)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void game(void);
int main(void) {
    srand(time(NULL));
    game();
    return 0;
}
void game(void) {
    int choice = 1;
    while (choice != 0) {
        int number1, number2, resultStudent, result;
        number1 = 1 + rand() % 9;
        number2 = 1 + rand() % 9;
        result = number1 * number2;
        printf("How much is %d times %d ?", number1, number2);
        scanf("%d", & resultStudent);
        while (resultStudent != result) {
            printf("No. Please try again.");
            scanf("%d", &resultStudent);
        }
        printf("Very Good\n");
        printf("Do you wanna play again?(0 for Exit):  ");
        scanf(" %d", &choice);
        printf("Hmm you wanna play again...\n");
    }
    printf("Program is terminated.");
}


text:
Q: Javascript - map object members to return new flattened object Is there a simpler way to achieve the code below? Answer using lodash will be also accepted.
var obj = {
    dataTable: {
      column1: ["1"],
      column2: ["2"],
      column3: ["3"]
    },
    dataTable2: {
      column4: ["4"],
      column5: ["5"],
      column6: ["6"]
    }
}

var result = {};
var keys = Object.keys(obj);

keys.forEach(function(key) {
  var fields = Object.keys(obj[key]);
  fields.forEach(function(field) {
    result[field] = obj[key][field][0];
  });
});

console.log(result)
---> {column1: "1", column2: "2", column3: "3", column4: "4", column5: "5", column6: "6"}

A: You could do this with two for...in loops

var obj = {
  dataTable: {
    column1: ["1"],
    column2: ["2"],
    column3: ["3"]
  },
  dataTable2: {
    column4: ["4"],
    column5: ["5"],
    column6: ["6"]
  }
}, result = {}

for (p in obj) {
  for (a in obj[p]) {
    result[a] = obj[p][a].join('');
  }
}

console.log(result);

A: You can use forOwn function (https://lodash.com/docs#forOwn)
 var result = {};
    _.forOwn(object, function(value, key){
      result[key] = value[0];
    })

for 2-level nesting you could use that method twice:
var result = {};
_.forOwn(obj, function(value1, key){
  _.forOwn(value1, function(value2, key){
    result[key] = value2[0];
  })
})

A: You can use recursion:
myFn= (u,o,k)=> {
    if (o.map == [].map) u[k] = o[0];
    else for (k in o) myFn(o[k],k)
}

The above function will search ALL nested levels, and will populate your object accordingly.
To use, simple do this:
var output = {};
myFn(output, obj);

console.log(output);
// {column1: "1", column2: "2", column3: "3", column4: "4", column5: "5", column6: "6"}

A: The kind of tasks where ES6 really shines.
const res = Object.assign(...Object.keys(obj).map(x => obj[x]))
Object.keys(res).forEach(x => res[x] = res[x][0])

A: Here is a lodash solution that uses reduce() to merge() all datatable objects and then use mapValues() to set each of the column values by using head().
DEMO
var result = _.chain(obj)
  .reduce(_.merge) // merge all values
  .mapValues(_.head) // set the first item of the array as the value
  .value();


text:
Q: How to make babel compile null coalescing operator? A dependency of mine uses the null coalescing operator. Babel can't handle it. Is there any way to make Babel work here?
babel.config.js
module.exports = {
    presets: ['@babel/preset-env', '@babel/preset-react'],
    plugins: [
        '@babel/transform-runtime',
        '@babel/plugin-proposal-nullish-coalescing-operator'
    ],
};

Compile error:
./node_modules/test/dist/test.js 26:10
Module parse failed: Unexpected token (26:10)
File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| export class Test {
|   constructor() {
>     null ?? 0;
|   }
|


text:
Q: Symfony form values to array How can I get form values in an array instead of doing

array('field1'=>$this->getValue('field1'), 'field2'=>$this->getValue('field2')...)

A: You should try
$result = $this->getValues();

A: You can use $yourform->getValues() OR forms can be used as arrays. Read more here more with symfony under the "A Form is an Array" section.


text:
Q: How do I get JSON response from a route? I have the following route:
@api_blueprint.route("/cars", methods=["GET"])
@jwt_required()
def get_inventory():
    with session_scope():
        cars = dbu.list_cars()
        return jsonify(CarDetails(many=True).dump(cars))

I have to get the JSON response in a GET method which is a list of cars and insert into my html page.
I'm also not sure whether the code after the comment is true, it was one of my attempts to do something.
let xhr = new XMLHttpRequest();
    let method = "GET";
    const url = "http://127.0.0.1:5000/cars";
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
            /*get here JSON response from a route somehow*/
            document.getElementsByClassName("car_name").innerHTML = info.info[1]
            document.getElementsByClassName("car_price").innerHTML = info.info[2]
        }
        else if (xhr.readyState === 4 && xhr.status !== 200){
            alert(JSON.parse(xhr.responseText).message);
            window.location.reload();
        }
    };
    xhr.send(null);
}

The response is following:
[
    {
        "carId": 1,
        "name": "Chevrolet",
        "price": 3547.14
    },
    {
        "carId": 2,
        "name": "Lotus",
        "price": 4558.47
    },
    {
        "carId": 3,
        "name": "Chevrolet",
        "price": 4385.96
    }
]

A: When using XMLHttpRequest the response body can be found in the responseText property of the XMLHttpRequest instance. You've misplaced the position of where you read the response.
let xhr = new XMLHttpRequest();
let method = "GET";
const url = "http://127.0.0.1:5000/cars";

xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      const data = JSON.parse(xhr.responseText);
      console.log(data);

      // getElementsByClassName returns an array of elements.
      // querySelector returns a single element based on a CSS selector.
      document.querySelector(".car_name").innerHTML = data.info[1]
      document.querySelector(".car_price").innerHTML = data.info[2]
    } else {
      // statusText shows the status message of the request.
      alert(xhr.statusText);
      window.location.reload();
    }
  }
};
xhr.send(null);

Sidenote. Nowadays we have the Fetch API, which is the modern equivalent of the XMLHttpRequest interface. Though it is useful to know how XMLHttpRequest works, I'd recommend learning fetch as well.
The example below is the fetch equivalent of the code above.
let method = "GET";
const url = "http://127.0.0.1:5000/cars";

fetch(url, {
  method,
  headers: {
    "Content-Type": "application/json"
  }
}).then(response => {
  if (!response.ok) {
    throw new Error(`Fetching JSON went wrong - ${response.statusText}`);
  }

  return response.json();
}).then(data => {
  console.log(data);

  document.querySelector(".car_name").innerHTML = data.info[1]
  document.querySelector(".car_price").innerHTML = data.info[2]
}).catch(error => {
  alert(error);
  window.location.reload();
});


text:
Q: Operator '<' cannot be applied to types 'number' and 'Promise' with an Excel Add-In I am making an Excel add-in and I want to convert the data of a spreadsheet in Excel into a 2D array in Javascript but I can't get data to convert and I have been unable to figure out how to fix it, how do I fix the promise so that the function returns a number. The issue also exists for the getData function.
This is on the taskpane.js for the Excel add-in. I have tried .then(), await before the variable, and let, but I couldn't get it to work.
import { get } from "http";

/*
 * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
 * See LICENSE in the project root for license information.
 */

import { get } from "http";

/*
 * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
 * See LICENSE in the project root for license information.
 */

Office.onReady(info => {
  // Determine if the user's version of Office supports all the Office.js APIs that are used in the tutorial.
  if (!Office.context.requirements.isSetSupported('ExcelApi', '1.7')) {
    console.log('Sorry. The tutorial add-in uses Excel.js APIs that are not available in your version of Office.');
  }

  // Assign event handlers and other initialization logic.
  document.getElementById("run").onclick = run;
  if (info.host === Office.HostType.Excel) {
    document.getElementById("sideload-msg").style.display = "none";
    document.getElementById("app-body").style.display = "flex";
  }
});

function Create2DArray(rows) {
  var arr = [];

  for (var i = 0; i < rows; i++) {
    arr[i] = [];
  }

  return arr;
}

function sortedData() {
  var rows = getRowCount();
  var arrImport = getData();
  var arrExport = Create2DArray(rows);
  for (var r = 0; r < rows; r++) {
    arrExport[r][0] = arrImport[r][1];//money
    arrExport[r][1] = arrImport[r][5];//Company
    arrExport[r][2] = arrImport[r][0];//date
  }
  return arrExport;
}

async function getRowCount() {
  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();
    var rowCount = 0;

    for (var i = 0; i >= 0; i++) {
      var cell = sheet.getCell(i, 0);
      cell.load("address, values");
      await context.sync();
      if (cell.values[0][0] == "") {
        break;
      }
      else {
        rowCount++;
      }
    }
    await context.sync();
    return rowCount;
  });
}

async function getData() {
  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();
    //let rowCount = await getRowCount();
    var rowCount = getRowCount();
    var arrExport = Create2DArray(rowCount);

    for (var r = 0; r < rowCount; r++) {
      for (var c = 0; c < 5; c++) {
        var cell = sheet.getCell(r, c);
        cell.load("address, values");
        await context.sync();
        arrExport[r][c] = cell.values[0][0];
      }
    }
    await context.sync();
    return arrExport;
  })
}

async function run() {
  await Excel.run(async (context) => {
      var currentWorksheet = context.workbook.worksheets.getActiveWorksheet();
      rows = getRowCount();
  })
  .catch(function (error) {
      console.log("Error: " + error);
      if (error instanceof OfficeExtension.Error) {
          console.log("Debug info: " + JSON.stringify(error.debugInfo));
      }
  });
}

I want to get the number of rows from my excel spreadsheet that are used but I can't get it to work and I can't figure out async. The error is the title.

A: First issue, since getRowCount is async, it returns a Promise
Second issue, getRowCount doesn't actually return anything
async function getRowCount() {
    let returnValue;
    await Excel.run(async(context) => {
        const sheet = context.workbook.worksheets.getActiveWorksheet();
        var rowCount = 0;

        for (var i = 0; i >= 0; i++) {
            var cell = sheet.getCell(i, 0);
            cell.load("address, values");
            await context.sync();
            if (cell.values[0][0] == "") {
                break;
            } else {
                rowCount++;
            }
        }
        await context.sync();
        returnValue = rowCount;
    });
    return returnValue;
}

There may be a better way to do the above, but I don't know the workings of this Excel.run etc, so but as long as Excel.run is returning a Promise - which I assume because you use await on it - then the above should work
and, usage in your code would be
async function getData() {
  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();
    let rowCount = await getRowCount();
    var arrExport = Create2DArray(rowCount);

    for (var r = 0; r < rowCount; r++) {
    .
    .
    .

Should now work


text:
Q: Saving Excel PDF in the same file path for different users VBA (MAC) I am having difficulty saving Each PDF in a specific folder for various users on our network. I want the code to save a PDF version of the worksheet in this location: Macintosh HD ▸ Users ▸ (Specific Username Saving the PDF) ▸ Dropbox ▸ Froghair ▸ QB Invoices
This is the code I have so far, I cannot get it to save anything. Any help is greatly appreciated. Thanks in advance!
ActiveSheet.PageSetup.PrintArea = Range("A1:G90")

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:="C:Macintosh
HD\Users\" & Environ$("Username") & "\Dropbox\Froghair\QB Invoices" &
ThisWorkbook.Name & "Invoice " & Range("F6").Text & "_copy",
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True

A: I am not really across Macs but don't you need a \ after C: when you specify the filename?.
Possibly you need one after QB Invoices too as I am not sure if that is the start of the filename or if it is a folder?
Also does the Mac have the same environment variables as Windows? I am not 100% sure that this will work the way it does in Windows.

A: Try changing Environ$("Username") to Environ("Username") instead. Where did the $ come from?. I would just save to the root folder to see if that works. If it does, then your path is incorrect.


text:
Q: Read in only certain column names from TSV file into R I have a very large .TSV file that I cannot read into R due to its size.
I want to read in only select columns BY HEADER NAME, eg. "HEALTH".
How can I go about doing this?

A: Have a look at the colClasses argument of read.table:
df <- read.table(header = TRUE, colClasses=c(NA, "NULL", NA), text = '
                 A B C
                 1 2 3
                 4 5 6')
df
#  A C
#1 1 3
#2 4 6

Update:
To select by names first read in the header and then create a vector for colClasses:
# read the header
header <- read.table(header = FALSE, nrow = 1, text = '
                 A B C
                 1 2 3
                 4 5 6')

# cols we want to select
take <- c('A', 'B')
# create vector for colClasses
takecols <- ifelse(t(header) %in% take, NA, 'NULL')

# read selected cols
df <- read.table(header = TRUE, colClasses=takecols, text = '
                 A B C
                 1 2 3
                 4 5 6')


text:
Q: Number of Unique sections in CDA schema I have read CCD is a summarized version of CDA and has 17 unique sections including the header. I couldn't find out how many overall sections there are when there are full-fledged CDA documents.

A: There isn't necessarily a hard limit of 17 sections in a C-CDA 2.1 CCD. There are 17 sections listed for that document type, of which only 6 are required. But it's an open document template, so it's allowable to include other section types.
All sections use the same XML Schema elements. Section types are distinguished by the <code> and <templateId> elements.


text:
Q: How to remove the extra space on the left and the right of the default BarChart?
pbdomains = <|
       "Overall " -> Around[2.6, 0.04],
       "PB" -> Around[4.25, 0.06]
|>;

BarChart[pbdomains, ChartStyle -> "BrightBands",
 LabelStyle -> {FontFamily -> "Times New Roman", 28, Bold,
   GrayLevel[0]}, Frame -> True, FrameLabel -> {"", " Count"},
 BarSpacing -> Tiny,
 ChartLabels -> Callout[Automatic, Above, Appearance -> "Balloon"]]

A: Based on Rohit Namjoshi solution:
pbdomains = <|"Overall " -> Around[2.6, 0.04],
   "PB" -> Around[4.25, 0.06]|>;

BarChart[pbdomains, ChartStyle -> "BrightBands",
 LabelStyle -> {FontFamily -> "Times New Roman", 28, Bold,
   GrayLevel[0]}, Frame -> True, FrameLabel -> {"", " Count"},
 BarSpacing -> Tiny,
 ChartLabels -> Callout[Automatic, Above, Appearance -> "Balloon"],
 PlotRange -> {{0.5, 2.5}, All}]

A: You can use PlotRangePadding.
pbdomains = <|
       "Overall " -> Around[2.6, 0.04],
       "PB" -> Around[4.25, 0.06]
|>;

BarChart[pbdomains, ChartStyle -> "BrightBands",
 LabelStyle -> {FontFamily -> "Times New Roman", 28, Bold,
   GrayLevel[0]}, Frame -> True, FrameLabel -> {"", " Count"},
 BarSpacing -> Tiny,
 ChartLabels -> Callout[Automatic, Above, Appearance -> "Balloon"],
 PlotRangePadding -> {{-1.4, -1.37}, {None, Scaled[0.2]}}]

A: 1. Use the (undocumented) option "FixedBarSpacing" as  "FixedBarSpacing" -> True or as  Method -> {"FixedBarSpacing" -> True}
BarChart[pbdomains, ChartStyle -> "BrightBands",
  LabelStyle -> {FontFamily -> "Times New Roman", 28, Bold,
      GrayLevel[0]}, Frame -> True, FrameLabel -> {"", " Count"},
  ChartLabels -> Callout[Automatic, Above, Appearance -> "Balloon"],
  "FixedBarSpacing" -> True]

2. Use {pbdomains} as the first argument and use the option BarSpacing -> {Tiny, 1}:
BarChart[{pbdomains},
  BarSpacing -> { Tiny, 1},
  ChartStyle -> "BrightBands",
  LabelStyle -> {FontFamily -> "Times New Roman", 28, Bold, GrayLevel[0]},
  ImageSize -> Large, Frame -> True, FrameLabel -> {"", " Count"},
  ChartLabels -> Callout[Automatic, Above, Appearance -> "Balloon"]]


text:
Q: Shift right ">>" in C99
Possible Duplicate:
Weird behavior of right shift operator

Hello
Why both numbers from this function are printed the same? It is not a cyclic shift.
unsigned int i=0x89878685;
int main()
{
  printf("0x%x\n", i);
  printf("0x%x\n", i>>32);
}

$ ./a.out
0x89878685
0x89878685

Do all compilers work in this way?

A: Shifting a 32-bit integer by 32 bits is undefined behavior. The result is not predictable.
In C and C++ if the integer has N bits, you are only allowed to shift by less then N bits. If you shift N or more the behavior is undefined.
In practice, when shifting a 32-bit integer, some platforms will simply interpret the shift count as a 5-bit value (discard any bits above the lower 5), meaning that 32 will be interpreted the same way as 0. This is apparently what happens on your platform. The value is not shifted at all.


text:
Q: how to get the records from a table of last 7 days if(isset($_POST['last']))
 {
    $s=mysql_query("select * from appointment where `date` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
    echo $s;
    while($last=mysql_fetch_array($s))
    {
        echo  $last['date'];
        echo $last['doctor'];
    }
 }

how to get the records of last 7 days from a table after clicking of button, the field name of date is  "date"

A: Your Query should look like below------
SELECT * FROM appointment WHERE `date`>= DATEADD(day, -7, GetDate())

A: SELECT * FROM `appointment` WHERE `date`>= DATE_SUB(CURDATE(),INTERVAL 7 DAY)

Use above query for your solution.

A: Try This buddy!
WHERE date <= NOW() AND date >= DATE_SUB(date, INTERVAL 7 DAY)


text:
Q: When are numerical expressions identical Very elementary:
2 + 3 == 5   evaluates to True and 5 == 5   evaluates to True.
How do I check if two numerical expressions are identical?
In other words, I want  a matching test that says 2 + 3 does not match 5, but 5 does match 5.
More generally, how do you test whether algebraic expressions are identical?

A: Here's a try for the first question:
reallySameQ[a_, b_] := SameQ[Hold[a], Hold[b]]
SetAttributes[reallySameQ, HoldAllComplete]
reallySameQ[5, 5]
(* True *)
reallySameQ[2 + 3, 5]
(* False *)

A: Following WReach's fine explanation here one cannot even rely on SameQ to check for identical expressions; instead it seems one needs Order, therefore with holding added:
SetAttributes[identicalQ, HoldAll]

identicalQ[x_, y_] := Order[Unevaluated @ x, Unevaluated @ y] == 0

Now:
identicalQ[2 + 3, 5]

identicalQ[5, 5]

False

True


text:
Q: How to get a reference to patricullar Word Document Paragraphs and then display it into Dsoframer or any Word Processing component for .net? We are developing C# .net 4.0 Windows Form Based Application. Here, User Will enter the Word Document paragraph number.After getting that Paragraph number, I want to Show that Selected Paragraph's in the any one of the WORD PROCESSING COMPONENT like Dsoframer or any other without changing the format. How i do it?
Using DSOFRAMER i could able to open the Entire Word Document.but I want to display only user selected paragraphs...
(OR)
I can able to retrieve the open xml representation of the user Selected Word document Pararaphs(USING OPEN XML SDK 2.0).Then how i paste it in to any WORD PROCESSING COMPONENT.

A:   Object fileName = "C:\\Documents and Settings\\saravanan\\Desktop\\test1.docx";
  axFramerControl1.Open(fileName, true, 0, "", "");

  Microsoft.Office.Interop.Word.Document wordDoc =     Microsoft.Office.Interop.Word.Document)axFramerControl1.ActiveDocument;
  Microsoft.Office.Interop.Word.Application wordApp = wordDoc.Application;

  Microsoft.Office.Interop.Word.Range r = wordDoc.Paragraphs[15].Range;
 //object dir = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseStart;
 //r.Collapse(ref dir);
 r.Select();

This Displays the 15th paragraph of your document with selection range...


text:
Q: pandoc latex template I have found this latex template,
http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/ThesisStyle/
which is perfect for my thesis. I am currently writing it directly in Latex with TexStudio, and playing around with the template directly is easy.
I am however switching to RStudio and wiriting it as a RNotebook, as I need to be able to easily produce docx versions of it (or other formats).
I already produced a Rmd version which works perfectly as a html/docx, but the pdf it produces (and i tried bookdown, thesisdown, oxfordown etc..) is never as good looking as the template above.
Is there a way to "extract" a template from the latex template in the link, which can be used for the pandoc conversion in RStudio? How?
(i am quite a newbie so please try with an easy accessible answer!)


text:
Q: C# Httpresponse gives Unable to write data to the transport connection: Broken pipe I have done this little piece of code on a console app, to stream a file or to simulate a stream of data over HTTP by chunk
            var musicFile = "music.mp3";
            var imageFile = "image.mp3";

            var prefixes = new List<string>() { "http://*:8888/" };
            HttpListener server = new HttpListener();

            foreach (string s in prefixes)
            {
                server.Prefixes.Add(s);
            }

            server.Start();

            System.Console.WriteLine("Listening...");

            var context = server.GetContext();

            var response = server.GetContext().Response;

            //response.ContentType = "image/jpeg";
            response.ContentType = "audio/mpeg";
            response.SendChunked = true;

            const int chunkSize = 1024;
            using (var file = File.OpenRead(path))
            {
                int bytesRead;
                var buffer = new byte[chunkSize];
                while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
                {
                    try
                    {
                        response.OutputStream.Write(buffer, 0, bytesRead);
                        response.OutputStream.Flush();

                        System.Console.WriteLine("Chunk sent.");
                    }
                    catch (System.Exception ex)
                    {
                        System.Console.WriteLine($"{ex.Message}");
                    }
                }
            }

            context.Response.Close();

Hello everyone
This works perfectly when I send an 10mb image, but it throw an exception when I use a mp3 file or a wav file.

Unhandled exception. System.Net.HttpListenerException (0x80131620): Unable to write data to the transport connection: Broken pipe.
at System.Net.HttpResponseStream.InternalWrite(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.HttpResponseStream.WriteCore(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 size)

Any help ?
Thank you.
EDIT: I tested on the same machine and on lan, with Chrome and Safari.


text:
Q: How to install XnViewMP in Ubuntu 18.04 and later Is there a way to install Image viewer and converter XnViewMP (or Xnview and XnConverter) in Ubuntu 18.04 and later?
Other described ways (14.04, 16.04, 16.10) seem not to work for me.

A: *

*Download and install the XnView MP deb file from the XnView Homepage. Although there were problems in Ubuntu 16.10, the newer versions (XnViewMP 0.9x) work fine in 18.04 and probably later. XnConvert also worked for me.

Update 19.04 and later (Thanks to Charles Green):
The XnViewMP .deb file does not install needed library libopenal1.
To fix this open a terminal windows (e.g. ctrl+alt+t) and enter the command
sudo apt install libopenal1

*Install it as **flatpak** from Flathub.
Follow the instructions from flatpak.org including the Software Flatpak plugin to setup flatpak including flathub support. After a system restart, you can find XnView and XnConvert in the Software Center and install it from there.

*As AppImage, see other answer.

A: *

*Download the AppImage file from the XnViewMP homepage.

*Give it execute permissions.
chmod +x XnView_MP.glibc2.17-x86_64.AppImage

*Run it.
./XnView_MP.glibc2.17-x86_64.AppImage

*To remove, delete the AppImage file and config folder at $HOME/.config/xnviewmp/

A: XnViewMP is also available as a snap:
~$ snap search xnview
Name      Version     Publisher  Notes  Summary
xnviewmp  0.90-snap1  vs         -      XnView MP is the enhanced version of XnView Classic.
Install with
sudo snap install xnviewmp

Update June 2019: Obviously XnViewMP has been removed from the snap store (I don't know if temporary or permanently), so this will not work anymore, please use one of the suggestions in the other answers.


text:
Q: meaning of R, S, Da in kCGBlendMode values I'm having trouble grasping the meaning of R = 0, R = S, R = S*Da, defined in kCGBlendMode values such as kCGBlendModeClear, kCGBlendModeCopy, kCGBlendModeSourceIn. So, to what do these symbols refer?

A: R=0 means that the result color will just be 0, meaning it will be cleared.
R=S means the result color is the same as the source color
R=S*Da means the result is the source color times the alpha value of the destination
If you take a look at the documentation and scroll down you will see their meaning listed:

The blend mode constants introduced in OS X v10.5 represent the Porter-Duff blend modes (a little explanation how they work). The symbols in the equations for these blend modes are:

*

*R is the premultiplied result

*S is the source color, and includes alpha

*D is the destination color, and includes alpha

*Ra, Sa, and Da are the alpha components of R, S, and D

If you furthermore take a look at Setting blend modes you can see most of the blend modes applied and what their result may look like.


text:
Q: react leaflet - MapContainer only get initial value of parent useState I have a very weird scenario using react leaflet
I have a parent component:
import React, { useEffect, useState, useRef} from "react";
import Locate from "locate";

export default function Chat (props) {

    const [allowLocation, setAllowLocation] = useState(true)

    function handleUpdate(p){
    console.log(allowLocation)
    if(allowLocation){
    console.log("update location")
    }

    }

    function handleShareLocation(){
    if(allowLocation){
        setAllowLocation(false)
    }else{
        setAllowLocation(true)
    }
    }

return(

  <button onClick={handleShareLocation}>share location</button>
  <Locate  parentUpdate={(p)=>{handleUpdate(p)}} />

)
}

Basically, The parent component has an allowLocation variable to control if user permission to show map to opposite party(it's a chat app).
and Locate component(child):
export default function Locate (props){

  function handleMarkerPosition(pos){
    props.parentUpdate(pos)
  }

  return(

  <button onClick={e=>{handleMarkerPosition("test")}}>click test</button>
  <MapContainer
    whenCreated={m => {mapRef.current = m}} center={[lat, lng]} zoom={16} scrollWheelZoom={false}>
    <TileLayer url="https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png"/>
    <DraggableMarker location={[lat, lng]} markerupdateposition={(pos)=>handleMarkerPosition(pos)} />
  </MapContainer>

)}

function DraggableMarker(props) {
   ...
}

*

*If I click on click test button, it will call handleMarkerPosition function, that will call props.parentUpdate, and trigger handleUpdate from parent component. Then, it will trigger according to the allowLocation(this is expected behavior)

*but if I drag the DraggableMarker around, which using the same handleMarkerPosition function, will always get the initial value of allowLocation from parent, no matter how I already change the value in the parent.
Why is this happening? I only check allowLocation at parent component, but somehow the child component always remember the initial value of its parent component. Moreover, 1 and 2 are sharing the same function.
How can I resolve this?


text:
Q: Stop the procedure if there are no values in the A1 to the end of the column I have a problem with this routine, if in column A from A2 to the end of column there are no written cells, I would like to stop the sub but I can't understand how to set
Sub test()
Dim sh As Worksheet, lastR As Long, i As Long, j As Long, arr
  Set sh = Sheets(2)
  lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
  arr = sh.Range("A1:A" & lastR).Value
  i = 1
  For j = 2 To UBound(arr)
     If i > 0 Then arr(j, 1) = arr(j, 1) & "-"
     i = i + 1
     If i = 8 Then i = 0
  Next j
  sh.Range("A1").Resize(UBound(arr), 1).Value = arr
  Application.CutCopyMode = False
  Call Copia
End Sub

A: Use WorksheetFunction to count the non-empty cell and use Exit Sub to stop the procedure
Sub test2()
Dim sh As Worksheet, lastR As Long, i As Long, j As Long, arr
  Set sh = Sheets(2)
  lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
  arr = sh.Range("A1:A" & lastR).Value
  i = 1

  If WorksheetFunction.CountA(sh.Range(sh.Range("A2"), sh.Range("A2").End(xlDown))) = 0 Then

     Exit Sub

  End If

  For j = 2 To UBound(arr)
     If i > 0 Then arr(j, 1) = arr(j, 1) & "-"
     i = i + 1
     If i = 8 Then i = 0
  Next j
  sh.Range("A1").Resize(UBound(arr), 1).Value = arr
  Application.CutCopyMode = False
End Sub


text:
Q: Spring Security - Custom login form not calling the AuthenticationProvider on submit RESOLVED:
Spring Security 4 no longer seems to provide a default login-processing-url.  We must now explicitly provide it in form-login as follows.
login-processing-url="/j_spring_security_check"

I have a strange combination of behaviors that has me stumped.  Found lots of tutorials and similar questions but none quite exactly like this.  I hope someone can help.
Short version: The login page redisplays - regardless of good or bad username/password and the AuthenticationProvider is never called (breakpoints not tripped).
Long version:
Step 1 - successful

*

*I was able to use spring security with the default AuthenticationProvider and the default auto-generated login screen.  Good.

*I was able to write a custom AuthenticationProvider and UserDetailsService.  Things worked fine, using the default auto-generated login screen.  Good.

*... so the above rules out a lot of possible problems.

Step 2 - the problem - Setting up to use a custom login form
1) I added the form-login:
<sec:form-login
login-processing-url="/j_spring_security_check"
login-page="/login.htm"
authentication-failure-url="/login.htm?error"
username-parameter="username"
password-parameter="password"
/>
<sec:logout logout-success-url="/login.htm?logout"/>
<sec:csrf/>

2) I made sure that login URLs will be accessible:
<sec:intercept-url pattern="/login.htm"      access="permitAll" />

3) I created a trivial LoginController:
@Controller
public class LoginController {

@RequestMapping(value="/login.htm")
public ModelAndView login(HttpServletRequest request,
  @RequestParam(value="error", required=false) String error,
  @RequestParam(value="logout",required=false) String logout) {
  ModelAndView model = new ModelAndView();
  if(error!=null) {
    model.addObject("error", "Invalid username or password.");
  }
  if(logout!= null) {
    model.addObject("msg", "Successfully logged out.");
  }
  model.setViewName("/login");
  return model;
}

4) I created a trivial login.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<title>Login</title>

Login form

Username and Password

    <c:if test="${not empty error}">

${error}

    </c:if>
    <c:if test="${not empty msg}">

${msg}

    </c:if>

    <form name="loginForm" action="<c:url value='j_spring_security_check' />" method='POST'>

          User:
          <input type='text' name='username' value = '' />

          Password:
          <input type='password' name='password' />

          <input name="submit" type="submit" value="submit" />

[${not empty webUser}]

      <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    </form>

5) Then I setup some breakpoints in Eclipse to see how it behaves.

*

*The login page displays fine.

*I enter username and password and hit submit.

*Good or bad username and password all cause the same behavior, the redisplay of the login page.

*The breakpoints in the AuthenticationProvider are never tripped.

My interpretation is that the action specified by < c : url value='j_spring_security_check' /> is not triggering the AuthenticationProvider.
Note that the very same custom AuthenticationProvider worked flawlessly when I used the built-in default spring security login form.  That tells me that the problem has nothing to do with the provider itself, but rather with "reaching it" when I hit submit in login.jsp, especially since I have a breakpoint on its very first line and it is not being tripped.
I bet my error is trivial and obvious to someone familiar with Spring Security.  My thanks in advance to anyone that catches it.

A: This question is resolved.
Spring Security 4 no longer seems to provide a default login-processing-url. We must now explicitly provide it in form-login as follows.
login-processing-url="/j_spring_security_check"
After banging my head against the wall for quite a few hours I stumbled upon the solution.  I hope this is of help to others in the same situation.


text:
Q: data to be string in respond: function(status, data, headers, statusText) I have an API call as:
  $http.post(that.auth.apiUrl + '/data/auth', authParam).then(function (jsonObj) {

//jsonObj.data is string
                        var data = JSON.parse(jsonObj.data);
    }

It returns a JSON object with string in data like
Object {data: "{"userId":1,"userFormat":"2"}", status: 200, config: Object, statusText: "OK"}
For its unit testing, I have a mocked a http request like:
var mockObj = {
                "userid": 1,
                "userFormat" : "2"
            };
As I need data to be string I did stringify
 $httpBackend.when('POST', apiUrl + '/data/auth').respond( 200,
                        JSON.stringify(mockObj)
                );

but it returns
Object{data: Object{userid: 1, userFormat: '2'}, status: 200, headers: function (name) { ...
so instead of getting string in data object, I'm getting another Object. How can I make it in string format? I want the data to have a string value instead of an object with userId and format

A: According to https://docs.angularjs.org/api/ngMockE2E/service/$httpBackend it looks like respond() takes a callback function (that returns an array) or data. I don't see an option where it takes a status code and then data.
var mockObj = { "userid": 1, "userFormat" : "2" };
$httpBackend.when('POST', apiUrl + '/data/auth').respond(JSON.stringify(mockObj));

A: It worked when I gave mock object a string and again stringify it like
var mockObj = "{ 'userid': 1, 'userFormat' : '2' }";
$httpBackend.when('POST', apiUrl + '/data/auth').respond(JSON.stringify(mockObj));


text:
Q: Unit testing store.mapDispatchToProps in Stencil with Redux using Jest I am struggling to unit test the store in the componentWillLoad() lifecycle.
I have tried following this guide: https://github.com/dmitry-zaets/redux-mock-store
component.tsx
  @Prop({ context: "store" }) store: Store;

  componentWillLoad() {
    this.store.mapDispatchToProps(this, { updateStep });
  }

spec.ts
   const middlewares = [thunk];
   const mockStore = configureStore(middlewares);

   const mapDispatchToProps = () => ({ type: updateStep});

   it('should test componentWillLoad', () => {

    const initialState = {};
    const store = mockStore(initialState);

    store.dispatch(mapDispatchToProps());
    const actions = store.updateStep();
    const expectedPayload = { type: updateStep};
    expect(actions).toEqual([expectedPayload]);

});

I get the following error atm: TypeError: mockStore is not a function


text:
Q: Meaning of p-values for an interaction between a categorical variable (w/ >2 cats) & continuous variable I have a question about the meaning of the p-values when testing an interaction between a continuous and a categorical variable (with more than 2 categories).
When I do that in a glm model using R, I obtain a p-value for each class of the categorical variable vs. continuous one. However, I would like to get the p-value for the interaction itself using R, and to understand what the meaning of this p-value is.
An example of the code and results:
model_glm3=glm(cog~lg_hag+race+pdg+sex+as.factor(educa)+(lg_hag:as.factor(educa)),
               data=base_708)

Coefficients:
                         Estimate Std. Error t value Pr(>|t|)
(Intercept)               21.4836     2.0698  10.380  < 2e-16 ***
lg_hag                     8.5691     3.7688   2.274  0.02334 *
raceblack                 -8.4715     1.7482  -4.846 1.61e-06 ***
racemexican               -3.0483     1.7073  -1.785  0.07469 .
racemulti/other           -4.6002     2.3098  -1.992  0.04687 *
pdg                        2.8038     0.4268   6.570 1.10e-10 ***
sexfemale                  4.5691     1.1203   4.078 5.15e-05 ***
as.factor(educa)2         13.8266     2.6362   5.245 2.17e-07 ***
as.factor(educa)3         21.7913     2.4424   8.922  < 2e-16 ***
as.factor(educa)4         19.0179     2.5219   7.541 1.74e-13 ***
as.factor(educa)5         23.7470     2.7406   8.665  < 2e-16 ***
lg_hag:as.factor(educa)2 -21.2224     6.5904  -3.220  0.00135 **
lg_hag:as.factor(educa)3 -19.8083     6.1255  -3.234  0.00129 **
lg_hag:as.factor(educa)4  -8.5502     6.6018  -1.295  0.19577
lg_hag:as.factor(educa)5 -17.2230     6.3711  -2.703  0.00706 **

I would like to have the p-value of the interaction and its meaning (i.e., just one p-value for the whole interaction, not one for each category)

A: The general way to do this is with a full-reduced model test using the anova function.  Refit your model without the interaction of interest (the update function can be convenient for this) then run the anova function on the full and reduced models, for a glm fit you probably want to include test="Chisq".
Something like:
model_glm3_reduced <- update( model_glm3, .~. - lg_hag:as.factor(educa) )
anova( model_glm3_reduced, model_glm3, test="Chisq" )

Here the null hypothesis is that the 2 models fit equally well (any differences due to chance) and the alternative is that the full model contains at least one term that is an improvement in the fit.  Since the difference in the 2 models is only the interaction term, this gives a single test (p-value) for testing the entire interaction.


text:
Q: Lord of the Rings written to support constructed languages or the other way round? I've heard the claim that Tolkien wrote, or at least started writing, The Lord of the Rings to support (with a history providing cultural depth) the artificial languages he was creating at the time.
Is this true, or was it the other way round? Which came first, the languages or the fiction?

A: Tolkien began creating languages when he was a young man, well before he started his career as an author.  This essay shows that the languages came first and that his talent as a linguist led to his desire to create worlds in which these languages were commonplace.

A: Tolkien started writing the legendarium to support his constructed languages, then came The Hobbit, a children's story with the lengendarium as its (distant) background. The publishers of The Hobbit asked Tolkien to work on a sequel and that's what became The Lord of the Rings.
The legendarium is what Christopher Tolkien edited together to form The Silmarillion.
If I recall correctly, J.R.R.Tolkien loved both Welsh and Finnish and tried to construct a linguistic history that would explain a Welsh-like and Finnish-like language (Sindarin and Quenya respectively) that had a common origin.

A: Tolkien once said that the reason he created Arda was because he needed a world in which the word Earendil would come to its right. There's some great material on YouTube about this:
Christopher Tolkien on his father's languages
A must see 3-part lecture: J.R.R. Tolkien: An Imaginative Life

A: The languages came first.
J.R.R Tolkien was s philologist, and he loved languages. So he started creating a few himself. After a while, I suppose he realised these languages could be used, and he created a world (Middle Earth) and, for it, characters to speak the languages.


text:
Q: Creating separate data source for my session spring using JDBC and spring data jpa in spring boot I am a newbie in spring-boot and i want to configure my spring session with jdbc using h2 database, but it does not create a database and table in my h2 embedded database, it creates it in the PostgreSQL, using the PostgreSQL data source i configured in my applications properties file. How do i make my spring app use my embedded h2 db for storing sessions only while not conflicting with the PostgreSQL data source for my JPA
https://github.com/eshiett1995/SessionProject. i would love if someone could help me with the session

A: check https://github.com/nomanbplmp/CustomSessionStoreExample  to see complete example.
In order to make session store work with other than primary database it is required to provide custom session repository and override spring's internal as given below.
@Configuration
@EnableJdbcHttpSession
class SessionConfig {
    @Bean
    public JdbcOperationsSessionRepository sessionRepository(){
      DataSource ds =   DataSourceBuilder.create().driverClassName("org.h2.Driver").username("sa").url("jdbc:h2:file:~/test").build();
     return   new SessionRepo(ds,new DataSourceTransactionManager(ds));

    }
}

class SessionRepo extends JdbcOperationsSessionRepository  {

    public SessionRepo(DataSource dataSource, PlatformTransactionManager transactionManager) {
        super(dataSource, transactionManager);

    }

}


text: Q: How to freeze table header at modal box So I have tried using these TableLock method on normal page, it works just fine, but I tried using it on modal box and it didn't work. Any idea how to make table header at modal box freezes after it touched the top part of browser? I don't want the whole table to stay in one place like this freeze pane.


text:
Q: Refining My Eloquent Query (Laravel) Edited for Clarity:
I need some way for this Query to only return distinct course_ids in the
->wherein('course_id', $array)

part of the query. It gets the total number of completed courses, but if a user has completed a course more than once it counts it toward the total. So if you want to know how many students have done a course, the number will be off if a student has completed a course more than once.
    public function report_count(){
    $array = \Session::get('course_report')['course'];
    return $this->hasOne('Tracking', 'roster_id')
        ->selectRaw('roster_id, count(*) as aggregate')
        ->where('status', 1)
        ->wherein('course_id', $array)
        ->groupBy('roster_id');

I've tried adding groupBy('course_id') at the end but it does not work.

A: Fixed. Changed the query to
return $this->hasOne('Tracking', 'roster_id')
        ->selectRaw('roster_id, count(distinct course_id) as aggregate')
        ->where('status', 1)
        ->wherein('course_id', $array)
        ->groupBy('roster_id');

per @Robin R suggestion, I went on a search of ways to utilize SQL in my selectRaw query instead of trying this the eloquent way. Thanks to all who helped me brainstorm though this one.


text:
Q: Show Parent category and Subcategory in Wordpress I need to show sub category in below to the respective parent category in wordpress Sidebar.
Without using plugin I need to show the parent category and sits sub categories  in sidebar with following manner
Category1

     --Sub1

     --Sub2

Category2

   --Cat2Sub1

   --Cat2Sub2

A: Please try with this code
<?php
if(is_category()) {

    $breakpoint = 0;
    $thiscat = get_term( get_query_var('cat') , 'category' );
    $subcategories = get_terms( 'category' , 'parent='.get_query_var('cat') );

    if(empty($subcategories) && $thiscat->parent != 0) {
        $subcategories = get_terms( 'category' , 'parent='.$thiscat->parent.'' );
    }

    $items='';
    if(!empty($subcategories)) {
        foreach($subcategories as $subcat) {
            if($thiscat->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
            $items .= '

term_id.$current.'">
                term_id ).'" title="'.$subcat->description.'">'.$subcat->name.' ('.$subcat->count.' posts)

';
        }
        echo "
$items
";
    }
    unset($subcategories,$subcat,$thiscat,$items);
}
?>


text:
Q: not able to add meet link to google calendar events in java I am working on a spring boot api which schedules events for me but and its working fine but along with events I want to add a meet link too and I am not able to do that.I am using a service account from cloud console and shared my personal account with this service account.How can I implement google meet?
Here's my code:
Event event = new Event()
                    .setSummary("Google I/O 2015")
                    .setLocation("800 Howard St., San Francisco, CA 94103")
                    .setDescription("A chance to hear more about Google's developer products.");
            ConferenceSolutionKey conferenceSKey = new ConferenceSolutionKey();
            conferenceSKey.setType("hangoutsMeet");
            CreateConferenceRequest createConferenceReq = new CreateConferenceRequest();
            createConferenceReq.setRequestId("adojajaod"); // ID generated by you

            createConferenceReq.setConferenceSolutionKey(conferenceSKey);
            ConferenceData conferenceData = new ConferenceData();
            conferenceData.setCreateRequest(createConferenceReq);

            System.out.println(conferenceData);
            event.setConferenceData(conferenceData);

            DateTime startDateTime = new DateTime("2021-08-14T09:00:00-07:00");
            EventDateTime start = new EventDateTime()
                    .setDateTime(startDateTime)
                    .setTimeZone("America/Los_Angeles");
            event.setStart(start);

            DateTime endDateTime = new DateTime("2021-08-15T17:00:00-07:00");
            EventDateTime end = new EventDateTime()
                    .setDateTime(endDateTime)
                    .setTimeZone("America/Los_Angeles");
            event.setEnd(end);

            String[] recurrence = new String[]{"RRULE:FREQ=DAILY;COUNT=2"};
            event.setRecurrence(Arrays.asList(recurrence));

            EventReminder[] reminderOverrides = new EventReminder[]{
                    new EventReminder().setMethod("email").setMinutes(24 * 60),
                    new EventReminder().setMethod("popup").setMinutes(10),
            };
            Event.Reminders reminders = new Event.Reminders()
                    .setUseDefault(false)
                    .setOverrides(Arrays.asList(reminderOverrides));
            event.setReminders(reminders);

            event = client.events().insert("himanshuranjan30@gmail.com", event).setConferenceDataVersion(1).execute();
            System.out.printf("Event created: %s\n", event.getHtmlLink());

Here I am trying to setup a meet link using conference but its not working and giving a error like:
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid conference type value.",
    "reason" : "invalid"
  } ],
  "message" : "Invalid conference type value."
}

Any help will be appreciated.

A:
conferenceSKey.setType("hangoutsMeet");

Looks like the calendar where you try to insert the event does not accept the "hangoutsMeet" conference call type.
To verify use get of Calendar API to view your target Calendar metadata.
https://developers.google.com/calendar/api/v3/reference/calendars
You can see the allowed types under,
"conferenceProperties": {
    "allowedConferenceSolutionTypes": [
      string
    ]
  }


text:
Q: Count percentage of filled inputs inside div is there some simple way to count percentage of filled inputs inside a div?
It has to be in Javascript, not jQuery.
Here is my HTML code

General

 x % FILLED

Contact info

 x % FILLED

 <input type="text" name="first_name" />
 <input type="text" name="last_name" />

....

So basically if I enter only first name, which is 1/2 out of inputs, it should echo in that li element 50%.
Each tab will have different number of inputs and own filled percenage.
Is it possible with only Javascript?
Any help would be appriciated, thanks.

A: Initially you could get all the input fields inside a div. Then you could see how many they are. Later you could count how many of them has a value. Using these two numbers you can get what you want.
// Get the div you want to look in.
var div = document.getElementById("tabs-1");

// Get all the input fields inside your div
var inputs = div.getElementsByTagName('input');

// Get the number of the found inputs.
var totalInputs = inputs.length;

// Loop through them and check which of them has a value.
var inputsWithValue = 0;
for(var i=0; i<totalInputs; i++)
    if(inputs[i].value!=='')
        inputsWithValue +=1;

// Calculate the percentage.
var filledPercentage = (inputsWithValue/totalInputs)*100;

A: Here a fiddle with instant update of percentage: http://jsfiddle.net/39xdvo96/1/

Percentage

0%

    <input type="text" name="first_name" />
    <input type="text" name="last_name" />

Javascript
  var getInputs = document.getElementsByTagName('input');

    for (i = 0; i < getInputs.length; i++) {

        getInputs[i].onkeyup = function () {

            var elem = document.getElementsByTagName('input');
            var vals = [].map.call(elem, function (input) {
                return input.value;
            });

        var filteredvals = vals.filter(function(val) {
        return !(val === "" || typeof val == "undefined" || val === null);
        });

            document.getElementById('percentage').innerHTML = filteredvals.length/(elem.length) * 100 +"%";

        };

}


text:
Q: lua's loadstring() not working with tables I have some text and I'm trying to load it via load string. The following works:
local m = loadstring("data = 5")()

But when the data is a table it doesn't work and gives the error "attempt to call a nil"
local m = loadstring("data = { 1 = 10}")()

A: The table declaration in lua require integer keys to be put inside square brackets:
data = {
  [1] = value,
}

The enclosing of keys in square brackets is always allowed, valid and possible. It can be skipped iff your key follows the pattern: [A-Za-z_][A-Za-z0-9_]* (which is the same as a valid variable name in lua)

A: If you had added an assert you would have got a more helpful message:
local m = assert (loadstring("data = { 1 = 10}"))()

Result:
stdin:1: [string "data = { 1 = 10}"]:1: '}' expected near '='
stack traceback:
    [C]: in function 'assert'
    stdin:1: in main chunk
    [C]: ?

And to actually answer the question, unless the table key happens to follow Lua variable naming rules, you have to put it inside square brackets, eg.
local m = assert (loadstring("data = { [1] = 10}"))()

m is still nil when I do this

What does that matter? The loadstring is done.
Just do this:
assert (loadstring("data = { 1 = 10}"))()
print (data [1])

You don't need the variable m. The loadstring puts a table into data - that is the important thing.


text:
Q: How to parse date format in java? java.text.ParseException: Unparseable date: "2014-01-15 00:003:00" ecxception is throwing
please shorout my peoblem
Thanks
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.*;
public class Dd {

  public static void main(String args[]) throws ParseException {

String s1="2014-01-15 00:003:00";

SimpleDateFormat sdf=new SimpleDateFormat("yyyy--MM-dd h:mm:ss");
   try{

Date date =sdf.parse(s1);
      SimpleDateFormat sdf1=new SimpleDateFormat("dd--MMM-dd H:mm:ss");
      String s3=sdf1.format(date);
System.out.println(s3);

 }
   catch (ParseException e) {
       System.out.println(e);
  }

 }
}

A: You can use SimpleDateFormat
The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):
Letter  Date or Time Component  Presentation    Examples
G   Era designator  Text    AD
y   Year    Year    1996; 96
Y   Week year   Year    2009; 09
M   Month in year   Month   July; Jul; 07
w   Week in year    Number  27
W   Week in month   Number  2
D   Day in year Number  189
d   Day in month    Number  10
F   Day of week in month    Number  2
E   Day name in week    Text    Tuesday; Tue
u   Day number of week (1 = Monday, ..., 7 = Sunday)    Number  1
a   Am/pm marker    Text    PM
H   Hour in day (0-23)  Number  0
k   Hour in day (1-24)  Number  24
K   Hour in am/pm (0-11)    Number  0
h   Hour in am/pm (1-12)    Number  12
m   Minute in hour  Number  30
s   Second in minute    Number  55
S   Millisecond Number  978
z   Time zone   General time zone   Pacific Standard Time; PST; GMT-08:00
Z   Time zone   RFC 822 time zone   -0800
X   Time zone   ISO 8601 time zone  -08; -0800; -08:00

A: Try this..
String s1 = "2013-01-15 8:00:03";
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd h:mm:ss");
    try {
        Date dt=sdf.parse(s1);//converting to date
         SimpleDateFormat sdf1=new SimpleDateFormat("dd-MMM-yyyy h:mm:ss");
         String s2=sdf1.format(dt);//formating to new format string
         System.out.println(s2);
    } catch (ParseException ex) {

    }

//new answer
public class Dd {

    public static void main(String args[]) throws ParseException {

        String s1 = "2014-01-15 00:003:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            Date date = sdf.parse(s1);
            SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
            String s3 = sdf1.format(date);
            System.out.println(s3);

        } catch (ParseException e) {
            System.out.println(e);
        }

    }
}


text:
Q: Getting Value Error when calculating time diffrences from a reference time in Pandas Given a df
4,2019-01-15 07:00:00
0,2019-01-15 07:00:05
3,2019-01-15 07:00:10
3,2019-01-15 07:00:15
3,2019-01-15 07:00:20
1,2019-01-16 10:00:00
3,2019-01-16 10:00:05
2,2019-01-16 10:00:10
4,2019-01-16 10:00:15
0,2019-01-16 10:00:20

I would like to calculate the time diffrence between the first row and the subsequent rows under the column time and express the result in the unit of seconds.
df['elapse_second']=pd.Timedelta(df['time'] - df.loc[0,'time']).seconds / 3600.0

However the compiler return an error
ValueError: Value must be Timedelta, string, integer, float, timedelta or convertible, not Series

The code to reproduce the above error is
import pandas as pd
import numpy as np

np.random.seed(0)

np.random.seed(0)
data_time=['2019-01-15 7:00:00','2019-01-16 7:00:00']
lapse=5 # unit in second
alist=[pd.DataFrame(np.random.randint(5,size=(5)),columns=['data']) for _ in range (2)]
all_df=[]
for disdf,ndata_time in zip(alist,data_time):
  disdf['time']=pd.date_range(start=ndata_time, periods=len(disdf), freq='5S')
  all_df.append(disdf)

df=pd.concat(all_df).reset_index(drop=True)

# t1 = pd.to_datetime('2019-01-15 7:00:00')
t1=df.loc[0,'time']
df['elapse_second']=pd.Timedelta(df['time'] - df.loc[0,'time']).seconds / 3600.0

Expected output
4,2019-01-15 07:00:00,0
0,2019-01-15 07:00:05,5
3,2019-01-15 07:00:10,10
3,2019-01-15 07:00:15,15
3,2019-01-15 07:00:20,20
1,2019-01-16 10:00:00,86400
3,2019-01-16 10:00:05,86405
2,2019-01-16 10:00:10,86410
4,2019-01-16 10:00:15,86415
0,2019-01-16 10:00:20,86420

A: Since your time column is already a datetime, you can simply subtract the 1st row using df.loc and extract the seconds from thr result using Series.dt.seconds:
In [475]: df['difference_in_seconds'] = (df['time'] - df.loc[0, 'time']).dt.seconds

In [476]: df
Out[476]:
   data                time  difference_in_seconds
0     4 2019-01-15 07:00:00                      0
1     0 2019-01-15 07:00:05                      5
2     3 2019-01-15 07:00:10                     10
3     3 2019-01-15 07:00:15                     15
4     3 2019-01-15 07:00:20                     20
5     1 2019-01-16 10:00:00                  10800
6     3 2019-01-16 10:00:05                  10805
7     2 2019-01-16 10:00:10                  10810
8     4 2019-01-16 10:00:15                  10815
9     0 2019-01-16 10:00:20                  10820

A: You need to change the dtype to 'timedelta64[s]' since you want the difference in seconds.
Replace
df['elapse_second']=pd.Timedelta(df['time'] - df.loc[0,'time']).seconds / 3600.0

with
df['elapse_second']=(df['time'] - df.loc[0,'time']).astype('timedelta64[s]')

and your code will produce the expected outcome.
Output:
   data                time  elapse_second
0     4 2019-01-15 07:00:00            0.0
1     0 2019-01-15 07:00:05            5.0
2     3 2019-01-15 07:00:10           10.0
3     3 2019-01-15 07:00:15           15.0
4     3 2019-01-15 07:00:20           20.0
5     1 2019-01-16 07:00:00        86400.0
6     3 2019-01-16 07:00:05        86405.0
7     2 2019-01-16 07:00:10        86410.0
8     4 2019-01-16 07:00:15        86415.0
9     0 2019-01-16 07:00:20        86420.0


text:
Q: Ajax not getting response from php I really have no clue whats wrong with my code here. Response from php is not getting back to my ajax call.  Here is my code. JQuery
$(".theform").submit(function(e){
            var formData = {
                "name": $('#name').val(),
                "email": $('#email').val(),
                "phone": $('#phone').val(),
                "message": $('#message').val()
            }

            var sendMail = $.ajax({
                type: 'POST',
                url: 'submit.php',
                data: formData,
                dataType: 'json',
                encode: true
            });

            sendMail.done(function(output){
                if(output == "failed"){
                        console.log("failed");
                )
                        }
                });

            e.preventDefault();
        });

PHP
if($_POST){

$adminEmail = "";
$data = [];
$to = $adminEmail;
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['phone'];
$headers = "From: $email". "\r\n" .
"Reply-To: $email" . "\r\n" .
'X-Mailer: PHP/' . phpversion();

$message = $_POST['message'];

$sendMail = mail($to, "Mail from $name", $message, $headers);

if($sendMail){
    $data = ["success"];
} else {
    $data = ["failed"];
   }
 }
print $data[0];

When i check the request, i see the response from the php but I can't seem to print it to screen or console in the ajax call.
Please, what am i  doing wrong? By the way, it should return "failed" for now


text:
Q: JSoup: проблема с IndexOutOfBoundsException Надо пропарсить страницу и взять оттуда расписание электричек. Jsoup не подходит, не знаю почему, но парсить страницу он отказывается и выдает ошибку

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

Код:
Document doc2;
doc2 = Jsoup.connect("http://www.tutu.ru/rasp.php?st1=16503&st2=17003&date=today").get();
Element table2=doc2.select("table.schedule_table_classic").get(0);

Объясните мне кто-нибудь, XML ли это и как можно извлечь расписание.

A: Ваша ошибка говорит о том, что doc2.select("table.schedule_table_classic") возвращает список элементов нулевой длины, после чего вы пытаетесь взять его первый элемент, коий не существует.
Решение:
Ешё раз изучите целевую страницу (её код) и составьте валидное выражение для поиска нужного списка элементов.
Elements tableRows = doc2.getElementById("schedule_table").getElemetsByTagName("tr");

A: Вот попробуйте так, у меня работает, выводит и строки и столбцы
    doc2 = Jsoup.connect("http://www.tutu.ru/rasp.php?st1=16503&st2=17003&date=today")
            .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36")
            .method(org.jsoup.Connection.Method.GET)
            .get();
    Element table=doc2.getElementById("schedule_table");
    Elements tr=table.getElementsByTag("tr");
    Elements td=tr.select("td");
    for(Element el:td)
        System.out.println(el);

A: Попробуйте с timeout.
С этим кодом, у меня все выводит.
    Document doc = Jsoup.connect("http://www.tutu.ru/rasp.php?st1=16503&st2=17003&date=today")
                .userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
                .timeout(150000).get();
    Element table = doc.getElementById("schedule_table");
    Elements tr = table.getElementsByTag("tr");
    Elements td = tr.select("td");
    for (Element el : td)
        System.out.println(el);

A: URL url=new URL("http://www.tutu.ru/rasp.php?st1=16503&st2=17003&date=today");
HttpURLConnection request= (HttpURLConnection) url.openConnection();
request.setRequestMethod("GET");
request.connect();
InputStream is=request.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuilder sb=new StringBuilder();
String rline=null;
while((rline=br.readLine())!=null){
            sb.append(rline);
        }

и потом строку можно парсить Jsoup'ом
org.jsoup.nodes.Document docu = Jsoup.parse(sb.toString());

и так далее


text:
Q: How to implement Recursive Fibonacci with openMPI it's my first question on StackOverflow :-) So sorry if I post the question in a wrong way...
This is my problem:
I have to compare the Recursive Fibonacci algorithm with different parallel programming model: Cilk, openMP...and openMPI
Cilk and OpenMP were trivial, but openMPI it's a bit more complicated for me...
I found an implementation of the Recursive Fibonacci that uses MPI_Comm_spawn and it works, but MPI_Comm_spawn primitive creates and execute new processes on the master node only. So the cluster is unused.
So...my ask is: there is a way to execute the spawned processes on the entire cluster? Otherwise, there are other solutions to implement Recursive Fibonacci with openMPI?
Thank you for helping me! :-)
This is the code that actually works on master node only:
[MASTER]
int main (int argc, char **argv){
  long n, fibn;
  int world_size, flag;
  int universe_size = 10;
  int myrank;
  char command[] = "slave_fib";
  MPI_Comm children_comm;
  MPI_Status status;
  int errcodes[1];

  MPI_Init (&argc, &argv);
  MPI_Comm_size (MPI_COMM_WORLD, &world_size);
  MPI_Comm_rank (MPI_COMM_WORLD, &myrank);

  MPI_Info local_info;
  MPI_Info_create (&local_info);

  if (world_size != 1)
    perror ("Top heavy with management");

  MPI_Comm_get_attr (MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, &universe_size,              &flag);
  if (universe_size == 1)
    perror ("No room to start workers");

  // Prepare argv for spawning the recursive process
  argv += 1;
  n = atol (argv[0]);

  if (n < 2){
      printf ("fib(%ld)=%ld\n", n, n);
      exit (0);
  }else{
      sprintf (argv[0], "%ld", n);
      MPI_Comm_spawn (command, argv, 1, local_info, myrank, MPI_COMM_SELF,
                      &children_comm, errcodes);
  }
  MPI_Recv (&fibn, 1, MPI_LONG, MPI_ANY_SOURCE, 1, children_comm,
            MPI_STATUS_IGNORE);

  printf ("fib(%ld)=%ld\n", n, fibn);
  fflush(stdout);

  MPI_Finalize ();
}

##### SPAWNED BYNARY #####

int main (int argc, char **argv){
  long n, fibn, x, y;
  int myrank, size;
  char command[] = "slave_fib";
  MPI_Comm children_comm[2];
  MPI_Comm parent;
  MPI_Info local_info;
  int world_size,flag;
  int universe_size=10;
  int errcodes[1];

  MPI_Init (&argc, &argv);
  MPI_Comm_get_parent (&parent);
  MPI_Comm_rank (MPI_COMM_WORLD, &myrank);
  MPI_Info_create (&local_info);

  MPI_Comm_size (MPI_COMM_WORLD, &world_size);

  if (parent == MPI_COMM_NULL)
    perror ("No parent!");

  if (parent != MPI_COMM_NULL)
    MPI_Comm_remote_size (parent, &size);

  if (size != 1)
    perror ("Something's wrong with the parent");

  MPI_Comm_get_attr (MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, &universe_size, &flag);

  argv += 1;
  n = atol (argv[0]);
  if (n < 2){

      MPI_Send (&n, 1, MPI_LONG, 0, 1, parent);

  }else{

      sprintf (argv[0], "%ld", (n - 1));

      MPI_Comm_spawn (command, argv, 1, local_info, myrank,
                      MPI_COMM_SELF, &children_comm[0], errcodes);

      sprintf (argv[0], "%ld", (n - 2));

      MPI_Comm_spawn (command, argv, 1, local_info, myrank,
                      MPI_COMM_SELF, &children_comm[1], errcodes);

      MPI_Recv (&y, 1, MPI_LONG, MPI_ANY_SOURCE, 1,
                children_comm[1], MPI_STATUS_IGNORE);

      fibn = x + y;             // computation

      MPI_Send (&fibn, 1, MPI_LONG, 0, 1, parent);
    }

  MPI_Finalize ();
}

How to execute it: mpirun -np 1 bynary name fib_num
The only way to execute it is with -np 1, if you set np > 1 the execution will return an error ( for the MPI_Comm_spawn )

A: After a fresh installation of ubuntu 16.04 and the libopenmpi-dev 1.10.2 on a cluster of 4 nodes the fibonacci computation seems works and the spawned processes are spread on all nodes.( without Torque)
But when I want to compute a fibonacci number more than 10, I receive some errors...
1) sometimes the execution wait forever the end of a spawned process
2) sometimes I receive this error:
 Child job 67 terminated normally, but 1 process returned a non-zero
 exit code..

Moreover I receive a lot of this messages in each execution:
[[30037,42],0] dpm_base_disconnect_init: error -12 in isend to process 0

These messages appear when the computation fail and when it end successfully as well.  Probably am I using the comm_spawn and send/recv in a wrong way?


text:
Q: Getting Facebook group posts automatically in android app I would like to implement the following feature in my android app.
We have a Facebook group and whenever a user post's something, it should be lively read on my android app(including post content,likes and comments).
Is it possible with currently available Facebook API's?.

A: If you manage the group, you can authorize with the user_managed_groups permission and get the feed with /group-id/feed. There is no realtime API for groups, so you have to check for new items with a Cron Job (for example).
More information and example code: https://developers.facebook.com/docs/graph-api/reference/v2.4/group/feed


text:
Q: Android: BroadcastReceiver: UNINSTALL_PACKAGE intent I need to detect when my app is being uninstalled. For that, I've seen logcat sends out UNINSTALL_PACKAGE intent, and I simply added it to existing Broadcast Receiver I have. But it just doesn't catch it, while other intent I'm listening to, TIME_TICK, works perfectly. Why?
Code currently used:
    private IntentFilter intentFilter;

static {
    intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_TIME_TICK);
    intentFilter.addAction(Intent.ACTION_UNINSTALL_PACKAGE);
}

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_UNINSTALL_PACKAGE) {
            Log.e("App", "Uninstalling");
        } else if (action.equals(Intent.ACTION_TIME_TICK){
        // this works
        }
    }
};

A:
I need to detect when my app is being uninstalled

There is no supported way to do this, for obvious security reasons.

But it just doesn't catch it

ACTION_UNINSTALL_PACKAGE is an activity action. Nothing on an Android device should be sending it as a broadcast. Hence, you cannot listen to it via a BroadcastReceiver.

A:
I 've seen logcat sends out UNINSTALL_PACKAGE intent, and I simply added it to existing Broadcast Reciever I have. But it just doesn't catch it, while other intent I'm listening to, TIME_TICK, works perfectly. Why?

Whenever your application is being uninstalled, Android OS kills all the components associated with that application as well free memory & resources. Uninstall broadcast receiver intent was to listen uninstall event of others app not for your app.
If you want to capture uninstall event of your app then there is no concept google provides, however you can do by observing data change in your file system where you need to keep monitoring changes in file system.
This solution is not going to work for all phones & different versions of Android.

A: Can't you just listen for android.intent.action.PACKAGE_REMOVED with your IntentFilter when you uninstall using ACTION_DELETE or ACTION_UNINSTALL_PACKAGE?


text:
Q: 401. "str' object has no attribute 'read' The code below produces these errors:

 'Response' object has no attribute 'read'
Please help me understand what I did wrong. I made sure un and pwd are correct
user = "un"
password = 'pwd'

datanodes = ["https://server040:25000/"]

for i, datanode in enumerate(datanodes):
    print("Checking {0}: {1}".format(i, datanode))
    try:
        print "trying"
        response = requests.get(datanode + "queries?json",auth=(user,
password), verify='certs.pem')
        print response
        data = json.loads(response.read())
        print data
        if data["num_waiting_queries"] > 0:
            print(data["num_waiting_queries"])
            for in_flight_query in data["in_flight_queries"]:
                if in_flight_query["waiting"] is True and
in_flight_query['state'] == "FINISHED":
                    cancel_url = datanode + "cancel_query?query_id=
{}".format(in_flight_query['query_id'])
                    print(cancel_url)

    except IOError as ioe:
        print ioe
    except Exception as e:
        print(e)

I have tried both json.load(reponse) and json.loads(response.read())

A: I was able to get around the issues by adding HTTPDigestAuth and changing data = json.loads(response.read()) to data = response.json()


text:
Q: Is there any way to delay the launch of a third party app? Say I have an accessibility service and I'm using it to detect when certain apps are launched. What I need is to run a few lines of code before these apps are launched. It's important that this code is executed before an app is launched not after, otherwise the code would have no effect.
What I'm currently capable of is:
App gets launched --> Accessibility service detects launch --> Accessibility service runs some code
What I need is:
App gets launched --> Accessibility service detects this launch and stops it somehow --> Accessibility service runs some code --> App now gets to launch
How do I go about doing this?


text:
Q: How to prove $v_1v_2^Tv_2=v_2v_2^Tv_1$? How can I prove
$$
v_1v_2^Tv_2=v_2v_2^Tv_1
$$
where $v_1$ and $v_2$ are all of shape $(1, n)$.
The original problem is from this paper, where Eq.4 in page 3 is defined as

But I derive something like
$$
\alpha R(\tau')\nabla_{\theta'}\log\pi_{\theta'}(\tau')(R(\tau)\nabla_\theta\log\pi_\theta(\tau)^T\nabla_\theta\log\pi_\theta(\tau))
$$
where $\alpha$, $R(\tau')$ and $R(\tau)$ are scalars. In fact I'm not so sure why I transpose the first $\nabla_\theta\log\pi_\theta(\tau)$, I do so simply because I think there should be a matrix. I hope someone could help me clarify it. Thanks in advance.

A: It is in general not true that $v_1 v_2^T v_2 = v_2 v_2^T v_1$. Try for example with $v_1 =(1,0,0), v_2=(0,0,1)$.