text:
Q: How to access a connect function from another file in another function The problem here is that the viewauthor.php considered the $conn as an undefined variable. It also gives me an error that states mysqli_query() expects parameter 1 to be mysqli, null given in in the $results line. How can I make the viewauthor.php access the $conn in the dbconnect.php file?
this is the code in db.connect.php
   <?php
    class dbconn {
    public function dbcon() {
        global $conn;
        $conn = new mysqli('localhost','root','','bookinventory') or die
        ('Error connecting to mysql' .mysqli_error());
        return $conn;

    }
}
?>

this is the code in viewauthor.php
    <?php
    require_once 'dbconnect.php';

    class author {
     $con = new dbconn();
     $conn = $con->dbcon();

    public function viewAuthor() {
    $query = ("SELECT * FROM author");
    $results = mysqli_query($conn,$query);
    $authors = array();

            while($author = mysqli_fetch_object($results)) {
            $authors[] = $author;
      }
            return $authors;
    }
 }
 ?>

A: Found problems:

*

*See $con = new dbconn(): To define properties of a class use one of the keywords public, protected, or private, static, constant, etc, followed by a normal variable declaration.
See Properties.

*See $con = new dbconn(): You can not create an object as part of a property definition. The property value must be a constant expression, not (for example) a variable, a property, or a function call. See Properties and Class Constants.

*See $results = mysqli_query($conn, $query);: Why are you receiving the error "mysqli_query() expects parameter 1 to be mysqli, null given in ..."? Because you're trying to reference $conn, but it is neither defined as parameter in the definition of viewAuthormethod - like viewAuthor($conn) {...}, nor correctly defined as a class property - if it was you'd have to reference it like this: $results = mysqli_query($this->conn, $query);.

Now I'll try to give you two correct alternatives. But only the second one would be the recommended one. And I'll try to keep my explanations simple. Mind my naming and coding conventions, including the changed table name, the page names, the require statement for the connection page, etc. And don't forget to change the database credentials in the page connection.php with yours.
But, first, some recommendations:

*

*Don't use a class for connecting to the database. Just create an including file with the proper connectivity code (see connection.php).

*Create a constructor for each class needing to access the database and define a parameter for the connection object to be passed as argument. This passing step is called dependency injection.

*Use require instead of require_once when you're including the connection.php.

*Use the object oriented mysqli, not the procedural one. To each mysqli procedural function described on php.net there is an object oriented styled one too.

*Important: Use prepared statements instead of just directly querying the database by using mysqli_query. See this too.

*Important: Read this and this for properly applying error handling. E.g. to elegantly and safely get rid of die(...), mysqli_error(), etc.

*Important: Implement an autoloader, or, a lot better, use the Composer library. Implement namespaces too. Read PSR-1, PSR-2, PSR-4 and, in time, the other recommendations from PHP-FIG as well.

Alternative 1:
In the codes bellow it becomes obvious, why this alternative is not really a good one:

*

*An object of type Author - which should actually be the representation of only one table row - is used to fetch a collection of authors. Which are even fetched as a collection of objects of type stdClass. Bad.

*An object of type Author is responsible for querying a database. Why should an object of type Author have something to do with a database, actually? Bad.

connection.php:
<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');

/*
 * Enable internal report functions. This enables the exception handling,
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
 * (mysqli_sql_exception).
 *
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
 *
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
 * Create a new db connection.
 *
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

Author.php:
<?php

class Author {

    /**
     * Database connection.
     *
     * @var mysqli
     */
    private $connection;

    /**
     *
     * @param mysqli $connection Database connection.
     */
    public function __construct(mysqli $connection) {
        $this->connection = $connection;
    }

    /**
     * Get all authors.
     *
     * @return stdClass[] The authors list.
     */
    public function getAllAuthors() {
        /*
         * The SQL statement to be prepared.
         *
         * @link http://php.net/manual/en/mysqli.prepare.php
         */
        $sql = 'SELECT * FROM authors';

        /*
         * Prepare the SQL statement for execution.
         *
         * @link http://php.net/manual/en/mysqli.prepare.php
         */
        $statement = $this->connection->prepare($sql);

        /*
         * Execute the prepared SQL statement.
         * When executed any parameter markers which exist will
         * automatically be replaced with the appropriate data.
         *
         * @link http://php.net/manual/en/mysqli-stmt.execute.php
         */
        $statement->execute();

        /*
         * Get the result set from the prepared statement.
         *
         * NOTA BENE:
         * Available only with mysqlnd ("MySQL Native Driver")! If this
         * is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in
         * PHP config file (php.ini) and restart web server (I assume Apache) and
         * mysql service. Or use the following functions instead:
         * mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
         *
         * @link http://php.net/manual/en/mysqli-stmt.get-result.php
         * @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
         */
        $result = $statement->get_result();

        // Fetch the data into a stdClass[] array.
        $rows = [];
        while ($row = $result->fetch_object()) {
            $rows[] = $row;
        }

        return $rows;
    }

    /**
     * Get an author by id.
     *
     * @param int $authorId Author id.
     * @return stdClass The author.
     */
    public function getAuthorById(int $authorId) {
        /*
         * The SQL statement to be prepared. Notice the so-called markers,
         * e.g. the "?" signs. They will be replaced later with the
         * corresponding values when using mysqli_stmt::bind_param.
         *
         * @link http://php.net/manual/en/mysqli.prepare.php
         */
        $sql = 'SELECT *
                FROM authors
                WHERE id = ?
                LIMIT 1';

        $statement = $this->connection->prepare($sql);

        /*
         * Bind variables for the parameter markers (?) in the
         * SQL statement that was passed to prepare(). The first
         * argument of bind_param() is a string that contains one
         * or more characters which specify the types for the
         * corresponding bind variables.
         *
         * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
         */
        $statement->bind_param('i', $authorId);

        $statement->execute();
        $result = $statement->get_result();

        // Fetch the data into a stdClass object.
        $row = $result->fetch_object();

        return $row;
    }

}

index.php:
<?php

require 'connection.php';
require_once 'Author.php';

$author = new Author($connection);

/*
 * ================================
 * Example 1: Get all authors.
 * ================================
 */

// Get all authors.
$theAuthors = $author->getAllAuthors();

// Print the results.
echo 'Example 1: The whole authors list:';
echo '

';
foreach ($theAuthors as $theAuthor) {
    echo $theAuthor->id . ' - ' . $theAuthor->first_name . ', ' . $theAuthor->last_name . '
';
}

echo '

';

/*
 * ================================
 * Example 2: Get an author by id.
 * ================================
 */

// Get an author by id.
$theAuthor = $author->getAuthorById(2);

// Print the results.
echo 'Example 2: One selected author:';
echo '

';
echo $theAuthor->id . ' - ' . $theAuthor->first_name . ', ' . $theAuthor->last_name . '
';

Alternative 2:
Let's change the code above to make more semantical and structural sense. For this, think of an object of type Author as an entity whose only purpose is to hold the characteristics of an author and to manipulate them on demand. This type of objects are known as domain objects and are only responsible with the business logic. See this answer. So, an Author object should have nothing to do with a database, or with any other persistence layer (session, file system, etc). It should actually be completely unaware of the place and fashion in which its properties are fetched.
The responsibility of querying the database, fetching the author characteristics (e.g. the field values of a specific row in the authors table) and assigning them to an Author object should therefore be deferred to a so-called data mapper.
So, the code in your case would look like this:
connection.php:
The same as above.
Author.php:
<?php

class Author {

    /**
     * Author id.
     *
     * @var int
     */
    private $id;

    /**
     * First name.
     *
     * @var string
     */
    private $firstName;

    /**
     * Last name.
     *
     * @var string
     */
    private $lastName;

    /**
     * Get the name as 'John, Doe'.
     *
     * @return string The name.
     */
    public function getName() {
        return $this->firstName . ', ' . $this->lastName;
    }

    /**
     * Get the id.
     *
     * @return int
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set the id.
     *
     * @param int $id Id.
     * @return $this
     */
    public function setId($id) {
        $this->id = $id;
        return $this;
    }

    /**
     * Get the first name.
     *
     * @return string
     */
    public function getFirstName() {
        return $this->firstName;
    }

    /**
     * Set the first name.
     *
     * @param string $firstName First name.
     * @return $this
     */
    public function setFirstName($firstName) {
        $this->firstName = $firstName;
        return $this;
    }

    /**
     * Get the last name.
     *
     * @return string
     */
    public function getLastName() {
        return $this->lastName;
    }

    /**
     * Set the last name.
     *
     * @param string $lastName Last name.
     * @return $this
     */
    public function setLastName($lastName) {
        $this->lastName = $lastName;
        return $this;
    }

}

AuthorMapper.php:
<?php

require_once 'Author.php';

class AuthorMapper {

    /**
     * Database connecton.
     *
     * @var mysqli
     */
    private $connection;

    /**
     * Authors collection.
     *
     * @var Author[]
     */
    private $authorsCollection = [];

    /**
     *
     * @param mysqli $connection Database connection.
     */
    public function __construct(mysqli $connection) {
        $this->connection = $connection;
    }

    /**
     * Get all authors.
     *
     * @return array Authors list.
     */
    public function getAllAuthors() {
        $sql = 'SELECT * FROM authors';

        $statement = $this->connection->prepare($sql);
        $statement->execute();
        $result = $statement->get_result();

        // Fetch the data into a stdClass[] array.
        $rows = [];
        while ($row = $result->fetch_object()) {
            $rows[] = $row;
        }

        // Fill and return the authors collection.
        return $this->createAuthorsCollection($rows);
    }

    /**
     * Get an author by id.
     *
     * @param int $authorId Author id.
     * @return Author The author.
     */
    public function getAuthorById(int $authorId) {
        $sql = 'SELECT *
                FROM authors
                WHERE id = ?
                LIMIT 1';

        $statement = $this->connection->prepare($sql);
        $statement->bind_param('i', $authorId);
        $statement->execute();
        $result = $statement->get_result();

        // Fetch the data into a stdClass object.
        $row = $result->fetch_object();

        // Crete and return an Author object.
        return $this->createAuthor($row);
    }

    /**
     * Create an Author from the given stdClass object:
     *
     * - Create an Author object.
     * - Assign a property value to the Author object for each property of the given stdClass object.
     * - Return the Author object.
     *
     * @param stdClass $row The row object.
     * @return Author The author.
     */
    public function createAuthor(stdClass $row) {
        $author = new Author();

        $author
                ->setId($row->id)
                ->setFirstName($row->first_name)
                ->setLastName($row->last_name)
        ;

        return $author;
    }

    /**
     * Create an Author[] list from the given stdClass[] list:
     *
     * - Iterate through the given stdClass[] list.
     * - Create an Author object for each list item.
     * - Assign a property value to the Author object for each property of the given stdClass object.
     * - Push the Author object to the authors collection.
     * - Return the content of the collection.
     *
     * @param array $rows Rows list as a stdClass[] list.
     * @return Author[] The authors list as an Author[] list.
     */
    public function createAuthorsCollection(array $rows = []) {
        foreach ($rows as $row) {
            $this->authorsCollection[] = $this->createAuthor($row);
        }

        return $this->authorsCollection;
    }

}

index.php:
<?php

require 'connection.php';
require_once 'AuthorMapper.php';

// Create an author data mapper.
$authorMapper = new AuthorMapper($connection);

/*
 * ================================
 * Example 1: Get all authors.
 * ================================
 */

// Get all authors.
$authors = $authorMapper->getAllAuthors();

// Print the results.
echo 'Example 1: The whole authors list:';
echo '

';
foreach ($authors as $author) {
    echo $author->getId() . ' - ' . $author->getName() . '
';
}

echo '

';

/*
 * ================================
 * Example 2: Get an author by id.
 * ================================
 */

// Get an author by id.
$author = $authorMapper->getAuthorById(2);

// Print the results.
echo 'Example 2: One selected author:';
echo '

';
echo $author->getId() . ' - ' . $author->getName();

As you see, an AuthorMapper queries the database and fetches the table rows into  a collection of objects of type stdClass. Then it maps these objects to corresponding objects of type Author, whose properties are printed, or used by certaing methods (like getName()) in order to achieve certain results.
The output of each alternative:

Used data:
CREATE TABLE `authors` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) DEFAULT NULL,
  `last_name` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `authors` (`id`, `first_name`, `last_name`)
VALUES
    (1,'Johny','John'),
    (2,'Samantha','Sam'),
    (3,'Maria','Mar');

List of resources:

*

*PHP Object Oriented Programming (OOP)

*The list of resources on MVC for advanced PHP developers

*PHPNW15: James Mallison - Dependency Injection and Dependency Inversion in PHP

*SOLID Design Principles (Code Walks)

*Tell Don't Ask and Control Coupling | Code Walks 015

*Tell Don't Ask | Code Walks 011

*Design Patterns in Object Oriented Programming

*Tom Butler's programming blog (look especially into Articles)


text:
Q: MVC5 self-hosted OWIN returns 404 I have created a simple web application using MVC5 and ASP.NET 4.5. Using that web application as the startup project works just fine when running locally. I'm trying to convert this to an OWIN self-hosted application so I have added a Console program to the project and set it as the startup project in Visual Studio (I'm using 2013 Community).
This is my Program class:
class Program
    {
        static void Main(string[] args)
        {
            using (Microsoft.Owin.Hosting.WebApp.Start<WebApp.Startup>("http://localhost:9000"))
            {
                Console.WriteLine("Press [enter] to quit...");
                Console.ReadLine();
            }
        }
    }

This runs fine and doesn't trigger any error. However when I try to reach that URL, all I get is a blank page which is actually a 404 error page (I don't have any content in the page, but looking at the network trace I see that the response is a 404).
This is the Startup class of WebApp:
public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        }
    }

Yes, it's empty because I don't have much to do (there's no authentication or database schema update to trigger). I'm sure I'm missing something obvious but I can't seem to find any article detailing what is required to make OWIN hookup correctly to a MVC5 project.

A: You cannot use self hosting OWIN with MVC 5. This is one of the limitations of MVC, currently. MVC 6 completely addresses this issue. MVC 5 has deep dependencies on the System.Web and IIS pipeline, which makes it unsuitable for running self hosted. You'll need to either wait for MVC 6, or use OWIN on top of IIS or IIS Express.
When MVC 6 ships, you'll be able to do something similar to this:
public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
}

Other web platforms, like WebAPI 2+ and SignalR 2, have already made this transition away from the System.Web Dependency, and can run on self-hosted OWIN.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue updating second orbiting body in a processing.js example I was given a processing.js example of how to orbit an object around another object by a user on gamedev.stackexchange here.
Essentially, in the example, an origin or center is established along with the cooridinates of the orbiting point:
// Logic vars
PVector origin;
float orbitRadius = 75.0;
PVector orbitVelocity;
PVector orbitPoint;
float t = 0.0;
float fps = 60.0;
float constDT = 1 / fps;

Then, they are initialized in the setup:
void setup() {
    size(400, 400);
    frameRate(fps);

    /*central point */
    origin = new PVector(width / 2.0, height / 2.0);

    /*first point and velocity of orb around center*/
    orbitVelocity = new PVector(0.0, /*-orbitRadius*/orbitRadius);
    orbitPoint = new PVector(origin.x + orbitRadius, origin.y);
}

And then the cooridinates of the orbiting point are updated each time step:
void update(float dt) {

    /*update orbit of first orb using velocity*/
    PVector accelerationTowardsOrigin = PVector.sub(origin, orbitPoint);
    orbitVelocity.add(PVector.mult(accelerationTowardsOrigin, /*dt*/constDT));
    orbitPoint.add(PVector.mult(orbitVelocity, /*dt*/constDT));

}

(I have omitted the drawing code as it is not relevant.) I have been attempting to update the code to add additional orbiting ellipses, which can be seen here.  I have been able to successfully add a second point along orbit around the central point by adding these additional variables
/*Logic vars for second point on circle*/
PVector orbitPoint2;
PVector orbitVelocity2;
float circAngle;
float xcoord_along_circle;
float ycoord_along_circle;

and adding this to setup:
    //Added in setup
    /*second orbiting point for second orb*/
    /*Calculate second point along circle*/
    circAngle = 90.0;
    xcoord_along_circle = orbitRadius * cos(circAngle) + origin.x;
    ycoord_along_circle = orbitRadius * sin(circAngle) + origin.y;

    /*second point and velocity of orb around center*/
    orbitVelocity2 = new PVector(xcoord_along_circle,orbitRadius);
    orbitPoint2 = new PVector(xcoord_along_circle, ycoord_along_circle);

However, when I update the cooridinates of the second ellipse each point it results in a stretched out, elongated orbit:
 /*update orbit of second orb using velocity*/
    PVector accelerationTowardsOrigin2 = PVector.sub(origin,orbitPoint2);
    orbitVelocity2.add(PVector.mult(accelerationTowardsOrigin2,/*dt*/constDT));
    orbitPoint2.add(PVector.mult(orbitVelocity2, /*dt*/constDT));

I believe I am doing everything correctly, and replicating the necessary steps. How can I correct this so that the orbit is not distorted?

A: At this point you're duplicating code all over the place rather than modularising your code by capturing the orbiting bodies in a class that you can simply build a million times. I'd suggest first rewriting your code to something like
class OrbitalBody {
    float ox, oy, x, y, m, a;
    OrbitalBody(float originX, float originY, float startX, float startY, float mass, float speed) {
      ox = originX;
      oy = originY;
      x = startX;
      y = startY;
      m = mass;
      a = speed / 200;
    }
    void update() {
      float nx = (x-ox) * cos(a) - (y-oy) * sin(a),
            ny = (x-ox) * sin(a) + (y-oy) * cos(a);
      x = nx+ox;
      y = ny+oy;
    }
    void draw() {
      fill(255);
      ellipse(x,y,m,m);
    }
}

ArrayList<OrbitalBody> bodies = new ArrayList<OrbitalBody>();
int mx, my;

void setup() {
    size(420, 420);
    mx = width/2;
    my = height/2;
    bodies.add(new OrbitalBody(mx, my, mx-50, my, 10, 10));
    bodies.add(new OrbitalBody(mx, my, mx-100, my, 20, 3));
    bodies.add(new OrbitalBody(mx, my, mx-120, my, 5, 13));
    bodies.add(new OrbitalBody(mx, my, mx-170, my, 15, 6));
    bodies.add(new OrbitalBody(mx, my, mx-190, my, 10, 9));
    ellipseMode(CENTER);
}

void draw() {
    background(0);
    fill(100,100,0);
    ellipse(mx,my,50,50);
    for(OrbitalBody b: bodies) {
        b.update();
        b.draw();
    }
}

demonstrator: http://jsfiddle.net/XhPzL/34


text:
Q: if/else statement not working properly So this if/else statement is for a simple login form with Google Recaptcha attached. I've got the Recaptcha part working fine, it's just that when I got to enter my username and password, even if correct, I can't seem to login. This only occurred once I added the ReCaptcha. The only thing the ReCaptcha changed was another condition for the if statement to check for and shouldn't be causing issues.
Here's my validate.php file for reference, the if statement in question is at the bottom:
<?php

if (isset($_POST['submit'])) {
    $userid = $_POST["userid"];
    $password = $_POST["password"];
    $secretkey = "_SECRET_KEY_";
    $responsekey = $_POST["g-recaptcha-response"];
    $useripaddress = $_SERVER["REMOTE_ADDR"];

    $url = "https://www.google.com/recaptcha/api/siteverify?secret={$secretkey}&response={$responsekey}&remoteip={$useripaddress}";
    $response = file_get_contents($url);
    // $response = json_decode($response);
    echo $response;
}

require_once("scripts/thecrab.php"); // This connects to the db

$userid = htmlspecialchars($_POST['userid']);
$password = htmlspecialchars($_POST['password']);

$query = "SELECT userid from users where userid = ? and password = PASSWORD(?)";
$stmt = $pdo->prepare($query);
$stmt->execute([$userid, $password]);

if ($stmt->rowCount() && $response->success === "true") {
    $_SESSION['valid_recipe_user'] = $userid;
    echo "
Log In Successful

\n";
    echo "\n";
} else {
    echo "
Sorry, your user account was not validated.

\n";
    echo "Try again
\n";
    echo "Return to Home\n";
}

Here's the exact if statement and condition in question:
if ($stmt->rowCount() && $response->success === "true") {
    // Successful Login. Meaning the userid and password are in the database AND the Google ReCAPTCHA response->success has the value of EXACTLY true.
} else {
    // Incorrect Login
}

Even with a correct username and password that does exist in the database, it will not execute the if statement and jumps to the else, which does not log me in.

A: Boolean != String
Change
$response->success === "true"

to
$response->success === true

Triple equal checks the datatype as well. So boolean true will not be equal to string 'true'. BTW, you need not type check here. Simple == will do!

Or to be frank, this is just enough:
if ($stmt->rowCount() && $response->success)

A: In your comparison, you have $response->success === "true". This compares not by value, but by type.
If success is bool, you can use $response->success === true. However, simpler and enough is $response->success == true, which will auto-convert string / int (whatever) from $response->success to bool


text:
Q: Einstein notation: can a free index be upper in one term and lower in another term? Consider a linear combination of terms written using Einstein notation.
Consider one free index in the linear combination: is it necessary that the index is upper in all terms or lower in all terms, or not?
Equivalently is it possible to have the same free index, but in one term it is a upper index and in the other it is a lower index?
For example, is it possible to have the following expression?
$$A_\mu+B^\mu$$
Or this is forbidden in einstein notation, and one free index can only appear upper in all terms or lower in all terms?

A: Short answer: No.
When dealing with contravariant vectors (also just vectors $\rightarrow$ upper indices) and covariant vectors (also covectors $\rightarrow$ lower indices), you can only sum vectors that transform the same way with respect to change of basis.
Think of a vector as a column vector and a covector as a row vector, to make this simple to assimilate.
Also, a contravariant vector can only be contracted with a contravariant vector, corresponding to the summation of the products of their coefficients. On the other hand, when there is a fixed coordinate basis (or when not considering coordinate vectors), one may choose to use only subscripts.

A: Well, you can write down the expression if you want to, and calculate its value, but there is a problem: it doesn't have any well defined transformation law when you change coordinates. Say you switch to a different frame through a change-of-basis matrix $C^\mu{}_\nu$. The components of a contravariant vector $A^\mu$ change to $C^\mu{}_\nu A^\nu$ and those of a covector $B_\mu$ change to $B_\nu (C^{-1})^\nu{}_\mu$, so if you form a combination like
$$D^\mu = A^\mu + B^\mu,$$
in a new basis we have
$$D'^\mu = C^\mu{}_\nu A^\mu + C^\mu{}_\nu B^\mu = C^\mu{}_\nu (A^\nu + B^\nu)= C^\mu{}_\nu D^\nu,\tag{1}$$
so its components will also change like a vector. But under a change of basis, the expression $A^\mu + B_\mu$ changes to
$$C^\mu{}_\nu A^\mu + (C^{-1})^\nu{}_\mu B_\nu$$
which does not obey any simple transformation law. In particular, and this is the important part, the way it transforms depends on the values of $A^\mu$ and $B_\mu$ individually instead of simply depending on $A^\mu + B_\mu$; compare with $(1)$ above, where the transformation just depends on $D^\mu$.
It's for this reason that the notation doesn't let you give it a name: both $D^\mu = A^\mu + B_\mu$ and $D_\mu = A^\mu + B_\mu$ would be wrong, because the position of the index on $D$ is in both cases implying a transformation law that is not the one $D$ actually obeys.


text:
Q: Create sheets based on range (ignoring empty cells) I'm trying to create new sheets named after a range of values after I push a button, but I get the following error: "Method 'Range' of object'_Worksheet failed" when I set MyRange
My current sheet is "V-Class GC" and the starting cell is U2
Here's what I've got so far:
Dim MyCell As Range, MyRange As Range

Set MyRange = Range(Sheets("V-Class GC").[u2], Sheets("V-Class GC").Cells(Rows.Count, "U").End(xlUp))

For Each MyCell In MyRange
    If Len(MyCell.Text) > 0 Then
        Sheets.Add after:=Sheets(Sheets.Count)
        Sheets(Sheets.Count).Name = MyCell.Value
    End If
Next MyCell

Thanks!

A: You should refer to a range with method .Range of the Sheets class.
Set MyRange = Range(Sheets("V-Class GC").Range("U2"), Sheets("V-Class GC").Cells(Rows.Count, 21).End(xlUp))

When you are trying to understand what's happening when you refer to a range, try to select it and work with a single cell at time, in your case you could try to select the single cell range, using Range.[u2] you would quickly found the error because of the error raised by excel.

A: Try
Dim Foo As Variant, FooRange As Range

Sheets("V-Class GC").Select
Set FooRange = Range("u2", Range("u2").End(xLDown))

For Each Foo In FooRange
    If Len(Foo.Value) > 0 Then
        Sheets.Add after:=Sheets(Sheets.Count)
        Sheets(Sheets.Count).Name = Foo.Value
    End If
Next

Your problem is likely coming from how you define your range to iterate.


text:
Q: Numpy array in panda dataframe from json I have a JSON file containing properties of some mathematical objects (Calabi-Yau manifolds). These objects are defined by a matrix and a vector, and two additional properties I am storing are the matrix size (such that it does not need to be computed again) and the Euler number of the manifold (some integer). In total there are roughly 1 million entries, the biggest matrix is 16 x 20.
I would like to convert the matrix and vectors to numpy arrays. Hence I was wondering if it is possible to do it directly when loading from json, or at least how to convert afterwards. The reason for converting is that I will need in any case some functions from numpy later, but I also hope (especially if the conversion is done on loading) that it will speed up my code: for the moment loading the complete dataset takes roughly 90 seconds (a previous loading using json module required only 20 s; I will open another thread on this question if using numpy does not improve).
Here is a minimal working code:
import pandas as pd
import numpy as np

json = '''
{"1":{"euler":2610,"matrix":[[6]],"size":[1,1],"vec":[5]},
"2":{"euler":2190,"matrix":[[2,5]],"size":[1,2],"vec":[6]},
"4":{"euler":1632,"matrix":[[2,2,4]],"size":[1,3],"vec":[7]},
"6":{"euler":1152,"matrix":[[2,2,2,3]],"size":[1,4],"vec":[8]},
"7":{"euler":960,"matrix":[[2,2,2,2,2]],"size":[1,5],"vec":[9]},
"8":{"euler":2160,"matrix":[[2],[5]],"size":[2,1],"vec":[1,4]},
"9":{"euler":1836,"matrix":[[0,2],[2,4]],"size":[2,2],"vec":[1,5]}}
'''

data = pd.read_json(json, orient="index")
data.sort_index(inplace=True)

My first guess was to use the numpy argument, but it fails with an error:
>>> data = pd.read_json(json, orient="index", numpy=True)
ValueError: cannot reshape array of size 51 into shape (7,4,2,2)

Then I have tried giving the dtype argument but it does not look like changing anything (my hope was that by using a numpy type it would convert the list to an array):
>>> dtype = {"euler": np.int16, "matrix": np.int8, "vector": np.int8,
...          "size": np.int8, "number": np.int32}
>>> data = pd.read_json(json, orient="index", dtype=dtype)
>>> type(type(data["matrix"][1]))
list

For the conversion I was wondering if there is a more subtle (and perhaps more efficient) way than brutal conversion:
data["matrix"] = data["matrix"].apply(lambda x: np.array(x, dtype=np.int8))


text:
Q: How to convert a non-templated beam job to templated job and run it on GCP Dataflow runner? I was able to run the non-templated beam job directly on the GCP dataflow runner by using the below command :
java -jar <jar_name>
--runner=DataFlowRunner
--gcpTempLocation=gs://some/gcs/location
--stagingLocation=gs://some/gcs/location/stage
--tempLocation=gs://some/gcs/location/temp
--region=<region_name>
--project=<project_name>
--subnetwork=<subnet_name>
--jobName=<job_name>

I wanted to templatize the same job by using the below command to stage the template in the gcs bucket :
java -jar <jar_name>
--runner=DataFlowRunner
--gcpTempLocation=gs://some/gcs/location
--stagingLocation=gs://some/gcs/location/stage
--templateLocation=gs://some/gcs/location/templates/<job_name>
--region=<region_name>
--project=<project_name>

but I am receiving the below error while creating the job template instance:
18:11:05.004 [main] INFO org.apache.beam.runners.dataflow.DataflowRunner - Template successfully created.
Exception in thread "main" java.lang.UnsupportedOperationException: The result of template creation should not be used.
    at org.apache.beam.runners.dataflow.util.DataflowTemplateJob.getJobId(DataflowTemplateJob.java:41)
    at org.apache.beam.runners.dataflow.DataflowPipelineJob.getJobWithRetries(DataflowPipelineJob.java:559)
    at org.apache.beam.runners.dataflow.DataflowPipelineJob.getStateWithRetries(DataflowPipelineJob.java:540)
    at org.apache.beam.runners.dataflow.DataflowPipelineJob.waitUntilFinish(DataflowPipelineJob.java:324)
    at org.apache.beam.runners.dataflow.DataflowPipelineJob.waitUntilFinish(DataflowPipelineJob.java:253)
    at org.apache.beam.runners.dataflow.DataflowPipelineJob.waitUntilFinish(DataflowPipelineJob.java:212)
    at org.apache.beam.runners.dataflow.DataflowPipelineJob.waitUntilFinish(DataflowPipelineJob.java:206)
    at com.gojek.de.jobs.EventFilterJob.main(EventFilterJob.java:72)

and upon running the dataflow job from the GCS template, the dataflow job runner cannot launch the job instance from the template.
I am able to see the template creation at the GCS bucket. I am not sure, why the job run failed.
also, can we directly convert a non-template beam job to a template job?
Note: I cannot run the maven command given in the document as our project is Gradle based.

A: When you are creating a template, you can not use DataflowPipelineJob::waitUntilFinish, as there is no job attached to that run -- which seems to be the case here.
Take a look at the WordCount example to see an example of a working template.


text:
Q: IF not exists not working properly I have a problem with a SQL Server stored procedure. I am trying to check if there is already data with the same id in both tables.
ALTER PROCEDURE [dbo].[Objective_Comment_Insert]
    @CompanyName AS NVARCHAR(100)
AS
BEGIN
    IF NOT EXISTS (SELECT *
                   FROM dbo.[SB$Objective Comment] oc, [dbo].[comments] cc
                   WHERE CONVERT(INT, oc.[Employee No_]) = (SELECT u1.employee_no
                                                            FROM c0_intranet.dbo.users u1
                                                            WHERE u1.user_id = cc.user_id)
                     AND oc.[No_] = cc.comment_id)
    BEGIN
        INSERT INTO dbo.[SB$Objective Comment]([Comment By], [Comment], [Date Created],
                                               [No_], [Comment On], [Employee No_])
            SELECT
                (SELECT u1.employee_no
                 FROM c0_intranet.dbo.users u1
                 WHERE u1.user_id = cs.user_id
                ),
                CASE
                   WHEN cs.comment IS NULL
                      THEN ''
                      ELSE cs.comment
                END,
                CASE
                   WHEN cs.date_created IS NULL
                      THEN FORMAT(GETDATE(), 'yyyy-MM-dd')
                      ELSE FORMAT(cs.date_created, 'yyyy-MM-dd')
                END,
                cs.comment_id,
                CASE
                   WHEN cs.comment_on IS NULL
                      THEN 0
                      ELSE cs.comment_on
                END,
                (SELECT u1.employee_no
                 FROM dbo.users u1
                 WHERE u1.user_id = cs.user_id)
            FROM
                dbo.comments cs
    END
    ELSE
    BEGIN
        UPDATE NAV_2017.dbo.[SB$Objective Comment]
        SET [Comment By] = (SELECT u1.employee_no
                            FROM dbo.users u1
                            WHERE u1.user_id = cs.user_id),
            [Comment] = CASE
                           WHEN cs.comment IS NULL
                              THEN ''
                              ELSE cs.comment
                        END,
            [Date Created] = CASE
                                WHEN cs.date_created IS NULL
                                   THEN FORMAT(GETDATE(), 'yyyy-MM-dd')
                                   ELSE FORMAT(cs.date_created, 'yyyy-MM-dd')
                             END,
            [No_] = cs.comment_id,
            [Comment On] = CASE
                              WHEN cs.comment_on IS NULL
                                 THEN 0
                                 ELSE cs.comment_on
                           END,
            [Employee No_] = (SELECT u1.employee_no
                              FROM dbo.users u1
                              WHERE u1.user_id = cs.user_id)
        FROM dbo.comments cs, NAV_2017.dbo.[SB$Objective Comment] oc
        WHERE
            CONVERT(INT, oc.[Employee No_]) = (SELECT u1.employee_no
                                               FROM dbo.users u1
                                               WHERE u1.user_id = cs.user_id)
            AND oc.[No_] = cs.comment_id
    END
END

When it is executed for the first time, there is no data in second table and it works after I add another record in first table it doesn't insert it into second table but there is no errors.
This is when I execute the procedure inside exists
This is data from table comments

A: If I properly reconstructed your logic, this query is equal to yours:
select 1
from [dbo].[comments] cc
    join c0_intranet.dbo.users u1 on u1.user_id = cc.user_id
    join dbo.[SB$Objective Comment] oc on oc.[No_] = cc.comment_id and CONVERT(int, oc.[Employee No_] = u1.employee_no

and if so, it will always return rows if there is any data already copied to dbo.[SB$Objective Comment], try replacing with this:
select 1
from [dbo].[comments] cc
    join c0_intranet.dbo.users u1 on u1.user_id = cc.user_id
    left outer join dbo.[SB$Objective Comment] oc on oc.[No_] = cc.comment_id and CONVERT(int, oc.[Employee No_] = u1.employee_no
where oc.[No_] is null

A: I think your approach is wrong here and you should be looking at a trigger rather than a procedure. Specifically I think you have inserted 6 rows to comments, executed the procedure then inserted another row to comments and then another execute of the procedure. The problem is that at the first call the exists test fails (ie it does not exist) so comment is inserted. On the second call the exists test passes (6 records do exist) so the insert is not done. The procedure cannot know what has been inserted to comments which is why a trigger (which does know what has been inserted) would be my choice together with a suitable exists test for insertion into comment.


text:
Q: Обернуть подстроки в HTML теги, Python Как я могу обернуть подстроки в строке в Python, в необходимые HTML теги, к примеру, есть строка:

Tite Post
```
include you code here
```

В которой, необходимо заменить строку между двумя группами символов ``` на теги <code> и </code> соответственно.

A: как на счет примитивной регулярки?
import re

In [7]: print(s)

<P>
Tite Post
```
include you code here
```
</p>

In [8]: print(re.sub(r'```(.*?)```', r'\1', s, flags=re.S|re.M))

Tite Post

include you code here

PS вложенные случаи правильно обрабатываться не будут, но в вашем случае это невозможно т.к. нет возможности отличить начало блока от конца


text:
Q: Looking for tips: building a workstation around Xen and GPU pass-through I'm building my new home machine right now and as usual this will be a heavily overloaded workstation that will serve as development and testing machine, file server and game console (plus I'm adding TV cards and multimedia streaming for my home network).
Since these use cases work against each other (file server is unavailable when the machine is used as game console), I'm heavily considering the use of Xen to provide everything at once. Performance shouldn't be an issue in general, but the game console use case definitely requires direct access to a GPU.
Therefore I have several questions:

*

*is this feasible in general?

*is the GPU passthrough usable enough with non-server GPUs?

*when buying, what technologies should I look for on the motherboard
(most likely choosing Gigabyte + Intel CPU again)

*is there some virtualization technology creeping on the horizon that
is worth waiting for?

*how good is Xen at dividing resources?

*

*the file-server and multimedia-streaming portion of the workstation
has to work even if the game console part is eating 100% of its
resources and vice-versa

*the system will run on top of 8 disks with software Raid6 and LVM,
should I buy a dedicated disk for the game console portion of
the system?

*

*I have read about some problem with Xen and I/O performance

Any input will be greatly appreciated.
P.S. I won't mind using other technology then Xen, but I'm unaware of any other virtualization platform that supports GPU passthrough.

A: The information out there about PCI passthrough is terribly outdated and unhelpful.
I have an HD 7850, and a junk PCI vga-only Nvidia card that has to be a decade old.  Neither of these devices support Function-Level Reset.  They both work flawlessly being passed-through to DomUs; I run my Domain0 headless with no graphics card, both of my cards are sent to pciback at boot up via a kernel argument.
Xen is quite good about assigning resources to a VM and not allowing access to other resources; you can pin your vcpus to pcpus (cores, threads) and assign dedicated memory.  Going with a high end Nvidia, you may have some work cut out for you- but it's hard to say since the papers/writeups that say that also say things like Function Level Reset is a necessity: it no longer is.

A: The critical part in your setup is 3D performance.
I've worked quite a bit with Xen 2-3 years ago - resource allocation worked fine back then and I'm sure that the technology has improved since. Everything but gaming either uses very few resources (file serving, streaming...) or isn't real-time critical (compiling on the dev system, etc).
I havn't done GPU passthrough, but cursory googling doesn't indicate
that it works reliably, tweaking is required. Basically, it won't be plug&play - you are pretty much guaranteed that a few/some/many games won't work.
The most reliable option IMHO would be to use Win7 as a host and for games, and run the other services as virtual machines via VirtualPC or VirtualBox. Its not the most elegant solution (everything depends on Windows, every reboot means stopping all the VMs, etc.), but if you want gaming that Just Works, thats the way to go (other than using a second computer).

A:
Is this feasible in general?

Yes. I have rencently performed Xen VGA passthrough and it worked fine. Take a look at the following video:
http://www.youtube.com/watch?v=Gtmwnx-k2qg

Is the GPU passthrough usable enough with non-server GPUs?

Yes and no. Officially, only NVDIA Quadro FX 3800, 4800 and 5800 are supported, but I've successfully used a NVIDIA GeForce GTX 460 as in the previous video and Teo En Ming used a GeForce 8400 GS. It really depends on the graphic card.

When buying, what technologies should I look for on the motherboard (most likely choosing Gigabyte + Intel CPU again)

You should make sure the chipset support I/O MMU (AMD-Vi/VT-d), that the CPU support AMD-V/VT-x and that the graphic card support function level reset (FLR).
Note that this technique is not yet mature and it is not guaranteed to work until you try it!

A: Depending on the games you want to run, a better option may be to use Wine on top of Linux: check out the Wine Application Database, plus there are commercial versions of Wine that may provide better compatibility. You don't even need a Windows license.
In a way, Wine provides GPU pass-through, but it's at the Windows API level rather than at the PCI level. 3D performance is often comparable between Windows and Linux+Wine.

A: Based on my experience with Xen, here the Q/A:

*

*Is this feasible in general?
Yes, given the right hardware and configuration.

*Is the GPU passthrough usable enough with non-server GPUs?
Yes, there are plenty of user reports who use typically AMD cards for VGA passthru and gaming under Windows.

*When buying, what technologies should I look for on the motherboard (most likely choosing Gigabyte + Intel CPU again)?
VT-d (also called IOMMU or AMD-V by AMD) is an absolute must. With Intel CPUs both the CPU and the motherboard/BIOS must support VT-d. (Some old Intel chipset/CPU configurations also support VT-d, but that's not something you want to use for a modern system.) Look here: http://wiki.xen.org/wiki/VTdHowTo. In addition, make sure you got a tested and proven graphics card. Otherwise it may not work. See XenVGAPassthroughTestedAdapters for reference, though the list is not complete.
Be very careful with the hardware selection and - if possible - buy from vendors who support Linux and specify VT-d / IOMMU in their technical specifications. Why? Because a BIOS update can easily brick your system. In any case, make sure which BIOS version supports VT-d, and don't upgrade unless you got a very good reason. Also, beware of vendors with no Linux experience - their answers can be misleading (to put it politely).

*Is there some virtualization technology creeping on the horizon that is worth waiting for?
Both KVM and VMware are making some efforts to reproduce what Xen is doing with VGA / PCI passthrough. Some KVM and VMware users have reported success with VGA passthru, more so with PCI passthru. I'm not familiar with Microsoft's Hyper-V, but I've seen reports that it also supports some sort of VGA passthru. I don't know how good Microsoft supports Linux on Hyper-V.

*How good is Xen at dividing resources?
It shines! At default settings it works great with balancing the CPU resources. It can be easily fine-tuned, but there really isn't much to do except reserving a fixed amount of memory for dom0 and perhaps giving it a little higher priority in the scheduler. The only weak point I could find is network configuration - it can be tricky and I still have to solve some minor issues.

*The file-server and multimedia-streaming portion of the workstation has to work even if the game console part is eating 100% of its resources and vice-versa - A: I haven't seen problems with that, and in any event it can be tuned. Give dom0 enough resources.

*The system will run on top of 8 disks with software Raid6 and LVM, should I buy a dedicated disk for the game console portion of the system?
Xen works very well with LVM. However, in a Windows domU it's important to install the GPLPV disk driver to get good performance! You also have the option of passing through a SATA controller to the guest so it gets direct access to the hardware. If ~140-240MB/s file transfer speed between an SSD and striped LVM disks is acceptable, then I wouldn't bother adding a dedicated disk for gaming. Your RAID/LVM combo should do OK.

*I have read about some problem with Xen and I/O performance - A: These reports may have been based on file based storage, which performs poor with other hypervisors too. Using LVM should provide good performance, as long as dom0 has sufficient RAM and CPU resources to handle I/O. So far I've never noticed any I/O problem, even under 100% CPU load of all cores (i7 3930K 6-core CPU).


text:
Q: MySQL SUM Amount per month and group by caterory I have table:
User nvarchar(30)
Date datetime
Total decimal(8,2)
And i need to get data per month like this:

I can get it this way (without month columns):
SELECT User, MONTHNAME(FROM_UNIXTIME(Date)) as month, SUM(Total) as total FROM `wp_banking_expenses` group by month,User

But i need it to make as on image above...

A: use conditional aggregation using case when expression
select user,max(case when month='January' then total end) as Jan,
max(case when month='February' then total end) as Feb,
max(case when month='March' then total end) as Mar,
max(case when month='April' then total end) as Apr,
max(case when month='May' then total end) as May,
max(case when month='June' then total end) as June,
----
from
(
SELECT User, MONTHNAME(Date) as month, SUM(Total) as total
FROM `wp_banking_expenses`
group by month,User
)A group by user

A: You can try to use condition aggregate function.
SELECT  User,
        SUM(CASE WHEN MONTHNAME(Date) =  'January' THEN Total END) as Jan,
        SUM(CASE WHEN MONTHNAME(Date) =  'February' THEN Total END) as Feb,
        SUM(CASE WHEN MONTHNAME(Date) =  'March' THEN Total END) as Mar,
        SUM(CASE WHEN MONTHNAME(Date) =  'April' THEN Total END) as Apr,
        SUM(CASE WHEN MONTHNAME(Date) =  'May' THEN Total END) as May,
        SUM(CASE WHEN MONTHNAME(Date) =  'June' THEN Total END) as JUN,
        SUM(CASE WHEN MONTHNAME(Date) =  'July' THEN Total END) as JUL,
        SUM(CASE WHEN MONTHNAME(Date) =  'August' THEN Total END) as AUG,
        SUM(CASE WHEN MONTHNAME(Date) =  'September' THEN Total END) as SEP,
        SUM(CASE WHEN MONTHNAME(Date) =  'October' THEN Total END) as OCT,
        SUM(CASE WHEN MONTHNAME(Date) =  'November' THEN Total END) as NOV,
        SUM(CASE WHEN MONTHNAME(Date) =  'December' THEN Total END) as DEC
FROM `wp_banking_expenses`
group by User


text:
Q: SWRevealController not calling UITableViewDelegate methods easily I'm using the SWRevealController for displaying a slideout menu and the table view datasource is working fine, however the delegate methods that requires user interaction are not being called easily.
For example the method didSelectRowAtIndexPath basically doesn't work and didHighlightRowAtIndexPath works only if the user does a long press.
Why is it happening? Does it have any solution?


text:
Q: Namespace aliasing in F#? I have a name clashing problem while opening some .Net assemblies in my F# code using
open System.IO

The only option I found and use now is to provide the full names of types for conflicting types, but this is a little bit boring.
Is there any possibility to define an alias for .Net namespace in F# to prevent name clashing?

A: F# does not support aliasing of namespaces - only modules and types. So, to resolve the conflicts between .NET assemblies, you will, unfortunatelly, need to define aliases for all the types you're using.
This may be slightly easier thanks to the fact that F# type aliases are viewed as normal type declarations (by the F# compiler, not by the runtime). This means that, unlike with C# using keyword, you can define them in a spearate file:
// Aliases.fs
namespace SysIO

// Open the 'System' namespace to get a bit shorter syntax
// ('type File = File' is interpreted as discriminated union)
open System

type File = IO.File
type Directory = IO.Directory

In the rest of your application, you can now use SysIO.File. You still have to write the aliases, but at least you don't have to do that in every file...


text:
Q: ngmin not working properly My Grunt file looks like:
"use strict"

module.exports = (grunt) ->
  require("load-grunt-tasks") grunt
  # Project configuration.
  grunt.initConfig
    appConfig:
      # configurable paths
      app: "app"
      server: "server"
      dist: "dist"

    # ngMin
    ngmin:
      dist:
        files: [
          cwd: '<%= appConfig.app %>/scripts'
          src: ['**/*.js']
          dest: ['<%= appConfig.dist %>/scripts']

        ]

But when I run it, I get:
Running "ngmin:dist" (ngmin) task
Warning: Arguments to path.join must be strings Use --force to continue.

What am I doing wrong?

A: The destination dest should be a single folder, not a list:
                dest: '<%= appConfig.dist() %>/scripts'

Not:
                dest: [ '<%= appConfig.dist() %>/scripts' ]


text:
Q: Is Magnetic force really the relativistic correction for electrostatic force? Imagine two charges (aligned vertically) with a separation $r$ in a spaceship moving with a velocity $v$ with respect to earth.
In the spaceship frame, the charges are stationary with a force $$F′=\left(\frac{1}{4πϵ_0}\right)×\frac{q_1q_2}{r^2} $$
If the force between the charges in earth frame is denoted as F, then $$F=\frac{F'}{\gamma}$$
The force is less as seen from the earth frame such that it accounts for time dilation. Many sources say that this reduction is due to the magnetic force which opposes the electrostatic force.
But if we subtract the magnetic force from the electrostatic force, the force as seen from the earth is $$F=\left(\frac{1}{4πϵ_0}\right)×\frac{q_1q_2}{r^2}-\frac{\mu_0}{4\pi}×\frac{q_1q_2v^2}{r^2}$$
simplifying this, we get $$F=\frac{F'}{\gamma^2}$$
But shouldn't it be $F=\frac{F'}{\gamma}$?
Where have I gone wrong?  Or is the idea that magnetic force is the relativistic correction for electric force incorrect?

A: The problem is that you considered an incorrect version for both the electric field and the magnetic field from the standpoint of the observer on the earth. The correct form, according to Resnick, is that the electric field, as well as the magnetic one, is measured to be increased by the gamma factor compared to those measured in the rest frame of the charges. Indeed, you have $E=\gamma E'$ and $B=vE/c^2=v\gamma E'/c^2$. Therefore, you ought to write:
$$F=Eq_1-q_1vB=(\gamma E')q_1-q_1v(\frac{v}{c^2}E)=(\gamma E')q_1-q_1v(\frac{v}{c^2}\gamma E')$$
$$=(\frac{\boldsymbol{\gamma}}{4πϵ_0})×\frac{q_1q_2}{r^2}-\frac{\boldsymbol{\gamma}}{4πϵ_0}×\frac{q_1q_2v^2}{c^2r^2}\space.$$
Then, we have:
$$F=\frac{F'}{\gamma}$$

A: For the two particles, as seen from Earth, time goes slower while their masses increase. Propper acceleration (about which we talk) is Lorenz invariant.
Now $a=\frac{F}{m}$. Inside the rocket, for each particle, $a=\frac{F_{el}}{m}$. As seen from Earth $a'=\frac{F_{el+mag}}{\gamma m}$. If the force as seen from Earth decreases in the way as the books state, $F'=\frac{F}{\gamma}$, then $a'=\frac{F}{{m\gamma}^2}$. So it seems that $a'$ doesn't equal $a$. But since $a$ is defined as $\frac{dx}{{dt}^2}$ there is a factor $\frac{1}{{\gamma}^2}$ introduced in $a'$ too (as on the right hand side of the expression for $a'$) because $dx$ is the same for someone on Earth and someone in the rocket. So both accelerations are equal as they should be.
So something has to be wrong with your expression. I can't tell you what though.
Is maybe the idea wrong that you can add the electric force and the magnetic force to obtain $F'$? After all, this is a classical calculation that can be done even in the time of Maxwell. I think this is indeed the case. So there is nothing wrong with your calculation by itself, but by its implementation in SR. So you can't use it to derive SR from it.
As I already stated in my comments, seen from the Earth space in the direction of motion of the rocket is contracted. This causes the electric field and magnetic field to be contracted too. The density of field lines increases. Hence the electric and magnetic fields are not how you have written them in the formula you ask about. In a classical view (in the time of Maxwell) your calculation would have been right. But in the context of SR it breaks down. This is in fact what has motivated Einstein. He said that acceleration has to be the same in all reference frames. Note that it not the force that has to be equal in both frames. The force decreases by a factor $\gamma$ while the mass increases by a factor $\gamma$, so the acceleration will stay the same. The fact that your formula doesn't give the same acceleration in both frames

A: The force between 2 electrons moving parallel at speed V measured as a fraction of the speed of light, is √[1−V²] less than if they were stationary.  You can either explain this by saying that due to relativity the electric force is reduced by this factor, or you can say that the electric force remains the same, but there is a magnetic force of 1 − √[1−V²].
The magnetic force between an electron and an infinitely long current-carrying wire, is a different situation.  Trying to explain this using just the effect above gives the wrong answer.  If you were to assume that the magnetic force between individual electrons was 1 − [1−V²] = V², then you would get the right answer, but that would not be a proper explanation.  I think that is the cause of your confusion.
Do not be conned by the other comments and answers, as physics textbooks invariably print nonsense on this subject.


text:
Q: Listview returns empty Good day, I'm trying to build a book shelf with a horizontal list inside a list view but when the app runs, the listview is blank.
What am i missing?
Here's my code (and some code from a tutorial which i was using as a guide)
ListBook.java
public class ListBooks extends ActionBarActivity {

    ListView listView;
    private VerticalAdapter verListAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_books);

        listView = (ListView)findViewById(R.id.listbooks);
        BookItem book1 = new BookItem("Fist of Fury");
        BookItem book2 = new BookItem("Fist of the fists");
        BookItem book3 = new BookItem("Enders game");
        BookItem book4 = new BookItem("Lovers");

        ArrayList<BookItem> arrayList = new ArrayList<BookItem>();
        arrayList.add(book1);
        arrayList.add(book2);
        ArrayList<BookItem> list = new ArrayList<BookItem>();
        list.add(book3);
        list.add(book4);
        ArrayList<ArrayList<BookItem>> group = new ArrayList<ArrayList<BookItem>>();
        group.add(arrayList);
        group.add(list);
        verListAdapter = new VerticalAdapter(this, R.layout.activity_book_list, group);
        listView.setAdapter(verListAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_list_books, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private class VerticalAdapter extends ArrayAdapter<ArrayList<BookItem>> {
        private int resource;

        public VerticalAdapter(Context _context, int _ResourceId,
                               ArrayList<ArrayList<BookItem>> _items) {
            super(_context, _ResourceId, _items);
            this.resource = _ResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rowView;

            if (convertView == null) {
                rowView = LayoutInflater.from(getContext()).inflate(resource,
                        null);
            } else {
                rowView = convertView;
            }

            HorizontalListView hListView = (HorizontalListView) rowView
                    .findViewById(R.id.sublistview);
            HorizontalAdapter horListAdapter = new HorizontalAdapter(
                    getContext(), R.layout.listitem, getItem(position));
            hListView.setAdapter(horListAdapter);

            return rowView;
        }
    }

   private class HorizontalAdapter extends ArrayAdapter<BookItem> {

        private int resource;

        public HorizontalAdapter(Context _context, int _textViewResourceId,
                                 ArrayList<BookItem> _items) {
            super(_context, _textViewResourceId, _items);
            this.resource = _textViewResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View retval = LayoutInflater.from(getContext()).inflate(
                    this.resource, null);

            TextView topText = (TextView) retval.findViewById(R.id.title);

            topText.setText(getItem(position).getTitle());

            return retval;
        }
    }

}

Layout files
Listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#fff">

    <ImageView
        android:id="@+id/image"
        android:layout_width="150dip"
        android:layout_height="150dip"
        android:scaleType="centerCrop"
        android:src="@drawable/wood"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:gravity="center_horizontal"
        />

</LinearLayout>

activity_book_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="com.azed">

    <com.HorizontalListView
        android:id="@+id/sublistview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ddd"/>

</LinearLayout>

activity_list_books.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical"
    tools:context="com.azed">

    <ListView
        android:id="@+id/listbooks"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></ListView>

</LinearLayout>


text:
Q: How would the Redshift of a Photon be influenced if it travels through a volumetric gas disk? so me and a buddy have been working on a Black Hole render engine for quiet a while now. And at this point we have most of the technical stuff worked out. Which results in images like these;
Note, the red coloration is just for testing purposes. Also, if anyone cares, the Render time on this is about 20minutes with 5 Supersamples, so the entire image is rendered 5 times with slight offsets to the initial conditions to achive Anti Alisasing. And if anyone wonders, the reason why the Einstein ring´s are darker is because the rays go straight through the disk in these areas. So the Optical depth is smaller.
Now, originally we had done Redshift & Doppler beaming on a 2D disk, which yielded results like these;
Because it used to be a 2D disk, we were able to make some drastic assumptions about the Frequency shift. This was only possible because rays would simply terminate as soon as they hit the disk. I.e the integration stopped right then and there.
However, with a Volumetric disk this is no longer possible. Now, the only way for a ray to just stop integrating is if it either hits the Event Horizon or its displacement is larger than the drawing distance (150 units). If a ray wants to orbit the black hole for 100000 Steps and pass through the disk 10 times, it is free to do so.
For transparency sake, this is what happened when we used our 2D Algorithm on the Volumetric disk;
Besides some pixels having infinit color values, it is rather clear what the issue is. It looks very unphysical and a lot of the color spectical is gone.
As such, the question is if there is anything special to consider with this set up ? Do we, for example, have to take samples of the local Redshift each time a ray is inside a Volume and use these all together ? Or does only the last position a ray had before leaving the disk for good matter ? Atm we are working on the assumption that we have to sample the redshift (and blueshift) throughout the disk and use all of these values to arrive at a final Redshift factor for any given ray / pixel. We thing this is needed because of Gravitational Redshift, which would be a factor for all Rays not just the ones that meet the disk.
Lastly, and these are not the main questions, if any of you have good resources on the temperature / Density and velocity distribution in an accretion disk, those would be very welocome :D
So yeah, i hope i explained the issue enough. Thank you for reading !


text:
Q: How to count partitions with FileSystem API? I am using Hadoop version 2.7 and its FileSystem API. The question is about "how to count partitions with the API?" but, to put it into a software problem, I am coping here a Spark-Shell script... The concrete question about the script is
The variable parts below is counting the number of table partitions, or other thing?
import org.apache.hadoop.fs.{FileSystem, Path}
import scala.collection.mutable.ArrayBuffer
import spark.implicits._

val warehouse = "/apps/hive/warehouse"  // the Hive default location for all databases
val db_regex  = """\.db$""".r   // filter for names like "*.db"
val tab_regex = """\.hive\-staging_""".r    // signature of Hive files

val trStrange = "[\\s/]+|[^\\x00-\\x7F]+|[\\p{Cntrl}&&[^\r\n\t]]+|\\p{C}+".r //mark
def cutPath (thePath: String, toCut: Boolean = true) : String =
  if (toCut) trStrange.replaceAllIn( thePath.replaceAll("^.+/", ""),  "@") else thePath

val fs_get = FileSystem.get( sc.hadoopConfiguration )
fs_get.listStatus( new Path(warehouse) ).foreach( lsb => {
    val b = lsb.getPath.toString
    if (db_regex.findFirstIn(b).isDefined)
       fs_get.listStatus( new Path(b) ).foreach( lst => {
            val lstPath = lst.getPath
            val t = lstPath.toString
            var parts = -1
            var size = -1L
            if (!tab_regex.findFirstIn(t).isDefined) {
              try {
                  val pp = fs_get.listStatus( lstPath )
                  parts = pp.length // !HERE! partitions?
                  pp.foreach( p => {
                     try { // SUPPOSING that size is the number of bytes of table t
                        size  = size  + fs.getContentSummary(p.getPath).getLength
                     } catch { case _: Throwable => }
                  })
              } catch { case _: Throwable =>  }
              println(s"${cutPath(b)},${cutPath(t)},$parts,$size")
            }
        })
}) // x warehouse loop
System.exit(0)  // get out from spark-shell

This is only an example to show the focus: the correct scan and semantic interpretation of the Hive default database   FileSystem structure, using Hive FileSystem API.  The script sometimes need some memory, but is working fine. Run with sshell --driver-memory 12G --executor-memory 18G -i teste_v2.scala > output.csv

Note: the aim here is not to count partitions by any other method (e.g. HQL DESCRIBE or Spark Schema), but to use the API for it... For control and for data quality checks, the API is important as a kind of "lower level measurement".

A: Hive structures its metadata as database > tables > partitions > files. This typically translates into filesystem directory structure <hive.warehouse.dir>/database.db/table/partition/.../files. Where /partition/.../ signifies that tables can be partitioned by multiple columns thus creating a nested levels of subdirectories. (A partition is a directory with the name .../partition_column=value by convention).
So seems like your script will be printing the number of files (parts) and their total length (size) for each single-column partitioned table in each of your databases, if I'm not mistaken.
As alternative, I'd suggest you look at hdfs dfs -count command to see if it suits your needs, and maybe wrap it in a simple shell script to loop through the databases and tables.


text:
Q: CDF after using weak law of large numbers Let $X_1, X_2,\ldots $  be a sequence of infinite independent and identically distributed random variables, where $X_i\sim U[0,1]$.
Let $D_n = \sqrt{X_1^2 + X_2^2 + X_3^2 + \ldots + X_n^2}$ be a random variable. What is the the value of the following cumulative distribution function at the point $\frac{1}{\sqrt{3}}$:  $$\lim_{n\to \infty}F_{\frac{Dn}{\sqrt{n}}} \left(\frac{1}{\sqrt{3}}\right)= \text{?}$$
Is it $1$ because all CDFs are right continuous or is it $\frac12$ because of the delta like function the distribution is like at $n=\infty$?

A: It's not the Weak Law of Large Numbers, it's the Central Limit Theorem.
$\mathbb E[X_n^2] = 1/3$.
By the Central Limit Theorem, $Y_n = \sqrt{n}(D_n^2/n - 1/3)$ tends in distribution to $\mathcal N(0, \sigma^2)$, where $\sigma$ is the standard deviation of $X_n^2$.  In particular
$$ \mathbb F_{\frac{D_n}{\sqrt{n}}}\left(\frac{1}{\sqrt{3}}\right) = \mathbb P\left(\frac{D_n}{\sqrt{n}} \le \frac{1}{\sqrt{3}}\right) = \mathbb P\left(Y_n \le 0\right) \to \mathbb P(Z \le 0) = \frac12$$


text:
Q: linux bash build command with strings from csv I am pretty new to bash (and linux overall).
Been researching the whole day thinking this was a simple fix that I was not understanding but I've tried a thousand different things and still cannot make it work... need an extra pair of eyes and some advice please.
I have a csv with only one column that hosts names of properties hosted in PasswordVault that I need to query for their password using the PasswordVault client.
This is a working query command:
/opt/CARKaim/sdk/clipasswordsdk GetPassword -p AppDescs.AppID=TEST-APP -p Query="safe=TEST-SAFE;folder=root;object=TEST-SAFE.dev-pwd" -p RequiredProps=Address,UserName -o Password,PassProps.UserName

I am testing with only 2 values in the CSV:
TEST-SAFE.dev-pwd
TEST-SAFE.prd-pwd

When I do the following:
while IFS="," read f1
do
    echo $f1
    /opt/CARKaim/sdk/clipasswordsdk GetPassword -p AppDescs.AppID=TEST-APP -p Query="safe=TEST-SAFE;folder=root;object=**$f1**" -p RequiredProps=Address,UserName -o Password,PassProps.UserName
done < extractiontest.csv

I get the following output:

TEST-SAFE.dev-pwd  -p RequiredProps=Address,UserName -o
  Password,PassProps.UserNameT-APP -p
  Query=safe=TEST-SAFE;folder=root;object=TEST-SAFE.dev-pwd
  TEST-SAFE.prd-pwd  -p RequiredProps=Address,UserName -o
  Password,PassProps.UserNameT-APP -p
  Query=safe=TEST-SAFE;folder=root;object=TEST-SAFE.prd-pwd

Seems as if the portion of the string that comes after the variable, is overwriting the portion of the string that's before the variable and up to it.
I've tried separating the string in multiple variables and try concatenating them one after the other.
I've tried substituting the string with XXX and then doing:
stri="${originalstring//XXX/${f1}}"
echo $stri

I've tried eval.
I've tried different combinations of single vs. double quotes
I even tried having the command as a line in the csv file.
Cannot make it work... :(
HELP? :)
I would really appreciate it!

A: Seems that your CSV file contains '\r' character at the end of the line. More precisely the line ends with '\r\n' just as it would under DOS/Windows.
In Bash the end on the line should contain only a single '\n' character.
Once you remove the "\r" from the file it would work nicely. For a large file you might use "dos2unix < input.csv > correct.csv" and user the output.csv for your script.


text:
Q: Playback with Web Audio api very slow I have a very strange problem:
I'm playing a wav with the web audio api the following way:
        var d2 = new DataView(evt.data);

        var data = new Float32Array(d2.byteLength / Float32Array.BYTES_PER_ELEMENT);
        for (var jj = 0; jj < data.length; ++jj) {
            data[jj] = d2.getFloat32(jj * Float32Array.BYTES_PER_ELEMENT, true);
        }

        var buffer = context.createBuffer(1, data.length, 44100);
        buffer.getChannelData(0).set(data);

        source = context.createBufferSource();
        source.buffer = buffer;
        source.start(startTime);
        source.connect(context.destination);

        startTime += buffer.duration;

This worked perfectly fine but now the playback speed is very slow...
I did not change anything on the code. The only thing that changed was that i recently changed my OS from Windows 7 to Windows 8.1.
Could there be any relation to this problem?
I tried it in Chrome and Firefox and both have the same behaviour.
Thanks for your help!
EDIT:
I'm sending float values to the client because as i learned in this thread the Web Audio Api needs float values between -1 an 1 to process the audio data correct.
When i remove the float values and start sending PCM Data again the playback speed is normal. It's full of noise again but the speed is normal...
I would really appreciate any input which might help me to figure out this strange problem.

A: Check the sample-rate of the AudioContext, and put it instead of the hard-coded 44100 value. Also, check the number of channels of you buffer. Your code, as it is, will only work on mono.

A: I had the same issue, playing at 88200 seemed to solve it.
But as @padenot indicated, I tried splitting up the left and right channel like this (assuming I was dealing with interleaved stereo):
var floatsLeft = new Float32Array(samples.length/2);
var floatsRight = new Float32Array(samples.length/2);

for (var i = samples.length - 1; i >= 0; i--) {
  if(i%2 == 0)
    floatsLeft[i/2] = samples[i];
  else
    floatsRight[(i-1)/2] = samples[i];
};

var audioBuffer = audioContext.createBuffer(2, samples.length/2, audioContext.sampleRate)
var bufferSource = audioContext.createBufferSource();

audioBuffer.getChannelData(0).set(floatsLeft);
audioBuffer.getChannelData(1).set(floatsRight);

bufferSource.buffer = audioBuffer;
bufferSource.connect(audioContext.destination);
bufferSource.start(0);

And now it works perfectly. And probably in stereo too!


text:
Q: Variable ora (time) with blank The following assignment:

set ora=%time:~0,2%%time:~3,2%%time:~6,2%%time:~9,2%

returns the value " 9194234" when the time is 9.19.42,34.
How can be squeezed the value or better to have the value "09194234"?

A: This should work
set ora=%time:~0,2%%time:~3,2%%time:~6,2%%time:~9,2%
set ora=%ora: =0%

It replaces spaces with 0


text:
Q: CMSIS-DAP stuck in Listening on port 4444 I can't use openocd with DAPLINK to debug some mcus. when I just test if DAPLINK working fine in cmd, I get the following output,it doesn't go ahead ,and it stuck in listening on port 4444. After a few seconds it just reappears as the previous statement. My computer is windows 11.
enter image description here
I have try the different openocd version,I get the following output. Apparently, it's connected properly.So could you please tell me why the newer openocd is not connected successfully?
enter image description here


text:
Q: how to bind two events to an element in knockout.js I am novice to Knockout.js.
I have a code snippet, which basically opens a modal on click of an image button. For some reason it is not working on key press.
Here is the initial code:

Since it was missing keypress or keyup event, I made the below changes.

The action is not triggered by the keypress. I tried keyup as well ( as mentioned in some of the questions in stackoverflow. ), that didn't work too.
The Model looks like this:

viewModel.opt = {
    openModalForNew: function () {
        // Some code
    },
    openModalForEdit: function (assessmentType) {
        // Some code
    },
    saveModal: function () {
        // Some code
    },
    removeAsmtType: removeAsmtType
};

Update: The action is recognized but don't know why the event is not triggered.
        when I run the below test case, the test is printed on console everytime I hover the mouse over that  tag.

Can any one suggest what is that I am doing wrong. There are no errors that are shown in the browser console as well.
Thanks in advance.

A: The keypress event is triggered on the element that has focus, i.e.: an element that has the tabindex (or even contenteditable) attribute or supports it automatically (like any <input> element).
You can fix your issue by moving the event: { keypress: ... } binding to your  element that has tabindex=0.

ko.applyBindings({
  onPress: function(d, e) {
    console.log("keypress on node", e.target.nodeName);
  }
});

Tap the text and press a key. The console will log the element that has the keypress event

  some text


text:
Q: Where to put text files in directory in Android I have a text file i want to include in my Android application, it is not a string file it is a standard text file. It contains data that defines the characteristics of a "map" that is drawn on a board. The file is not an XML file so i am unsure where i should put it or if this isn't good file structure for android? Are you suppose to do this? If you are then under what directory are you suppose to put them? How then are you suppose to access the file? I know how to use FileInputStreams and FileOutputStreams i just need to know how to access the file. All relevant answers are welcome and appreciated!

A: Use assets or raw folder in your android folders structure to keep that file. For more info read this

A: You have to put your file in the assets folder as Waqas said.
Now to access it you do it like that.
I give you an example using BufferedReader
BufferedReader reader = new BufferedReader(
                 new InputStreamReader(getAssets().open("YourTextFile.txt")));

Be careful. In my case, I don't know why for now, I cannot read text files bigger than ~1MB and I had to split them in multiple small files. It seems other had the same problem of file size but I didn't find any information about that on Android developer site. If any one knows more about this ....
FOLLOW UP
My problem with the 1MB was due to a know bug/limitation of earlier versions of Android. Since using recent versions of Android, that problem is not present anymore.

A: I would just like to add to the accepted answer (I don't have enough reputation to comment unfortunately.) The link there to the tutorial that explains how to set up the res/raw method or the assets method is mostly good, but there's actually a MUCH easier way. Look at the function described there called LoadFile. That function is rather verbose. Lets say all you need is an InputStream variable so that you can read and write to a file. Then delete everything after line 77! Also you don't need the resource id at all! You can use this function:
//get the file as a stream
iS = resources.openRawResource(R.raw.mygpslog)

Now all you have to do is return iS and you will have your much desired file handle.

*

*For reference, the tutorial is right here -> http://www.41post.com/3985/programming/android-loading-files-from-the-assets-and-raw-folders


text:
Q: Как сжать/растянуть текст в css Имеется некий текст в
 и я хочу сжимать или растягивать его по ширине на 50%. Как это можно сделать?

Lorem ipsum

Оригинальный текст

Растянутый текст на 50%

Сжатый текст на 50%

A:

body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  overflow: hidden;
}

h1 {
  display: inline-block;
  transform: scale(8, 6);
}

Текст


text:
Q: Enumeration of a complex type How can I make an enumeration of a complex type?
For example, I want to store the following data into a xsd enumeration called Measurings

*

*description

*tag

*item

item
tag fileName
each one of these attributes has an specific value and this set makes one registry in my ennumeration. But the problem is that as far as I know, it's allowed just the "value" attribute in an enumeration.

A: There is nothing like complex type enumeration in XML Schema. You'll need to organize it externally. See
http://schemas.opengis.net/gml/3.1.1/base/dictionary.xsd
http://schemas.opengis.net/definitions/axisDirection.xml
for an implementation example.


text:
Q: Does using locals as arguments in pthread_create() work? This is mainly a question about scope and threads. Let's say we have the following struct.
struct Test
{
  int number;
  std::string name;
};

An instance of this struct will be used as an argument in the pthread_create function. Here is an example of what this might look like.
pthread_t tid[5];
for(int i = 0; i < 5; ++i)
{
  Test test;
  test.number = 5;
  test.name = "test";
  pthread_create(&tid[i], NULL, func, (void *)&test);
}

Is this acceptable? Since test is declared in the for's scope, that means we can only rely on it existing during a single iteration of the for loop.
When pthread_create is called, a pointer to test is given as an argument. This means that func is receiving the same pointer that is passed in to pthread_create. This means that when test goes out of scope, we can no longer rely on that pointer referring to test. If we were to create more locals, hence changing the stack, the location that the pointer points to would be overwritten by those new locals. Is this correct?

A:
Is this acceptable?

In general, no, for the reasons you stated.  Specifically, the thread's entry-function may not start executing until after the Test object has been destroyed, or the Test object might be destroyed while the thread's entry-function is still using it.  Either of those possibilities will lead to undefined behavior (and a program that only works correctly "sometimes").
You need to guarantee that the data you pass to the thread remains valid for as long as the thread needs to use it.  One way to do that is to allocate that Test object on the heap, and have the thread call delete on the Test-pointer when it's done using it.  Alternatively, you could use a condition variable to "pause" the main thread until the child pthread signals that it is done accessing the Test on the main thread's stack, so that it is now safe for the main thread to continue execution.

If we were to create more locals, hence changing the stack, the
  location that the pointer points to would be overwritten by those new
  locals. Is this correct?

Yes, you understand the issue correctly.


text:
Q: 2665 - Invalid Date Error in Teradata I'm trying to complete an insert into statement but keep getting a "Invalid Date" error as a result.
My create statement:
CREATE MULTISET TABLE Date_Table,
    NO FALLBACK ,
    NO BEFORE JOURNAL,
    NO AFTER JOURNAL,
    CHECKSUM = DEFAULT,
    DEFAULT MERGEBLOCKRATIO
     (
      customer_field,
      date_field DATE FORMAT 'YYYY-MM-DD',
      other_fields
     )
PRIMARY INDEX ( date_field );

My insert statement:
INSERT INTO Date_Table
select
  a.customer_field,
  a.CAST (date_field AS DATE FORMAT 'yyyy-mm-dd'),
  a.other_fields
from a

What I've tried so far:

*

*Making the date_field null by cast(null as date) as date_field

*checking each date in the date_field against sys_calendar.calendar to make sure they're valid dates

*Checking the type by SELECT TYPE (date_field) FROM date_table GROUP BY 1, they all turn out to be the 'date' type

Any thoughts?

A: When you created Date_Table , the datatype you specified is date. May be the datatype of table a is is VARCHAR, which is  not matching with Date_Table. That is the reason you are unable run INSERT statement. We can go for CAST.
INSERT INTO Date_Table
select
  a.customer_field,
  a.CAST (cast(date_field as varchar(8)) AS DATE FORMAT 'yyyy-mm-dd'),
  a.other_fields
from a

A: I had the same issue, but I found out it had nothing to do with the content of the date-fields. In my case, the order of the 'create table'-attributes and 'insert'-attributes was not the same, which caused this error-statement.
So, example:
create multiset table database.table ,fallback ,
     no before journal,
     no after journal,
     checksum = default,
     default mergeblockratio
     (
      selection_dttm date,
      strategy_nm varchar(30) character set latin not casespecific
     );

and then the 2 attributes in the insert statement in different order:
insert into database.table
select
    strategy_nm,
    selection_dttm
from source_table


text:
Q: Creating predefined values in field using PyQGIS I would like to make programmatically (with Python) the same thing than we can do directly in QGIS when you create a list of values for a field.
I would like to create a new field and specify a list of possible values for this field. I didn't find any function for that in the API. Is there anyone who has the solution?

A: You need to assign and configure a ValueMap widget to your layer's field in this way:
QGIS 3.x
fieldIndex = layer.fields().indexFromName( 'myField' )
editor_widget_setup = QgsEditorWidgetSetup( 'ValueMap', {
                         'map': {'Description 1': 'value1',
                                 'Description 2': 'value2'}
                        }
                      )
layer.setEditorWidgetSetup( fieldIndex, editor_widget_setup )

QGIS 2.x
fieldIndex = layer.fieldNameIndex( 'myField' )
layer.setEditorWidgetV2( fieldIndex, 'ValueMap' )
values = {u'Description 1': u'value1',
          u'Description 2': u'value2',
          u'Description 3': u'value3'}
layer.setEditorWidgetV2Config( fieldIndex, values )


text:
Q: Aggregation on GeoDjango queries I have the following models:
from django.contrib.gis.db import models as geomodels

class Shop(models.Model):
    objects = geomodels.GeoManager()
    name = models.CharField(max_length = 64)

class ShopOutlets(models.Model):
    objects = geomodels.GeoManager()
    shop = models.ForeignKey(Shop)
    location  = geomodels.PointField(srid = 4326, blank = True, null = True)

What I am trying to do is find (distinct) Shops in order of their closest outlets to a given point.
I have tried this:
Shop.objects.annotate(dist = Min('shopoutlet__location'))

but it doesn't actually give me the option of specifying a center point.  Any ideas on how this can be done?
Thanks in advance

A: I think you want to get the distance between two points.
If you want this, just do:
ShopOutlets.objects.distance(point).order_by('distance')

The distance method will calculate the distance between your object to the given point, and will put a distance attr in your object dynamically.


text:
Q: ASP.NET MVC Lifecycle - Do Some Work Once Per Page Request I'd like to perform some work per web request to a .NET MVC Web Application.  Specifically, I'd like to make a log entry into a DB for each page load.
Performing this work in an overridden Controller class Controller.Initialize() method doesn't work, because a new controller is created with every call to @Html.Action().  Thus, if a child action is called from a view, then I end up double logging--which isn't what I want.
How can I insert some work into the MVC Lifecycle, such that it executes once per page request?

A: You can use either OnActionExecuting or OnActionExecuted.
For example,
public class HomeController : Controller
{
    [LogActionFilter]
    public ActionResult Index()
    {
        return View();
    }
}

public class LogActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // If you register globally, you need this check.
        if (!filterContext.IsChildAction)
        {
           Log("OnActionExecuting", filterContext.RouteData);
        }
        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // If you register globally, you need this check.
        if (!filterContext.IsChildAction)
        {
           Log("OnActionExecuted", filterContext.RouteData);
        }
        base.OnActionExecuted(filterContext);
    }

    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
        Debug.WriteLine(message, "Action Filter Log");
    }
}

A: You can check in the Initialize if the action is a Child Action.
ControllerContext.IsChildAction


text:
Q: Reset Html:multibox to original values after hitting cancel button I have a html:multibox having checked values when loading the page set in action class. if i check other checkbox and hit cancel. its should restore the original values.
here is my code

    chkbox1

    chkbox2

    chkbox3

    chkbox4

    chkbox5

     chkbox6

    chkbox7

        <input type="submit" name="submit" class="submit" value="Submit">

A: Try to use something like this:
(Not tested)
<c:forEach items="${original_values}" var="item" >

   <c:out value="${item.key}"/> -
   <c:out value="${item.value.yourvalue}"/>
</c:forEach>


text:
Q: Flexbox content-responsive grid-type row I have the following html:

        <video>
            <source src="video1" />
        </video>

I'd like it for row to automatically adjust its height and for the subchildren of row to automatically adjust their widths and heights such that the aspect ratios of the content under the img and video tags remains the same, that row will have a width of 100%, and that there is no empty space within row.
In other words, I'm trying to make a content-responsive grid row with flexbox. Like so:

Except that rows and columns automatically change size to preserve image aspect ratios without creating gaps.
My current CSS attempt is as follows:
.row {
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
}

.item {
    position: relative;
    min-height: 100%;
}

.item video {
    max-width: 100%;
    max-height: 100%;
}

.item img {
    max-width: 100%;
    max-height: 100%;
}

A: There seems to be no effective way to do this with flexbox. The only example I could find of this working properly was on a wix website, which works by doing the following:

*

*All items are positioned absolutely and have width and height set manually.

*Initial width and height of all items are zero to prevent initial rendering problems.

*A function is defined which manually calculates the correct position, width, and height of all items.

*This function is called on every resize and immediately after page load.


text:
Q: Getting Node.js/Geddy app set up with CoffeeScript support Just getting started with Node.js and I'm using the Geddy framework (I like the similarity to Rails). But I'm having some trouble getting it to work properly with CoffeeScript. I see Geddy is now "supporting" coffee files. But when I start converting even the default js to coffee, I get errors:
/usr/local/lib/node_modules/geddy/lib/app.js:108
      ctor.origPrototype = ctor.prototype;
                               ^
TypeError: Cannot read property 'prototype' of undefined
at _registerControllers (/usr/local/lib/node_modules/geddy/lib/app.js:108:36)
at async.AsyncBase.runItem (/usr/local/lib/node_modules/geddy/node_modules/utilities/lib/async.js:108:10)
at async.AsyncBase.next (/usr/local/lib/node_modules/geddy/node_modules/utilities/lib/async.js:113:12)
at async.AsyncBase.execCallback (/usr/local/lib/node_modules/geddy/node_modules/utilities/lib/async.js:148:54)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

I have CoffeeScript installed, but I don't really know what else I'm supposed to do here. The documentation on this is pretty much non-existant.
Any idea what I'm missing here?

A: Have a look at geddy-coffee-templates. You can create a new base app from coffeescript. Adding a model and controller is working now, but the scaffold and resource generators are not working at the moment.
For an existing app, simply add a dependency to coffee-script on your package.json file. (Example). Then npm install.

A: this question is probably a bit old but I just ran into this problem.
In my case, all I did was added a controller file called fruits.js but inside my fruits.js I defined it as:
var Fruit = function () {

...

};

exports.Fruit = Fruit;

The problem is in the naming of the file and the actual variable name not matching.
In my case, the simple fix was:
either rename "Fruit" to "Fruits"

or
change the file name from "fruits.js" to "fruit.js"

So the lesson learned is Geddy expects the controller file name to match the actual variable definition inside the file.
Hope you were having the same problem.


text:
Q: Resharper equivalent of CodeRush's "Tab" shortcut (go to next/prev usage) I'm trying to switch to Resharper from CodeRush and really struggling with this one.
In CodeRush when you are over a variable/method etc. if you press "Tab" it will jump to the next usage of it. Similar to VS.NET's Ctrl + Shift + Down/up
Is there anyway to do this in Resharper? Is there any plugin or a way for me to assign Tab to similar command in Resharper?

A: ReSharper has this functionality, but only after you have either found or highlighted the usages of a variable/method/etc...
The keyboard shortcuts depend on whether you are using the Visual Studio or IDEA keyboard mappings (set in ReSharper -> Options -> Visual Studio Integration -> Keybarod Shortcuts).
To find the usages, press Shift + F12 (Visual Studio) or Alt + F7 (IDEA).
To highlight usages, press Shift + Alt + F11 (Visual Studio) or Ctrl + Shift + F7 (IDEA).
Once you have done either of the above, you can move to the next usage using Ctrl + Alt + FPgDn (Visual Studio) or Ctrl + Alt + Down (IDEA).
This ReSharper help page has a more complete set of shortcuts.


text:
Q: Is there any way to detect a program's version in cmake? I tried to use clang-format to format my cpp project. My cmake file is as follows:
...
find_program(CLANG_FORMAT_BIN_NAME NAMES clang-format-3.8 PATH /usr/bin/)
if(NOT CLANG_FORMAT_BIN_NAME-NOTFOUND)
    file(GLOB_RECURSE ALL_SOURCE_FILES *.cc *.h)
    add_custom_target(
            clang-format
            COMMAND ${CLANG_FORMAT_BIN_NAME}
            -style=google
            -i
            ${ALL_SOURCE_FILES}
    )
endif()
...

When I use make clang-format, everything goes well. Now let's step further, I want to use clang-format without specifying its exact version. Is there any way to achieve this goal? I have tried to change my CMakeLists.txt like this:
find_program(CLANG_FORMAT_BIN_NAME NAMES clang-format-* PATH /usr/bin/)
if(NOT CLANG_FORMAT_BIN_NAME-NOTFOUND)
    file(GLOB_RECURSE ALL_SOURCE_FILES *.cc *.h)
    add_custom_target(
            clang-format
            COMMAND ${CLANG_FORMAT_BIN_NAME}
            -style=google
            -i
            ${ALL_SOURCE_FILES}
    )
endif()

But it didn't work.


text:
Q: Send Javascript variables into PHP's function parameters on file? I'm making a php page that inserts values written by the user into an MySql table.
I'm trying to get the textbox values sent to the php code portion and can't do it.
I currently have this php function:
function insertion($Alias,$Password,$Nom,$Adresse,$Telephone,$CatPrefere){
       try{
        $insert = $mybd->prepare("CALL insertClients(?,?,?,?,?,?,?)",array(PDO::ATTR_CURSOR, PDO::CURSOR_FWDONLY));
        $insert->bindParam(1,$Alias);
        $insert->bindParam(2,$Password);
        $insert->bindParam(3,$Nom);
        $insert->bindParam(4,$Adresse);
        $insert->bindParam(5,$Telephone);
        $insert->bindParam(6,0);
        $insert->bindParam(7,$CatPrefere);
        $insert->execute();
       }
       catch(PDOException $e){
       echo('Erreur insertion dans table client: '.$e->getMessage());
       exit();
       }

And this Javascript function (notice the last line here, i call my php function):
function inscription() {
    var Alias = document.getElementById("alias").value;
    var Password = document.getElementById("password").value;
    var Nom = document.getElementById("nom").value;
    var Adresse = document.getElementById("adresse").value;
    var Telephone = document.getElementById("telephone").value;
    var Categories = document.getElementById("categorie");
    var CatPrefere = Categories.options[Categories.selectedIndex].value;
    <?php insertion(Alias,Password,Nom,Adresse,Telephone,CatPrefere);?>
}

How do i send all thoses variables to my php function?
If this is all correct then something else might not work in my spaghetti code.
Also i'm working on a single .php file named Inscription.php.

A: I think that is not possible. What you can do it is change the URL to get values in $_GET.
Look that stack overflow topic: send javaScript variable to php variable