text:
Q: Symfony2 Self referencing many to many relation I'm new to symfony2 and forms are quite tough to get my mind around.
This topic has been covered before, but mainly to do with the relationship aspect. I'm having issues with the form and how to manage the saving of the relationships.
The scenario being A user has many friends who are users. So a self referencing many-to-many relationship.
I'm using FOSUser Bundle and have a friendship entity. Here is the YAML for creating the entities.
MH\FriendshipBundle\Entity\Friendship:
type: entity
table: mh_friendship
repositoryClass: MH\FriendshipBundle\Entity\FriendshipRepository
id:
    id:
        type: integer
        generator:
            strategy: AUTO
fields:
    requested_at:
        type: datetime
        gedmo:
            timestampable:
                on: create
    is_accepted:
        type: boolean
        nullable: true
    accepted_at:
        type: datetime
        nullable: true
manyToOne:
    user:
        targetEntity: MH\UserBundle\Entity\User
        inversedBy: user_friends
        joinColumn:
            name: user_id
            referencedColumnName: id
    friend:
        targetEntity: MH\UserBundle\Entity\User
        inversedBy: friend_users
        joinColumn:
            name: friend_id
            referencedColumnName: id
lifecycleCallbacks:
    prePersist:   [ ]
    postPersist:  [ ]
    preUpdate:    [ ]
    postUpdate:   [ ]

MH\UserBundle\Entity\User:
type:  entity
table: mh_user
repositoryClass: MH\UserBundle\Entity\UserRepository
id:
    id:
        type: integer
        generator:
            strategy: AUTO
fields:
    first_name:
        type: string
        length: 100
        nullable: true
    last_name:
        type: string
        length: 100
        nullable: true
    created_at:
        type: datetime
        gedmo:
            timestampable:
                on: create
    updated_at:
        type: datetime
        gedmo:
            timestampable:
                on: update
oneToMany:
    user_friends:
        targetEntity: MH\FriendshipBundle\Entity\Friendship
        mappedBy: user
        cascade: ["persist", "remove"]
    friend_users:
        targetEntity: MH\FriendshipBundle\Entity\Friendship
        mappedBy: friend
        cascade: ["persist", "remove"]
    friend_groups:
        targetEntity: MH\FriendshipBundle\Entity\FriendGroup
        mappedBy: owner
        cascade: ["persist", "remove"]
lifecycleCallbacks:
    prePersist:   [ ]
    postPersist:  [ ]
    preUpdate:    [ ]
    postUpdate:   [ ]

Now i have a form that was create via the crud generator from the Friendship resource, and this is what i'm doing.
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('friend', 'entity', array(
                            'class' => 'UserBundle:User',
                            'property' => 'fullName',
                            'expanded' => true,
                            'multiple' => true,
                            'required' => false,
                    ))
    ;

}

Which renders a list of checkboxes of users that i can select and save as "friends".
My problems are :

*

*I get the following error when saving.

PHP Catchable fatal error:  Argument 1 passed to MH\FriendshipBundle\Entity\Friendship::setFriend() must be an instance of MH\UserBundle\Entity\User, instance of Doctrine\Common\Collections\ArrayCollection given, called in /Users/mohammedhamad/Sites/sociabills/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 345 and defined in /Users/mohammedhamad/Sites/sociabills/src/MH/FriendshipBundle/Entity/Friendship.php on line 155, referer: http://sociabills.local/friends/new

Not sure how to make sure that the chosen are "friends" are passed to the setFriends method which expects a collection, and not the setUser method which expects a User object.

*

*How to i get the form to list all other users, except for the logged in user. Don't want a person to befriend themselves.

A: Looking at the doc

/**
 * @ManyToMany(targetEntity="User", mappedBy="myFriends")
 **/
private $friendsWithMe;

/**
 * @ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
 * @JoinTable(name="friends",
 *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@JoinColumn(name="friend_user_id", referencedColumnName="id")}
 *      )
 **/
private $myFriends;

public function __construct() {
    $this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
    $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
}

// ...

}
The YML equivalent of the annotations would be (keep in mind I'm not used to yml for entity mapping and this is not tested)
   manyToMany:
     myFriends:
       targetEntity: User
       inversedBy: friendsWithMe
       joinTable:
         name: friends
         joinColumns:
           user_id:
             referencedColumnName: id
         inverseJoinColumns:
           friends_user_id:
             referencedColumnName: id
     friendsWithMe:
       targetEntity: User
       mappedBy: myFriends

Then you can implement addMyFriend($friend) method and removeMyFriend($friend) in your class
public function addMyFriend($friend){

 $this->myFriends[] = $friend;

}

public function removeMyFriend($friend)
{
    $this->myFriends->removeElement($friend);
}

Issue 2  was answered by @Darragh

A: Issue 1:
As I'm sure you noticed from the error, the first issue is occurring because setFriend() expects a single User entity, but is instead receiving an ArrayCollection of one or more User entities.
This was discussed here in a blog post by Bernhard Schussek, the creator of the form component. I assume that you are using version >= 2.1? If so, the you need to add some additional methods:
public function addFriend(User $friend)
{
    $this->friend[] = $friend;
}

and:
public function removeFriend(User $friend)
{
    $this->friends->removeElement($friend);
}

My understanding is that these methods are called for every element in the ArrayCollection. I am looking at a similar example in one of my repos and this is what is implemented in one of my entities.
This is available in version >= 2.1.
Issue 2:
To populate a form entity element with custom choices, you can use the query_builder option. A quick cut and paste example from my codebase here:
->add('client', 'entity', array(
    'class'         => 'HooluxDAPPUserBundle:Organisation',
    'property'      => 'name',
    'query_builder' => function(EntityRepository $er) use ($builder) {
        if ($builder->getData()->hasAdvertiser()) {
            return $er->buildQueryClientsForAdvertiser(
                $builder->getData()->getAdvertiser()
            );
        }
        return $er->createQueryBuilder('c');
    }
))

The query_builder option accepts an anon function/closure that receives a reference to the repository class for your Entity. You can call any custom method that returns a query builder object.
Edit

*

*Documentation for query_builder option

*Some answers on passing variables to the buildForm() method
In your controller:
// pass current user's own id as an option
$this->createForm(new FriendType(), $entity, array('user_id' => $this->getUser()));

In the buildForm method:
public function buildForm($builder, $options) {
    $builder
        ->add('friend', 'entity', array(
            'class' => 'UserBundle:User',
            'property' => 'fullName',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
            // closure, include $options from parent scope with `use`
            'query_builder' => function(EntityRepository $er) use ($options) {
                // current user's own id
                $userId = $options['user_id'];
                // call custom method on UserRepository class
                return $er->getUsersWhereIdIsNot($userId); // returns QueryBuilder object

            }
        ));
}

Then add a method that returns all users WHERE id != :id or whatever.
Hope this helps :)


text:
Q: Extracting token from a string I've a some strings like that "paddington road" and I need to extract the word "road" from this string. How can I do that?
The problem is that I need to process a list of streets and extract some words like "road" "park" "street" "boulevard" and many others.
What could be the best way to do that? The complexity is O(n*m) and if you consider that I process more than 5000 streets, the performance should be very important.
I'm extracting the values from a Postgres db and putting into a List but I'm not sure it's the best way, may be a hash table is faster to query?
I tried something like this:
    // Parse selectedList
    Iterator<String> it = streets.iterator();
    Iterator<String> it_exception = exception.iterator();

    int counter = streets.size();
    while(it.hasNext()) {

        while ( it_exception.hasNext() ) {
            // remove substring it_exception.next() from it.next()
        }
    }

What do you think?

A: You need to get a new iterator for your list of keywords at each iteration of the outer loop. The easiest way is to use the foreach syntax:
for (String streetName : streets) {
    for (String keyword : keywords) {
        // find if the string contains the keyword, and perhaps break if found to avoid searching for the other keywords
    }
}

Don't preoptimize. 5000 is nothing for a computer, and street names are short strings. And if you place the most frequent keywords (street, rather than boulevard) at the beginning of the keyword list, you'll have less iterations.

A: You can try Set:
Set<String> exceptions = new HashSet<String>(...);
for (String street : streets) {
    String[] words = street.split(" ");
    StringBuilder res = new StringBuilder();
    for (String word : words) {
        if (!exceptions.contains(word)) {
            res.append(word).append(" ");
        }
    }
    System.out.println(res);
}

I think complexity will be O(n), where n is a number of all words in streets.

A: List streets = new ArrayList<String>();
    streets.add("paddington road");
    streets.add("paddington park");

    for (Object object : streets) {
        String cmpstring = object.toString();
        String[] abc = cmpstring.split(" ");
        String secondwrd = abc[1];
        System.out.println("secondwrd"+secondwrd);

    }

you can keep secondwrd in a list or string buffer etc....

redpajama_set_name: RedPajamaStackExchange


text:
Q: servicemix custom repository not downloading jars I am running servicemix 5.0.4. I have to use my own repository and not the internet maven repository. I did these steps
config:edit org.ops4j.pax.url.mvn
config:propset org.ops4j.pax.url.mvn.repositories http://repo.xyz.com@snapshots ( i need snapshots)
config:update
But Still, not able to download the features when i run features:install.
What is the correct way to specify the repository URL. If my repos is repo.xyz.com. Are there any other things to add to the URL apart from just giving repo.xyz.com.

A: thanks Ksobkowiak
It worked by changing the repository URL  to something like repo.xyz.com/xyz/content


text:
Q: Linux doesn't like my PC? System Specs (Desktop PC):

*

*Intel Core i5 4460 (IGP enabled)

*Gigabyte H97-HD3 Motherboard

*8gb DDR3 - 1600 Kingston RAM (4GB X2)

*Sapphire Radeon R9 380X GPU

*Currently main OS is Windows 10

Distros i tried:

*

*Kubuntu 18.10

*Linux Mint Mate and Cinnamon 19.1

*Linux Mint KDE 18.3

*Manjaro Linux KDE 18.04

Using Sandisk 8 GB USB stick. Using lastest Rufus to prepare USB. No faults here because my laptop has no problem booting and installing from this. Currently running Kubuntu on my laptop with no issues at all.
First of all, i searched these and some other forums elsewhere in hopes to finding a solution to my problem but i caould not find.
For starters, none of these distros can boot normally (with hardware acceleration). I can only see the grub menu or boot menu, can select to boot to corresponding OS and the screen goes "no-signal mode" for normal boot attempts. I have to boot with nomodeset option. Manjaro KDE does not boot at all.
For Kubuntu distro, i can boot to the screen where it asks if i want to try or install the OS. If i select the trial i see the messages in the screen shot.
I'd like to use Kubuntu mostly, because i like KDE desktop the most.
What is the problem? Is it my Radeon GPU? Not compatible with Linux kernel? Is there any way to install and run Kubuntu with hardware acceleration?
Please ask me if you need any detail.
Screen after attempting to "try" Kubuntu

A: The problem is not your video card.
I've run Ubuntu 18.04 & 18.04-hwe just fine with an AMD Radeon HD 6950, and with an AMD Vega 64 video card, both with hardware acceleration.  All of these use the same family of drivers.  I also run some KDE applications in this environment, and they run fine.
The issue is probably how you are attempting to enable hardware acceleration, and/or if you are attempting to use the proprietary drivers.  Those proprietary AMD drivers are very finicky and only work with Linux kernel version up to 4.15.  Unless you have a reason not to, you should be using the open source mesa drivers (radeon, amdgpu, etc.)
Search for how to enable the latest versions of these, usually from adding the padoka ppa and adding a few lines to a xorg configuration file.


text:
Q: If-Then-Else code that Locks / Unlocks cells keeps failing Using: Excel 2010
This portion of my code keeps failing and I am not sure why. When I try running the entire code block, it returns "Run-time error '1004': Unable to set the Locked property of the Range class".
'Lock/unlock issue
ThisWorkbook.Sheets("Dashboard").Activate
    ActiveSheet.Unprotect Password:="my password"
    Selection.Locked = False
    Selection.FormulaHidden = False
    If Range("D20").Value <> "Document Recorded" Then Range("F24").Locked = True Else Range("F24").Locked = False
    ActiveSheet.Protect Password:="my password", DrawingObjects:=True, Contents:=True, Scenarios:=True

Basically, I am trying to say: If cell D20 does not equal "Document Recorded" then lock cell F24, otherwise unlock cell F24.

A: While I tested your code and it worked as is, I suggest refactoring your code to the following.
With ThisWorkbook.Sheets("Dashboard")

    .Unprotect Password:="my password"
    .Range("F24").Locked = .Range("D20").Value <> "Document Recorded"
    .Protect Password:="my password", DrawingObjects:=True, Contents:=True, Scenarios:=True

End With

Working directly with the objects and avoiding 'Select' and 'ActiveSheet/Workbook/Cell' is best practice and if used can lead to all kinds of unsuspecting issues.

A: You have to turn the sheet protection off before you run the code.  I'm assuming your using protection otherwise you wouldn't be using the cell lock feature.


text:
Q: Split a string and apply an operation to each segment (or "word") I'm currently writing a tutorial for some software, and I'd like to refer to the shortcuts used in this program. These shortcuts should be notable, i.e. displayed in a different color or font style.
Basically what I'm trying to do is create a new command, with only one argument -- a string of words, separated by some delimiter (comma). Each word (or segment, since in this case words would be substrings like Ctrl, Shift, Enter or just S, O) should be displayed in the notable style (let's say \textbf{}), and between each two words there should be a + (or some other symbol) using the regular font style. Note that this isn't necessarily the same delimiter used in the argument (the comma)!
In pseudo code:
\newcommand{\shortcut}[1]{
    For every word in the argument #1:
        - Display in notable font style
        - Add + in regular font style (except for last word)
}

So \shortcut{Ctrl,Shift,Z} should result in \textbf{Ctrl}+\textbf{Shift}+\textbf{Z}.
Any recommendations for packages to use, or can this be done using relatively simple LaTeX?

A: Almost any list-processing package would be able to help here, including LaTeX3's list processing constructs. Here's one using etoolbox:

\documentclass{article}
\usepackage{etoolbox}% http://ctan.org/pkg/etoolbox
\makeatletter
\newcommand{\shortcut}[1]{%
  \begingroup%
  % count the elements
  \@tempcnta=\z@
  \renewcommand*\do[1]{\advance\@tempcnta\@ne}%
  \docsvlist{#1}%
  \chardef\@listsize\@tempcnta%
  \@tempcnta=\@ne%
  \renewcommand*\do[1]{%
    \ifnum\@tempcnta<\@listsize
      \texttt{##1}+\penalty\z@ \advance\@tempcnta\@ne%
    \else
      \unpenalty\texttt{##1}%
    \fi}%
  \docsvlist{#1}%
  \endgroup%
}
\makeatother
\begin{document}
You can use \shortcut{Ctrl,Shift,Z} or \shortcut{2,2,1,2,Alt,X} and on occasion \shortcut{Ctrl,Alt,Del}.
\end{document}

Taken from Special formatting of a mathmode list. The introduction of a zero \penalty allows for breaking at the text block boundary if your sequence is long.

A: You can use a \foreach loop from the pgffor package, which is pare of the pgf package:

Notes:

*

*I used the etoolbox package to provide the toggle to test for the first element, but it should be easy to adapt this to not require that package if desired using solutions from LaTeX conditional expression.

Code:
\documentclass{article}
\usepackage{etoolbox}
\usepackage{pgffor}

\newtoggle{FirstShortcut}
\newcommand*{\shortcut}[1]{%
    \global\toggletrue{FirstShortcut}%
    \foreach \member in {#1} {%
        \iftoggle{FirstShortcut}{}{+}%
        \textbf{\member}%
        \global\togglefalse{FirstShortcut}%
    }%
}%

\begin{document}
    \shortcut{Ctrl,Shift,Z}
\end{document}

A: Another one, using lambda-lists:
\documentclass{article}
\usepackage{lambda} % http://www.ctan.org/pkg/lambda-lists
\makeatletter
\def\Unlistize#1{#1\Unlistize@{}}
\def\Unlistize@#1{#1\Foldr\Plusize{}}
\makeatother
\def\Plusize#1#2{+#1#2}
\def\shortcut#1{\Show\Map\textbf[#1]}

\begin{document}

\shortcut{Ctrl,Alt,Del}
\shortcut{Ctrl,Shift,Z}

\end{document}

A: "Old style" method
\makeatletter
\newcommand{\shortcut}[1]{%
  \@tempswafalse
  \@for\next:=#1\do
    {\if@tempswa+\else\@tempswatrue\fi\textbf{\next}}%
}
\makeatother

Then \shortcut{Ctrl,Shift,Z} will do what you want.
"New style" method
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\shortcut}{O{,}m}
 {
  \ailurus_make:nn {#1} {#2}
 }

\cs_new_protected:Npn \ailurus_make:nn #1 #2
 {
  \seq_set_split:Nnn \l_ailurus_args_seq { #1 } { #2 }
  \seq_pop_left:NN \l_ailurus_args_seq \l_ailurus_temp_tl
  \textbf { \l_ailurus_temp_tl }
  \seq_map_inline:Nn \l_ailurus_args_seq { + \textbf { ##1 } }
 }

\seq_new:N \l_ailurus_args_seq
\tl_new:N \l_ailurus_temp_tl
\ExplSyntaxOff

\begin{document}
\shortcut{Ctrl,Shift,Z}

\shortcut[/]{Ctrl/,}
\end{document}

It seems more complicated, but it's really very similar. The input is split at the commas and then a cycle is performed. The first element is popped off and treated specially (not very much, actually, in this case).
Bonus With this solution you can easily print a comma, by choosing a different delimiter as optional argument. Of course also
\shortcut{Ctrl,{,}}

would have worked, but this strategy can be used also in more difficult cases.

A: \documentclass{article}

\makeatletter

\def\shortcut#1{{\def\scsep{\def\scsep{+}}\@for\w:=#1\do{\scsep\textbf{\w}}}}
\makeatother

\begin{document}

\shortcut{Ctrl,Shift,Z}

\end{document}

A: ... and a really short one, using only one 'special' macro :) (requires xstring):
\documentclass[10pt,a4paper]{article}

\usepackage{xstring}

\newcommand{\specialtext}[1]{%
    \StrSubstitute{#1}{,}{ + }[\myspecialtext]
    \textbf{\myspecialtext}}

\begin{document}
This is a \specialtext{very,special} command.
\end{document}

EDIT: As @PeterGrill pointed out, this will produce a bold face +. To avoid this, as the request of the OP was (in case this is necessary), the code should be modified like this, without sacrificing any comfort:
\newcommand{\specialtext}[1]{%
    \noexpandarg
    \StrSubstitute{#1}{,}{ \textnormal{+} }[\myspecialtext]
    \textbf{\myspecialtext}}


text:
Q: My function is running but it's not displaying the pictures I'm holding in my array I want to create a slideshow aka a carousel. However, I'm not seeing any images being displayed in the image element. I don't know where I've gone wrong.

var i = 0
var time = 3000;
var images = new Array(3)
var slide = document.getElementById("slide")

images[0] = new Image();
images[0].src = "picture/michael-jordan.jpg"
images[1] = new Image();
images[1].src = "picture/usain-bolt.jpg";
images[2] = new Image();
images[2].src = "picture/zidane.jpg"

console.log(images)

function changeImg() {
  slide.src = images[i];
  if(i < images.length - 1) {
    i++
  } else {
    i = 0;
  }
  setTimeout("changeImg()", time)
}

window.onload=changeImg;
<!DOCTYPE html>

    <link rel="stylesheet" href="index.css">
    <meta charset="utf-8">
    <title>slideshow</title>

A: You have to use CSS along with Javascript. Please take a look at this snippet.

First, set the slideIndex to 1. (First picture)
Then call showDivs() to display the first image.
When the user clicks one of the buttons call plusDivs().
The plusDivs() function subtracts one or  adds one to the slideIndex.
The showDiv() function hides (display="none") all elements with the
class name "mySlides", and displays (display="block") the element with
the given slideIndex.
If the slideIndex is higher than the number of elements (x.length),
the slideIndex is set to zero.
If the slideIndex is less than 1 it is set to number of elements
(x.length).

source: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_self

<button class="w3-button w3-display-left" onclick="plusDivs(-1)">❮</button>
<button class="w3-button w3-display-right" onclick="plusDivs(+1)">❯</button>

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
 var i;
 var x = document.getElementsByClassName("mySlides");
 if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length} ;
  for (i = 0; i < x.length; i++) {
   x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
}


text:
Q: Calculate pdf of distribution I have a normal distribution how can I calculate pdf(probability density function) value from it
#Distribution
from scipy import stats
Distribution = stats.norm(10, 9)

A: from scipy import stats

def pdf(x):
    return Distribution.pdf(x)

pdf(10)

--> 0.04432692004460363


text:
Q: Deployment according to environment and user privileges through TFS CI I have trying to implement CI for my desktop .NET application. But I am stuck at how to implement some stuff.
According to the requirements, I need to implement a filter while releasing the build according to user privileges and also filter the funtionalities that need not be installed on production.
I used to do this manually using a manifest.xml but now it seems a bit tidious to implement the same through TFS without using the Manifest.
My manifest looks like this:
<?xml version="1.0" encoding="Windows-1252"?>
<Manifest UpdaterVersion="3.33.7.717">
  <f t="DLL" v="0.86.5.0" p="Module1.dll" />
  <f t="DLL" v="1.26.2.123" d="true" x="true" p="File\Module2.dll" />

In this example "d" is for dll not be installed on production and "x" is for power user only.
Can anyone help me find a solution for this?


text:
Q: .htaccess with strange code So my .htaccess file is looking like this:
    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>

    php_value max_execution_time 1800

    # END WordPress

    #RewriteCond %{HTTP_USER_AGENT} Firefox\/40\.1
    #RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR]
    #RewriteCond %{REQUEST_URI} ^(.*)?xmlrpc\.php(.*)$ [OR]
    #RewriteCond %{REQUEST_URI} ^(.*)?wp-admin(.*)$
    #RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.121$
    #RewriteRule ^(.*)$ - [R=403,L]

SetEnvIfNoCase User-Agent "Firefox/40.1" tool Deny from env=tool

After the # END Wordpress looks pretty strange. I searched google and found that "SetEnvIfNoCase" line shouldn't be there. Is it correct?

A: Everyone who visits a site leaves behind a trace of how they accessed that website.
For example: Chrome leaves behind Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36
Some spam bots (automated programs hackers unleash first, to find vulnerable websites and WordPress installations) leave behind a fake trace. (By the way, this trace is called "user-agent".)
Apparently, this particular web hosting company has suffered a massive attack from a particular spam bot with fake trace identification ("user-agent") of "Firefox/40.1". (Firefox never had such a version.)
All the recommended code does is block access to visits with that particular user-agent.


text:
Q: GraphQL w/ Laravel Lighthouse @belogsTo same model I'm trying to use the @belongsTo relation with this test table employees https://www.w3resource.com/sql-exercises/employee-database-exercise/index.php
I'm using Laravel + Lighthouse
This is the response I'm trying to get
{
emp_name: JONAS
job_name: MANAGER
   {
     { emp_name: SCARLET }
     { emp_name: FRANK }
   }
}

GraphQL-playground query:
-------------- this is wrong sorry, I'm not sure how to do it
{
queryemployees(emp_id:65646){
  emp_name
  job_name
}
}

schema.graphql
type Employee{
 emp_id: ID!
 emp_name: String
 job_name: String
 manager_id: ID
 manager: Employee @belongsTo
}

type Query{
  queryemployees(emp_id:ID!) Employee @find
}

This is my App\Models\Employee.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{

    protected $table = 'employees';
    protected $fillable = ['emp_id', 'emp_name', 'job_name ', 'manager_id', 'hire_date', 'salary ', 'commission', 'dep_id'];

    public function employees(): BelongsTo
    {
        return $this->belongsTo('App\Models\Employee', 'manager_id');
    }

    public function manager(): HasMany
    {
        return $this->hasMany('App\Models\Employee', 'emp_id', 'manager_id');
    }

A: Your GraphQL-playground query needs to change
{
  queryEmployees(emp_id: 65646) {
    emp_id
    emp_name
    job_name
    manager {
      emp_id
      emp_name
    }
  }
}

I think your id field is mandatory in response. You need to specify everything you need in the response in GraphQL-playground.
Also you model relationships are in reverse.
employees should be hasMany('App\Models\Employee', 'manager_id', 'emp_id')
manager should be belongsTo('App\Models\Employee', 'manager_id', 'emp_id')
https://laravel.com/docs/7.x/eloquent-relationships#one-to-many


text:
Q: Coloring table rows - 3 rows, 3 different colors? I want to set the background color of my table rows to 3 different colors, basically like this:
Row 1 - Red
Row 2 - Blue
Row 3 - White
Initally I've had only two different colors where I used this tr:nth-child(2n+3) {background: #6bb8ff}
But I guess this can't work for 3 different colors as for example the 6th row would match every 3rd and every 2nd row ?
Is there any other way to do this, or am I thinking too complicated ? :-)

A: You can use :nth-child(3n+3) for every third element.

A: Why not, use classes to show the rows. If you're using a scripting language to output code, this shouldn't be too hard to implement
CSS:

HTML

Roeeels	Rofles

Roeeels	Rofles

Roeeels	Rofles

Roeeels	Rofles

Roeeels	Rofles

Roeeels	Rofles

A: :nth-of-type(3n), :nth-of-type(3n+1),:nth-of-type(3n+2)

did the trick.

A:

Row1

Row2

Row3

Row4

Row5

Row6

Row7

table tr:nth-child(3n+1)
{
 color:red;
}
table tr:nth-child(3n+2)
{
 color:blue;
}
table tr:nth-child(3n+3)
{
 color:white;
}

Working Example


text:
Q: Json and System.JSON in Delphi I have this Json
{
  "Sucess": true,
  "Msg": "OK",
  "Ret": {
    "First": 0,
    "Next": true,
    "Total": 60,
    "Itens": [
      {
        "ID": 212121,
        "Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
        "LcID": 9898,
        "Oclao": false,
        "Lal": {
          "ID": 12202,
          "Name": "pppppppppppppppppp",
          "Pais": "Brasil",
          "Dtc": 0.0
        },
        "Subtipo": {
          "ID": 7458,
          "Desc": "mnmnmnmnn"
        },
        "Tipo": {
          "Sit": "cor1",
          "Sitrm": 0,
          "Name": "Shsdfow"
        },
        "Qtde": 0,
        "Qntcoes": 0,
        "Pubum": "adfsdfsdfs",
        "Evias": {
          "arq": {
            "Mo": [
              "site.com"
            ],
            "Moir": [
              "site.com"
            ]
          }
        }
      },
      {
        "ID": 9797878,
        "Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
        "LcID": 9898,
        "Oclao": false,
        "Lal": {
          "ID": 12332,
          "Name": "pppppppppppppppppp",
          "Pais": "Brasil",
          "Dtc": 0.0
        },
        "Subtipo": {
          "ID": 7458,
          "Desc": "mnmnmnmnn"
        },
        "Tipo": {
          "Sit": "cor1",
          "Sitrm": 0,
          "Name": "Shsdfow"
        },
        "Qtde": 0,
        "Qntcoes": 0,
        "Pubum": "adfsdfsdfs",
        "Evias": {
          "arq": {
            "Mo": [
              "site.com"
            ],
            "Moir": [
              "site.com"
            ]
          }
        }
      }
    ]
  }
}

however, I can only take the values of the first items "Sucess, Msg and Ret"
I'm doing as follows
var
 JSONValue, jv: TJSONValue;
 joName: TJSONObject;
 data: TBytes;
 sHtmlResp, sTemp : String;
begin
  sHtmlResp := '[' + sHtmlResp + ']';
  data := TEncoding.ASCII.GetBytes(sHtmlResp);
  JSONValue := TJSONObject.ParseJSONValue(data, 0);
  for jv in JSONValue as TJSONArray do
   begin
    joName := jv as TJSONObject;
    sTemp:= joName.Get('Msg').JSONValue.Value;
   end;
end;

sHtmlResp contains the string json.
I've tried some other ways to get the most unsuccessful field, how do I get the sub-items as "Ret", "Items" and so on.
A detail, had to add '[' ']' in the JSON string I get, otherwise I can not get even the first fields.
Thank!

A: Ret is a subobject so you need to access it as such.  It has its own values and an array of subobjects, and so on.
Try this:
var
 joName, joRet, joItem: TJSONObject;
 joItems: TJSONArray;
 sHtmlResp, sMsg: String;
 bSuccess: Boolean;
begin
  sHtmlResp := ...; // original JSON without added braces around it
  joName := TJSONObject.ParseJSONValue(sHtmlResp) as TJSONObject;

  bSuccess := joName.GetValue('Success') is TJSONTrue;
  // if you are using Delphi 10 Seattle or later, you can use this instead:
  // bSuccess := (joName.GetValue('Success') as TJSONBool).AsBoolean;

  sMsg := joName.GetValue('Msg').Value;

  joRet := joName.GetValue('Ret') as TJSONObject;
  // use joRet.GetValue() as needed ...

  joItems := joRet.GetValue('Itens') as TJSONArray;
  for i := 0 to joItems.Count-1 do
  begin
    joItem := joItems.Items[i] as TJSONObject;
    // use joItem.GetValue() as needed ...
  end;
end;

A: If each object/sub-object have unique ObjectID (name).
The simple way is using this function
function ExtractJsonParm(parm:string;h:string):string;
var r:integer;
begin
  r:=pos('"'+Parm+'":',h);
  if r<>0 then
    result := copy(h,r+length(Parm)+4,pos(',',copy(h,r+length(Parm)+4,length(h)))-1)
  else
    result:='';
end;

Usage:
begin
  Writeln(ExtractJsonParm('First',Value));
  Writeln(ExtractJsonParm('Next',Value));
  Writeln(ExtractJsonParm('Total',Value));
end;

Outputs:
0
true
60

A: Using jsonDoc it would be
JSON(sHtmlResp)['Msg']

optionally enclosed in VarToStr to enforce type (and also silently convert Null to empty string value).
As noted in the comments by Remy: no need to enclose in [] as this enforces the outer array.


text:
Q: Parse Replacement Literal in Visual Studio Snippet
Possible Duplicate:
Formatting Literal parameters of a C# code snippet

EDIT: This can be closed. Found an exact duplicate, seems there is no solution. =(
Exact Duplicate:
Formatting Literal parameters of a C# code snippet
Is there any way to parse a replacement literal when writing a snippet? I'd like to do something like the following:
<Literal>
    <ID>PropertyName</ID>
</Literal>

User replaces PropertyName with 'MyProperty' and the results are such:
private object _myProperty;

public object MyProperty
{get;set;}

Note the capitalization. I need a way to parse the replacement literal and manipulate it. The underscore is trivial, simply a matter of hard coding that in.
Any chance here?
Edit; full snippet:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>MVVM Public Property</Title>
      <Author>Michael Leide</Author>
      <Description>Adds a public property with private backing and property changed event support.</Description>
      <Shortcut>propvm</Shortcut>
    </Header>

    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>PropertyType</ID>
          <Default>object</Default>
        </Literal>

        <Literal Editable="true">
          <ID>PropertyName</ID>
          <Default>PropertyName</Default>
        </Literal>
      </Declarations>

      <Code Language="csharp" Kind="" Delimiter="$">
        <![CDATA[
        $PropertyType$ _$PropertyName$;

        public $PropertyType$ $PropertyName$ {
            get {
                if (_$PropertyName$ == null)
                    _$PropertyName$ = new $PropertyType$();
                return _$PropertyName$;
            } set {
                _$PropertyName$ = value;
                this.OnPropertyChanged("$PropertyName$");
        }   }
        ]]>
      </Code>

    </Snippet>
  </CodeSnippet>
</CodeSnippets>

A: Unfortunately you can't transform your PropertyName into propertyName directlly. The best way to go about this is to include a third literal to specify the backing field. This prevents the ambiguity in your current literal and only adds an extra couple keystrokes.
The Declarations block looks like this:
  <Declarations>
    <Literal Editable="true">
      <ID>PropertyType</ID>
      <Default>object</Default>
    </Literal>

    <Literal Editable="true">
      <ID>PropertyName</ID>
      <Default>PropertyName</Default>
    </Literal>

    <Literal Editable="true">
      <ID>BackingPropertyField</ID>
      <Default>backingPropertyField</Default>
    </Literal>
  </Declarations>

And the code block becomes:

    public $PropertyType$ $PropertyName$ {
        get {
            if (_$BackingPropertyField$ == null)
                _$BackingPropertyField$ = new $PropertyType$();
            return _$BackingPropertyField$;
        } set {
            _$BackingPropertyField$ = value;
            this.OnPropertyChanged("$PropertyName$");
    }   }
    ]]>
  </Code>

You can then just tab through and specify the desired names.


text:
Q: Verificacion de contraseña encriptada no funciona de ninguna manera ¡Hola! Llevo partiendome la cabeza desde hace varios meses porque no puedo verificar una contraseña encriptada, tengo este codigo:
<?php
include ("conexion.php");

session_start();
session_destroy();

if (isset($_POST['ingresar'])) {
if (!empty($_POST['username']) && !empty($_POST['password'])) {

    $usuario = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    echo "$password<br>";

    $query_hash = mysqli_query($conn, "SELECT password FROM usuarios WHERE username = '$usuario'");
    $row_hash = mysqli_fetch_array($query_hash);
    $hash = $row_hash['password'];

    echo "$hash";

    $query = mysqli_query($conn, "SELECT `username`, `password`, `exclusivo` FROM `usuarios` WHERE username = '$usuario' AND password = '$password'");
    if (password_verify($password, $hash)){ y aqui mi codigo }

Esto es el hash de la contraseña en el login, todo funciona menos la verificacion.
Este es el registro:
<?php

include ("conexion.php");

if (isset($_POST['registrar'])) {
    if (strlen($_POST['username']) > 2 && strlen($_POST['password']) > 6) {
        if ($_POST["password"] === $_POST["password2"]) {

        $mail = $_POST['mail'];
        $username = $_POST['username'];
        $password = $_POST['password'];
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $exclusivo2 = 0;
        $torneosJugados = 0;
        $torneosGanados = 0;

        $consulta = "INSERT INTO `usuarios`(`mail`, `username`, `password`, `torneosJugados`, `torneosGanados`, `exclusivo`) VALUES ('$mail','$username','$hash','$torneosJugados', '$torneosGanados', '$exclusivo2')";
        $resultado = mysqli_query($conn,$consulta);

Mi base de datos de usuarios mysql es:

*

*Id

*username

*password

Estos son los datos necesarios, no quiero ahogarlos con codigos que ya funcionan, pero si necesitan mas diganme y lo edito.
Basicamente, mi problema es la verificacion de los hash que estoy haciendo, cuando los mando a encriptar se encriptan facilmente y rapido, no hay problema, eso funciona bien.
El problema viene al verificarlo, primero no utilice password_verify, ya que supuse que con solo comparar las contraseñas ya estaria (codigo sencillo, encripto en password que me da el usuario al hacer login y el que ya esta en la base de datos), pero entonces no funciono.
Luego busque como loguearse con contraseña encriptada y todos dicen lo mismo "utiliza password verify", bien, utilizo password verify como esta en el codigo que les pase y nada, no funciona, ya intente encriptando la contraseña que me da el usuario, sin encriptarla, comparandolas, separando en procedimientos el metodo de encriptacion (Tomo la contraseña en una variable, tomo la variable y la encripto, lo que yo hago es encriptarla directamente como ven en el codigo), me fije si el varchar era muy corto y lo alargue (primero 255, ahora 600...) tampoco funciono, tambien utilice BLOWFISH, es exactamente lo mismo, le puse salt, no le puse salt, le agregue eso de que tenga un valor de "14" (no recuerdo el nombre, mala mia), y nada funciono.
Sinceramente no se que mas hacer, busque por todos lados y no encontre respuesta, no se porque no se verifican las contraseñas.
Algo que puede ayudar:
Acabo de hacer un echo de las 2 contraseñas que tengo (la que me da el usuario y la que esta registrada en la base de datos) ya encriptadas (ambas con el mismo metodo) y las 2 contraseñas son diferentes, por lo que se esto esta bien, ya que parece ser que el metodo de encriptacion funciona porque 2 contraseñas iguales no daran la misma encriptacion.
Por favor, una ayuda, espero haberme explicado bien, porque de verdad llevo meses con esto y nada, ni un avance.
REPITO: Todo el codigo funciona a la perfeccion, no hay ningun problema con nada mas que co nla verificacion de la contraseña encriptada, el problema es que no quiero utilizar una base de datos sin contraseñas encriptadas, ya que bueno, obvias razones...
EDIT: Tambien, olvide mencionar que el codigo que subi es mi ultimo intento, el select de la contraseña del usuario no lo usaba, pero lo tome para comparar las contraseñas, tampoco los echos y demas.
Aqui tienen un ejemplo de 2 contraseñas iguales encriptadas y comparadas (tanto con password verify como una comparacion normal con un if)

*

*$2y$10$b7WUwoNWpVI0/j1hKZVtH.dKxhG9rUZhyjPv3XKfaHymqfWrIRm1S

*$2y$10$ASb4Lh.J6bQZeD6VRCWaRe1hs0aqceZTjoaWcZ2i9YIjmXmvW9Tbu

A: Por que no lo haces de la forma que te recomiendo.
Código:
session_start();
include ("conexion.php");

if (isset($_POST['ingresar'])) {

  $user = $_POST['username'];
  $pass = $_POST['password'];

  if (empty($user)) {
     echo 'El campo <b>username<\/b> es requerido';
  } elseif (empty($pass)) {
     echo 'El campo <b>password<\/b> es requerido';
  }

  $query = mysqli_query($conn, "SELECT username, password, exclusivo FROM usuarios WHERE username = '".$user."' AND password = '".$pass."'");
  if (password_verify($pass, $query['password'])) {
    #:: Aquí tu código si la contraseña coincide...
  } else {
    echo 'La contraseña no es valida';
  }
}

De esta forma sabemos en que if esta dando el error y lo muestra en pantalla. Intentalo y me comentas que tal.

A: Despues de revisar la documentacion de php, sobre las funciones de password_hash() y password_verify() (que yo no uso) me doy cuenta que el problema posiblemente se debe al "salpimentado" de la encripcion de la contraseña, es posible que se este generando una "sal" (salt en ingles) diferente al momento de encriptar y verificar.
Yo uso un metodo diferente (a la vieja escuela) y uso una combinacion de texto, password y "sal" con lo que genero un hash que guardo en la base de datos, pero, independientemente del metodo que uses, primero te debes asegurar de que la base de datos y tu script manejen la misma codificacion (en mi caso UTF8), en segundo lugar debes checar que lo que guardaste es EXACTAMENTE igual a lo que generaste (en lugar de un echo, podrias usar error_log())...
Una vez que estes segura de que la codificacion esta correcta y lo guarado en la db es igual a lo generado, deberia de funcionar, en caso de que no funcione, te recomendaria que crearas tu propia funcion para generar el hash y guardarlo.
Espero que esto ayude.
P.D. hay una gran cantidad de funciones en php que tienen ciertas limitaciones (este es un ejemplo) por lo que prefiero el camino largo (mas rapido?) y que no depende de futuras implementaciones o modificaciones de php (otro ejemplo es el manejo de fechas).


text:
Q: Remove post date on my pages Immediately after my {block:Posts} I have placed a date that will display the post date on top of every post I make. But I realized this piece of code is also rendered on my Pages as well and thus produces unwanted commas and
s. How can I let Tumblr know that I only want these dates to appear on my main blog page and not in any other pages?
Update:
     {block:Text}
{DayOfWeek}, {DayOfMonth} {Month} {Year}

                        {block:Title}

{Title}

                        {/block:Title}

                        {Body}
                        {block:IndexPage}

                             {NoteCountWithLabel}

                        {/block:IndexPage}

                {/block:Text}

A: Date Block and Variables
Currently the OP is using just the date variables, without the block. The block checks to see if the post has a date, and then render its.
As pages don't have a date, the block check fails and the date isn't rendered.
{block:Posts}
{block:Date}
{DayOfWeek}, {DayOfMonth} {Month} {Year}
{/block:Date}
{/block:Posts}

On a sidenote, the {block:Date} is a handy way to render markup (shares, comments, etc) specific to posts only.
Reference
Date Operators https://www.tumblr.com/docs/en/custom_themes#dates


text:
Q: Parsing and processing tabular .txt file I'm supposed to write a program that reads a file and then calculates the max and min and the average of the height and weight columns and adds an additional columnn that has the BMI calculated based on each height and weight.
The file is formatted like so:
Name        Height(m)   Weight(kg)
Joe         1.82        72.57
Mary        1.60        63.50
Dion        1.90        90.71
Kayla       1.72        66.31
Jose        1.78        70.23
Sofia       1.63        65.12
Erik        1.98        92.21
Sara        1.57        65.77

The output should be as follows:

I have the very very basics down (reading the text file). I know what I need to do next which is iterate through each column and add up all the data to get the average, etc etc. But I don't know how to code for it. You don't have to write the whole code for me because I know I don't have much, but if someone could just point me in the right direction/give me a hint as to how to proceed it'd be very helpful.
data_file = open("data.txt", "r")

total = 0
for line_str in data_file:
    line_str = line_str.strip()
    total+=1

A: The method you need is str's split(). The takes a string, like a line in a file, and breaks it up in to multiple chunks. After that you'll also need to use float() to parse the floating point number from the string chunk.

A: With Pandas library the solution is simple:
import pandas as pd

df = pd.read_csv("data.txt", delim_whitespace=True)
df['BMI'] = df['Weight(kg)'] / (df['Height(m)']**2)
df.describe()

A: Your problem can be solved by this way:
data_file = open("data.txt", "r")`

total = 0

for line_str in data_file:
         [float(s) for s in line_str.split() if s.isdigit()]


text:
Q: How to use "longClickGesture" in appium UiAutomator2 with x and y coordinates? I'm fairly new to Appium, and trying to understand mobile gestures using UIautomator2 . The official documentation provides JAVA syntax on how to use the "longClickGesture" when element id is present.

((JavascriptExecutor) driver).executeScript("mobile: longClickGesture", ImmutableMap.of(
    "elementId", ((RemoteWebElement) element).getId()
));

Can someone tell me how to use the above syntax when element id is absent and only with x and y coordinates.
I tried searching in different forums but could not see any direct answers.


text:
Q: Can Apache 2 be configured to start sending gzipped data early? We have Apache set up to gzip compress html pages before they are sent to the client browser.
However, some of our pages are slowish to generate and it seems that Apache is holding on until it has the complete page, compressing it, then sending it to the browser.
There are big chunks of the page (the main important bits) that are actually generated and output fairly quickly.
Is it possible to configure Apache to start compressing and send data for the page as soon as the script starts outputting something? Is it is, can you offer any help is how to do this?
If not, can you suggest any other way to get gzip compression working for the server?
The scripts that generate the pages are written in PHP. We are using Apache 2.0 on Linux.

A: We had this same problem with a perl backend.  I'm looking up the docs that pointed me @ the solution.  It ultimately had to do with gzip trying to compress the entire document to compute the content-length.
We had some long-running scripts that this ruined the user-experience for -- instead of getting output incrementally, they were waiting for 2-3 mins with no activity!
Update:
I'm afraid I can't find it.  Reviewing our activity logs, it seems I simply disabled it on our web server, then moved an nginx-based frontend for this and other reasons (it will gzip with chunked encoding w/o having to send content-length)
Try upgrading to Apache 2.2, iirc newer versions of apache handled the chunked/gzip thing much better.

A: It's called 'Early flushing', and its mostly a matter of just running 'flush();' before the entire page has been generated.  Normally, an optimised PHP server will, as you've found, buffer the entire page, but a deliberate call to flush() overrides that.  The tips page on Yahoo has more information: http://developer.yahoo.com/performance/rules.html#flush

A: Send flush() from time to time or after your blocks and unless you use obstart(), apache will send chunked responses.


text:
Q: Second Order and Beyond for Multivariable Taylor Series I am looking for reasons why an engineer might want to learn about multivariable Taylor Series beyond order one.
I have no problem seeing the value of single variable Taylor Series.
I have quite a few uses for the first order multivariable Taylor Series:
$$f(x_1,\dots,x_n)\underset{x_i\approx a_i}{\approx} f(a_1,\dots,a_n)+\sum_{i=1}^nf_{x_i}(a_1,\dots,a_n)(x-a_i).$$
I have one application of two-variable order-$n$ Taylor series: I think the derivations of higher-order Runge-Kutta formulae require it.
One of the nice applications of single variable Taylor Series to engineering is the simplification of formulae. For example, in the context of beam deflection, the exact but rather cumbersome
$$\delta=e\cdot \left(\sec\left(\sqrt{\frac{P}{EI}}\cdot \frac{L}{2}-1
\right)\right),$$
is well-approximated (using the Maclaurin series of $\sec x$), under reasonable assumptions, by the 'neat'
$$\delta\approx \frac{ePL^2}{8EI}.$$
However, I can't envision similarly nice examples using two-variable Taylor Series.

So my question is, why do engineers learn about order $n$ ($n\geq 2$)
  multivariable Taylor series?

I am hoping to end up with a nice exam question for my class that isn't as boring as "find the second order Taylor Series expansion of (some generic) $z=f(x,y)$ about $(a,b)$".

A: Apart from the obvious reason, that knowledge is a value in itself, there are indeed practical engineering application of multivariate calculus about order $n \geq 2$.
One example is the study of stability, which clearly benefits from Taylor expansions up to second order.
There are examples from computational methods too: if the engineer is using a Finite Element code and at some point along an analysis gets a "non positive definite Hessian", he would certainly benefit from knowing about second-order expansions to understand what is going on.
Another fitting example in my view is given by Laplace's method (alternatively, saddle-point) to approximate the solution of certain integrals, very common in Statistical Mechanics and not rare at all in Engineering. The method mandatorily requires a second order expansion.
Talking about thermodynamics, how would one prove the principle of minimum energy to an engineer not accustomed to second order expansions? With multivariate Taylor expansions, it takes just a moment, by expanding the entropy $S$ as function of an internal parameter $X$ and energy $U$ to second order, as $ \frac{\partial S}{\partial X} = 0$
$$ \mathrm{d}S \approx \frac{\partial^2 S}{\partial X^2}\mathrm{d}X^2 +\frac{\partial S}{\partial U} \mathrm{d} U $$ and the minimum nature of $U$ is on display.
Moreover, referring to elasticity as in your post,  the elastic moduli are related to the strain energy function $W$ via $$ \mathcal{C} = \frac{\partial^2 W }{\partial E^2} $$ where $E$ stands for a deformation tensor, so a second-order expansion of the strain energy is needed.
In $1$ D the "first-order only" engineer could avoid the problem by looking at stress-strain curves only. Indeed, in $1D$  $$ \sigma = \frac{\mathrm{d} W}{\mathrm{d} \epsilon}$$ where $\epsilon$ stands for the strain. As for small enough strains $\sigma = E \epsilon$, in this case only first-order condsiderations are needed to estimate the elastic moduli
(in fact, by letting the experiment perform a differentiation).
But in a more general case, dealing for example with a biaxial test (and this is not an academic example for modern engineers busy with polymers), it can often be easier to start from the energy $W$, perform a multivariate expansion up to second order, and get the elastic moduli matrix out of it.
The difference stems from practical reasons: in a $1D$ test one stretches in one direction, and what happens in the other directions is easy to characterise.
In a biaxial test this is far more complex: it is difficult to impose one strain value along a given direction, while  the strain along the perpendicular direction is varied. In other words, it is difficult to "perform partial derivatives" experimentally.
All this could be especially useful, and releavant, when a component is  loaded by a constant stress state, on top of which small oscillations are superimposed. It is then useful to re-define the constant stress-state as the "unloaded" state, and calculate "fictitious" elastic moduli.

A: Least Squares Best Fit Methods are well known for a point, a straight
line, a circle, a conic section, in general: for a simple figure.
But that's not really cool. I'd rather have some least squares best fit
method with complicated figures, for example: two points, crossing
or parallel lines, a bunch of circles, the image of a character 'A'
- my ultimate dream being the least squares best fit with music score elements, a treble clef for example :-)
So far so good about dreams. But one has to start somewhere ..
Let's consider the most simple case (I think) in two dimensions: a least squares
best fit with two points instead of one. Writing the minimum principle
for this case is not too difficult.
Let the function  M  to be minimized be defined by:
$$
M(a,b,p,q) = \sum_k \left[ (x_k - a)^2 + (y_k - b)^2 \right].\left[ (x_k - p)^2 + (y_k - q)^2 \right]
$$
Here the $(x_k,y_k)$ are the fixed points of a cloud in the plane and we
are satisfied if we can find some fairly unique points $(a,b)$ and $(p,q)$ .
A procedure to accomplish this is rather straigtforward. Differentiate
the above sum to $\,(a,b,p,q)\,$ and put the four outcomes of these partial
differentiations equal to zero:
$$
F_a = \frac{\partial M(a,b,p,q)}{\partial a} = - 2 \sum_k (x_k - a)\left[ (x_k - p)^2 + (y_k - q)^2 \right] = 0\\
F_b = \frac{\partial M(a,b,p,q)}{\partial b} = - 2 \sum_k (x_k - b)\left[ (x_k - p)^2 + (y_k - q)^2 \right] = 0\\
F_p = \frac{\partial M(a,b,p,q)}{\partial p} = - 2 \sum_k (x_k - p)\left[ (x_k - a)^2 + (y_k - b)^2 \right] = 0\\
F_q = \frac{\partial M(a,b,p,q)}{\partial q} = - 2 \sum_k (x_k - q)\left[ (x_k - a)^2 + (y_k - b)^2 \right] = 0
$$
The next step is to employ a four dimensional
Newton-Raphson method to find the zeroes.
The one-dimensional equivalent is well known:
$$
x_{n+1} = x_n - \frac{F(x_n)}{F'(x_n)} \quad \Longleftrightarrow \quad F'(x_n)(x_{n+1}-x_n) = - F(x_n)
$$
It generalizes as follows ( with $\Delta x = x_{n+1}-x_n$ ) and mind the symmetry:
$$
\large \begin{bmatrix} \frac{\partial^2 M}{\partial a^2} & \frac{\partial^2 M}{\partial a \partial b}
& \frac{\partial^2 M}{\partial a \partial p} & \frac{\partial^2 M}{\partial a \partial q} \\
\frac{\partial^2 M}{\partial a \partial b} & \frac{\partial^2 M}{\partial b^2}
& \frac{\partial^2 M}{\partial b \partial p} & \frac{\partial^2 M}{\partial b \partial q} \\
\frac{\partial^2 M}{\partial a \partial p} & \frac{\partial^2 M}{\partial b \partial p}
& \frac{\partial^2 M}{\partial p^2} & \frac{\partial^2 M}{\partial p \partial q} \\
\frac{\partial^2 M}{\partial a \partial q} & \frac{\partial^2 M}{\partial b \partial q}
& \frac{\partial^2 M}{\partial p \partial q} & \frac{\partial^2 M}{\partial q^2} \end{bmatrix}_n
\begin{bmatrix} \Delta a \\ \Delta b \\ \Delta p \\ \Delta q \end{bmatrix} = - \begin{bmatrix} F_a \\ F_b \\ F_p \\ F_q \end{bmatrix}_n
$$
The matrix on the left is known as the Hessian matrix,
commonly denoted as $\,H$ . We need the inverse of it:
$$
    H_n\,\Delta x = - F_n \quad \Longrightarrow \quad x_{n+1} = x_n - H_n^{-1}F_n
$$
So here are the OP's second order multivariable derivatives:
$$
\frac{\partial^2 M}{\partial a^2} = \frac{\partial^2 M}{\partial b^2} = 2 \sum_k \left[ (x_k - p)^2 + (y_k - q)^2 \right] \\
\frac{\partial^2 M}{\partial p^2} = \frac{\partial^2 M}{\partial q^2} = 2 \sum_k \left[ (x_k - a)^2 + (y_k - b)^2 \right] \\
\frac{\partial^2 M}{\partial a \partial p} = 4 \sum_k (x_k - a)(x_k - p) \qquad
\frac{\partial^2 M}{\partial a \partial q} = 4 \sum_k (x_k - a)(x_k - q) \\
\frac{\partial^2 M}{\partial b \partial p} = 4 \sum_k (x_k - b)(x_k - p) \qquad
\frac{\partial^2 M}{\partial b \partial q} = 4 \sum_k (x_k - b)(x_k - q) \\
\frac{\partial^2 M}{\partial a \partial b} = \frac{\partial^2 M}{\partial p \partial q} = 0
$$
Free software source implementing all this numerically and graphically is
found at my website .
It turns out that, given some neatly chosen conditions, iterations converge rather quickly to a result.Here is an animation of $10$ iterations as generated by our software. The $\color{red}{\mbox{red dots}}$ correspond with the points $(a,b)$ and $(p,q)$ that are approaching to a best fit with the two squares of black dots.

Numerically:

( 0.030000000, 0.030000000)  ;  ( 3.970000000, 3.970000000)
( 0.660367766, 0.655184806)  ;  ( 3.346246442, 3.338009121)
( 1.067931194, 1.059662172)  ;  ( 2.947311493, 2.933165294)
( 1.224322703, 1.215456066)  ;  ( 2.610372656, 2.591778103)
( 1.483524248, 1.473141085)  ;  ( 2.587165222, 2.567701858)
( 1.492857336, 1.482684318)  ;  ( 2.507701174, 2.488004719)
( 1.500161598, 1.489958755)  ;  ( 2.505384218, 2.485704103)
( 1.500206864, 1.490003939)  ;  ( 2.505303084, 2.485623596)
( 1.500206877, 1.490003953)  ;  ( 2.505303074, 2.485623586)
( 1.500206877, 1.490003953)  ;  ( 2.505303074, 2.485623586)

A: The result of an observation of a function $\,f(x,y,z)\,$
with Gaussian blur $\,G(x,y,z)\,$ for example is
in general a convolution integral: $$ \overline{f} =
 \iiint G(\xi,\eta,\zeta)\,f(x-\xi,y-\eta,z-\zeta)\,d\xi\,d\eta\,d\zeta $$
Here $\,G\,$ is the kernel function of the blur and $\,f\,$ is the function to be
observed. The function $\,f\,$ is developed into a Taylor series around
$\,(\xi,\eta,\zeta)=(0,0,0)$ :
$$ f(x-\xi,y-\eta,z-\zeta) \; \approx \; f(x,y,z) $$
$$ - \xi \frac{\partial f}{\partial x} - \eta \frac{\partial f}{\partial y} - \zeta \frac{\partial f}{\partial z} $$
$$ + \frac{1}{2} \xi^2 \frac{\partial^2 f}{\partial x^2} + \frac{1}{2} \eta^2 \frac{\partial^2 f}{\partial y^2}
   + \frac{1}{2} \zeta^2 \frac{\partial^2 f}{\partial z^2} $$
$$ + \xi \eta \frac{\partial f}{\partial x \partial y} + \eta \zeta \frac{\partial f}{\partial y \partial z}
   + \zeta \xi \frac{\partial f}{\partial z \partial x} $$
In this expression the partial differential quotients are no longer dependent
on $\,(\xi,\eta,\zeta)$ , because they are calculated for
$\,(\xi,\eta,\zeta)=(0,0,0)$ . Therefore the convolution integral is approximately
equal to:
$$ f(x,y,z) \iiint \, G \, d\xi\,d\eta\,d\zeta \\ \, - \, \frac{\partial f}{\partial x}
   \iiint \xi \, G \, d\xi\,d\eta\,d\zeta \, - \, \frac{\partial f}{\partial y}
   \iiint \eta \, G \, d\xi\,d\eta\,d\zeta \, - \, \frac{\partial f}{\partial z}
   \iiint \zeta \, G \, d\xi\,d\eta\,d\zeta \\
+ \frac{1}{2} \frac{\partial^2 f}{\partial x^2}\iiint \xi^2  \, G \, d\xi\,d\eta\,\zeta
+ \frac{1}{2} \frac{\partial^2 f}{\partial y^2}\iiint \eta^2 \, G \, d\xi\,d\eta\,d\zeta
+ \frac{1}{2} \frac{\partial^2 f}{\partial z^2}\iiint \zeta^2\, G \, d\xi\,d\eta\,d\zeta \\
+ \frac{\partial f}{\partial x \partial y}\iiint \xi \eta   \, G \, d\xi\,d\eta\,d\zeta
+ \frac{\partial f}{\partial y \partial z}\iiint \eta \zeta \, G \, d\xi\,d\eta\,d\zeta
+ \frac{\partial g}{\partial z \partial x}\iiint \zeta \xi  \, G \, d\xi\,d\eta\,d\zeta
$$
The first integral is by definition equal to $\,1$ . The next three integrals are
equal to the expectation value of the Gaussian kernel function, and therefore equal
to $\,0$ . The next three integrals are equal to the spreads of the Gaussian kernel function
in the different coordinate directions. The last three integrals, at last, are
zero. Thus: $$ \overline{f} \approx
   f + \frac{1}{2} \sigma_x^2 \frac{\partial^2 f}{\partial x^2} + \frac{1}{2} \sigma_y^2 \frac{\partial^2 f}{\partial y^2}
     + \frac{1}{2} \sigma_z^2 \frac{\partial^2 f}{\partial z^2} = f + \frac{1}{2} \sigma^2 \nabla^2 f $$
An asymptotic approximation for large distances, which can also be found
in any decent book about Statistics, where the last equality is for the
isotropic case only.
One possible application is the
renormalization
of singularities, for example the Electric field
of a point charge:
$$
E(r) = \frac{q}{4\pi\epsilon_0 r^2} \quad \mbox{with} \quad
\begin{cases} q = \mbox{(point) charge} \\ \epsilon_0 = \mbox{dielectric constant} \\ r = \mbox{distance to point} \end{cases}
$$
The far away field can be calculated without even knowing about the convolution integral:
$$
\overline{E} \approx E + \frac{1}{2} \sigma^2 \nabla^2 E \qquad \mbox{with} \qquad
\nabla^2 \frac{1}{r^2} =
   \frac{1}{r} \frac{\partial^2}{\partial r^2} r \frac{1}{r^2} = \frac{2}{r^4}
$$
Hence:
$$
\overline{E} \approx E \left( 1 + \frac{\sigma^2}{r^2} \right) \quad \mbox{for} \quad r \gg \sigma
$$
The Electric field with Gaussian blur is:
$$
\overline{E}(x,y,z) = \left( \frac{1}{ \sigma \sqrt{2\pi} } \right)^3
   \iiint \frac{q}{4 \pi \epsilon_0 ( \xi^2 + \eta^2 + \zeta^2 ) } \,
   e^{\, - [ (\xi - x)^2 + (\eta - y)^2 + (\zeta - z)^2 ] / 2\sigma^2 }
   \; d\xi\,d\eta\,d\zeta
$$
A special case is the value of the renormalized field at the origin, which turns out to be nicely finite :
$$
\overline{E}(r=0) = \left( \frac{1}{ \sigma \sqrt{2\pi} } \right)^3 \frac{q}{\epsilon_0}
   \int_0^\infty e^{- r^2 / 2 \sigma^2 } d r =
   \left( \frac{1}{ \sigma \sqrt{2\pi} } \right)^3 \frac{q}{\epsilon_0}
   \frac{1}{2} \sigma \sqrt{2\pi} = \frac{q}{4 \pi \epsilon_0 \sigma^2 }
   = E(\sigma)
$$
Anything in between is somewhat more difficult ..


text:
Q: docker-compose mongo rails connection fails I have a rails application with mongodb, in development environment.
Unable to connect mongodb with docker. Can connect to local mongodb with same mongoid config. I tried changing host as localhost to 0.0.0.0 but did not work.
What is missing in the settings ?
My doubt is mongo in Docker hasn't started or binded. If i make changes in mongoid config to read: :nearest, it says no nodes found.
error message is,
Moped::Errors::ConnectionFailure in Product#index
Could not connect to a primary node for replica set #]>
Dockerfile
#FROM ruby:2.2.1-slim
FROM rails:4.2.1
MAINTAINER Sandesh Soni, <my@email.com>
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev
RUN mkdir /gmv
WORKDIR /gmv
# Add db directory to /db
ADD Gemfile /gmv/Gemfile
RUN bundle install
ADD ./database /data/db
ADD . /gmv

docker-compose.yml
web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  volumes:
    - .:/gmv
  ports:
    - "3000:3000"
  links:
    - db
db:
  image: mongo
  command: "--smallfiles --bind_ip 0.0.0.0 --port 27027 -v"
  volumes:
    - data/mongodb:/data/db
  ports:
    - "27017:27017"

A: On your host machine execute docker run yourapp env, then in output look for ip address related to your database. That ip address & port you need to use to connect to your database running in container.
Similar question asked here


text:
Q: How to fix " Error starting userland proxy: listen tcp 0.0.0.0:1433 with docker on windows 10 I can't run MySQL server images on docker (Windows 10 Pro), I'm using next command:
docker run -e "ACCEPT_EULA=Y" -e "Tel12345678!" -p 1433:1433 -d microsoft/mssql-server-linux


text:
Q: I'm getting an error from Google Play Services. Whats wrong with it? I'm using Google Play Services to get location.
In my tests, some times, when i'm using the device without use the WiFi, I get this error. I am not getting why sometimes it works and sometimes it does not work.
09-25 14:53:45.389: E/AndroidRuntime(7732): FATAL EXCEPTION: main
09-25 14:53:45.389: E/AndroidRuntime(7732): java.lang.NullPointerException
09-25 14:53:45.389: E/AndroidRuntime(7732):     at bsfsdfgdfgzsdfgsfgsdfga.Helper.GPS.onConnected(GPS.java:63)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at com.google.android.gms.internal.u.v(Unknown Source)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at com.google.android.gms.internal.u$f.a(Unknown Source)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at com.google.android.gms.internal.u$f.a(Unknown Source)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at com.google.android.gms.internal.u$b.A(Unknown Source)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at com.google.android.gms.internal.u$a.handleMessage(Unknown Source)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at android.os.Looper.loop(Looper.java:130)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at android.app.ActivityThread.main(ActivityThread.java:3687)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at java.lang.reflect.Method.invokeNative(Native Method)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at java.lang.reflect.Method.invoke(Method.java:507)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
09-25 14:53:45.389: E/AndroidRuntime(7732):     at dalvik.system.NativeStart.main(Native Method)

public class GPS implements
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener,
    LocationListener, com.google.android.gms.location.LocationListener {

private LocationRequest lr;
private LocationClient lc;
static Location location;
double latitude = 0;
double longitude = 0;
Context context;
static Boolean status = false;

public  GPS(Context context) {
    this.context = context;
    lr = LocationRequest.create();
    lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    lr.setInterval(5000);
    lr.setFastestInterval(1000);
    lc = new LocationClient(context, this, this);
}

@Override
public void onLocationChanged(Location location) {
    lc.removeLocationUpdates(this);
    lc.requestLocationUpdates(lr, this);

    location = lc.getLastLocation();
    latitude = location.getLatitude();
    longitude = location.getLongitude();

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    Log.e("GPS", ""+arg0);

}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i("GPS", "Google Play Services Conectado.");
    lc.requestLocationUpdates(lr, this);

    location = lc.getLastLocation();
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}

public double getLatitude() {
    return latitude;
}

public double getLongitude() {
    return longitude;
}

public void connect(){
    lc.connect();
}

public void disconnect(){
    lc.disconnect();
}

@Override
public void onDisconnected() {

}

public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}

}
double latitude;
double longitude;
LocationClient lc;
LocationRequest lr;
Location location;
Button bt;
TextView tv;
GPS gps;

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

     bt = (Button)findViewById(R.id.bt);
     tv = (TextView)findViewById(R.id.tv);

     gps = new GPS(this);

     bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
                TextView tv = (TextView)findViewById(R.id.tv);

                /*List<Address> ad = null;
                try {
                    Geocoder mGeocoder = new Geocoder(MainActivity.this);
                    ad =  mGeocoder.getFromLocation(latitude, longitude, 1);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                String ads = ""+ad.get(0).getAddressLine(0) + " "+ad.get(0).getAddressLine(1);
                */
                tv.setText(""+latitude + " "+longitude);
                Log.i("GPS", ""+latitude +  " "+longitude);

            }
        });

}

@Override
protected void onStart() {
    gps.connect();
    super.onStart();
}

@Override
protected void onStop() {
    gps.disconnect();
    super.onStop();
}

@Override
protected void onPause() {
    gps.disconnect();
    super.onPause();
}

}

A: The exception is getting at line-63 @ GPS.java. You may have missed null pointer checking at that line.
See that getLastLocation() method can return null if a location is not available.
Change the line
location = lc.getLastLocation();

with
location = lc.getLastLocation();
if(location != null){
    //do something with location
}

A: imranhasanhira is correct. Maybe you could also check if at least one provider is available to get user position. You said the crash happen when WiFi is off, and I suppose neither GPS and SIM card are "active" on your device.
Look here how to check if a provider is available (you could also open the location settings screen if any of the providers are available): Android detect location settings


text:
Q: VSCode dynamic JSON schema validation I have built project for a web application configuration. It includes generated (from TypeScript) JSONSchemas. To simplify - user can configure things like forms - field order (string[]), hidden fields(string[]) etc. JSON Schmeas are very helpful for users, who aren't too familiar with the configuration, and it validates some errors, that could rise from mistakes in the configuration.
But they cannot help in every situation - in those string arrays - user can put any string, and the schema will be valid.
What I would want to make - is some dynamic validation - when the user opens [ for the field order - he has to choose from the list of fields, that would be fetched from the APIs.
Something, like when you type packageName: ""  in the package.json dependencies - it gets a version for the given package.
I would think, that I would have to make some VSCode extension for this - but I don't know - where to start. Can someone point me in the direction - an example, where someone uses real time JSON schema validation would be grateful.

A: Found an answer by digging through vscode source code. Searched all files, that contains package.json and dependencies (regex search (package.json[\s\S\n]*dependencies)|(dependencies[\s\S\n]*package.json)) and found a class PackageJSONContribution and this was exactly what I was looking for.
Then I made a simple extension using yo code (as from the example of Your first extension).
Some interfaces and classes I was unable to import from vscode, I just made a local copies for my extension. Made my own class FooJSONContribution with the only difference -
it's getDocumentSelector() function changed to
    public getDocumentSelector(): vscode.DocumentSelector {
        return [{ language: 'json', scheme: '*', pattern: '**/foo.json' }];
    }

Adjusted extensions package.json activationEvents and added "onLanguage:json" (this could be optimised).
Adjusted activate event of the extension by adding
    const contribution = new FooJSONContribution(xhr, true);
    const disposableCompletionItemProvider = vscode.languages.registerCompletionItemProvider(
        contribution.getDocumentSelector(),
        new JSONCompletionItemProvider(contribution),
        '"',
        ':'
    );
    context.subscriptions.push(disposableCompletionItemProvider);

And that's it. All of the foo.json files now work like package.json files -
Things I need to do now - adjust the code of FooJSONContribution.ts to work for my own needs, for my own API's, for my own files.
I Uploaded this example here https://github.com/leqwasd/VsCodeAsyncJsonAutocomplete


text:
Q: Adding new entries to a ListView My goal is to be able to input two numbers into two separate EditText fields, do a quick calculation with the two numbers, and add the three numbers + the date to a list while keeping any old entries also so it will add another row to the table at the top.
 Date1  |  Num1  |  Num2  |  CalculatedNum3

 Date2  |  Num4  |  Num5  |  CalculatedNum6

Above would be a rough layout of the design of the ListView.
I've looked into Arrays, Strings and Adapters but I can't seem to wrap my head around them; how I could use them in this situation. Any assistance would be much appreciated.

A: What you'll need is a ListView.  A ListView is a view that orders its child views in a scrolling vertical list automatically depending on the elements present in the dataset observed by the Adapter given to it.  Essentially, there are three parts:

*

*The dataset that contains the data you want to display.

*The Adapter which provides an interface from that data to:

*The view itself, which is responsible for displaying the data.

What you need to define is a mapping from some sort of collection to the Adapter so that the adapter knows how to access the data it needs to give to the ListView.  There are examples of this in the Android SDK and there's even a ListView Tutorial.
Beyond that, there are two approaches to presenting your data in the ListView.  You can compute the string "DateX | Num1 | Num2 | CalculatedNumX" and simply have each list element be that string (simplest).  Or, you can create a custom view with 4 (or 7) text boxes and populate each one individually with the appropriate data.  This is more complex but has the advantage of providing more flexibility as to how you format and position your text.

A: There are many ways to do this, some better than others in certain situations.
Understand the classes you will be using
As posted in another answer you will need:

*

*A ListView of some flavour to display your data

*An adapter of some sort (BaseAdapter will do fine) to handle displaying your data

*A variable to store your data (I would recommend an ArrayList)

*A custom Layout to display each set of data in a row of your ListView
Turning this into something working
Firstly,its easiest just to make your components then link them last. So first up, your layout for each row of your ListView:
// Very basic layout for a row
public class rowView extends LinearLayout {
    TextView tv1 = null;
    TextView tv2 = null;
    TextView tv3 = null;
    TextView tv4 = null;

    public rowView(Context ct) {
        super(ct);

        // Do some Layout settings as needed
        setOrientation(LinearLayout.HORIZONTAL);

        // Create and configure TextViews
        tv1 = new TextView(ct);
        tv2 = new TextView(ct);
        tv3 = new TextView(ct);
        tv4 = new TextView(ct);

        tv1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f));
        tv2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f));
        tv3.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f));
        tv4.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f));

    // Add the views to the layout
        addView(tv1);
        addView(tv2);
        addView(tv3);
        addView(tv4);
    }
}

Next up is your data display, the way you link it to your EditText's etc will vary. But here is some idea's on how you could use an ArrayList<String[]>.
Say when you calculate your third number, you call a function like below:
public void addData(String date, String num1, String num2, String calculatedNum) {
    String[] s = new String[4];

    s[0] = date;
    s[1] = num1;
    s[2] = num2;
    s[3] = calculatedNum;

    arrayListofStrings.add(s);
}

Now your data is stored. Last major step is simply creating your adapter which you have to to set up to correctly 'get your ListView to correctly talk with your data'. Seeing as your new data is added to the end of your ArrayList (which is a lot easier than trying to add it to the start), all you have to do is flip the order in your adapter like so:
public class myAdapter extends BaseAdapter {

    public int getCount() {
        return arrayListofStrings.size();
    }

    public Object getItem(int position) {
        // Returns the strings in REVERSE order
        return arrayListofStrings.get(arrayListofStrings.size() - 1 - position);
    }

    public long getItemId(int position) {
        // Not concerned with this
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // Here is the version for memory optimization (aka view recycling). This should be habit

        rowView ret = null;

        if (convertView == null) {
            // Create a new view
            ret = new rowView(getApplicationContext());
        } else {
            // Cast and reuse
            ret = (rowView) convertView;
        }

        // Get the data
        String[] data = (String[]) getItem(position);

        // Update the row with the data
        ret.tv1.setText(data[0]);
        ret.tv2.setText(data[1]);
        ret.tv3.setText(data[2]);
        ret.tv4.setText(data[3]);

        return ret;
    }
}

The last steps are just creating your ListView where you need it, creating and attaching your Adapter to your ListView and other minor things (like casting your values to Strings etc).
This is by no means a working solution, just the guts of what sort of thinking goes into it and what you will need to do.
Note: Whenever you change the data ensure you call BaseAdapter.notifyDataSetChanged

A: Here are what you need:

*

*A class contains those data: Date1, Num1, Num2, CalculatedNum

*A custom adapter which extends from BaseAdapter

*A layout for for an item within ListView

*Main layout, which contain the ListView

*Finally, the main activity which consists of two TextView, two EditText and one Button.

This is the most basic skeleton to set up a ListView, of-course you can implement all the view in code but try to follow this pattern. It will make your code cleaner and easier to adapt changes in layout.
#1
package com.example.demo;

public class Data {
    private int mX;
    private int mY;
    private int mSum;
    private String mDate;

    public Data(int x, int y, int sum, String date) {
        mX = x;
        mY = y;
        mSum = sum;
        mDate = date;
    }

    public int getX() {
        return mX;
    }

    public int getY() {
        return mX;
    }

    public int getSum() {
        return mSum;
    }

    public String getDate() {
        return mDate;
    }
}

#2
package com.example.demo;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class DemoAdapter extends BaseAdapter {
    private Context mContext;
    private List<Data> mItems;
    private ViewHolder mHolder;

    private static LayoutInflater mInflater = null;

    public DemoAdapter(Context context, List<Data> items) {
        mContext = context;
        mItems = items;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return mItems.size();
    }

    public Object getItem(int position) {
        return mItems.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public static class ViewHolder {
        TextView x;
        TextView y;
        TextView sum;
        TextView date;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
            mHolder = new ViewHolder();
            mHolder.x = (TextView) convertView.findViewById(R.id.text_x);
            mHolder.y = (TextView) convertView.findViewById(R.id.text_y);
            mHolder.sum = (TextView) convertView.findViewById(R.id.text_sum);
            mHolder.date = (TextView) convertView.findViewById(R.id.text_date);
            convertView.setTag(mHolder);
        }
        else {
            mHolder = (ViewHolder) convertView.getTag();
        }

        mHolder.x.setText(Integer.toString(mItems.get(position).getX()));
        mHolder.y.setText(Integer.toString(mItems.get(position).getY()));
        mHolder.sum.setText(Integer.toString(mItems.get(position).getSum()));
        mHolder.date.setText(mItems.get(position).getDate());
        return convertView;
    }
}

#3
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/text_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:text="date">
    </TextView>

    <TextView
        android:id="@+id/text_x"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:text="x">
    </TextView>

    <TextView
        android:id="@+id/text_y"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:text="y">
    </TextView>

    <TextView
        android:id="@+id/text_sum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.3"
        android:text="sum">
    </TextView>

</LinearLayout>

#4
<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" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Num 1" />

        <EditText
            android:id="@+id/edit_x"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="23dp"
            android:ems="10"
            android:inputType="number" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Num 2" />

        <EditText
            android:id="@+id/edit_y"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="22dp"
            android:ems="10"
            android:inputType="number" >

            <requestFocus />
        </EditText>
    </LinearLayout>

    <Button
        android:id="@+id/button_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add"/>

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

</LinearLayout>

#5
package com.example.demo;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {
    private List<Data> mData;
    private ListView mListView;
    private DemoAdapter mAdapter;

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

        Button add = (Button) findViewById(R.id.button_add);
        add.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                EditText editX = (EditText) findViewById(R.id.edit_x);
                EditText editY = (EditText) findViewById(R.id.edit_y);

                int x = Integer.parseInt(editX.getText().toString());
                int y = Integer.parseInt(editY.getText().toString());

                mData.add(new Data(x, y, x + y, "02/33/2033"));
                // add new data to list and refresh
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private void prepareDummyData() {
        mData = new ArrayList<Data>();
        mData.add(new Data(1, 2, 3, "07/22/2012"));
        mData.add(new Data(2, 3, 5, "07/23/2012"));
    }

    private void setupListView() {
        // add some data
        prepareDummyData();
        mListView = (ListView) findViewById(R.id.listview);
        mAdapter = new DemoAdapter(this, mData);
        mListView.setAdapter(mAdapter);
    }
}

A: Just inflate a custom view on Override of  the getView method on the adapter being used by the ListView (instead of android_simple_listview_item). On your case supply layout_weight and weigh_sum attributes on the XML layout resource to control the apperance of your view. Just use the Date and Calendar java classes for the calculation of the dates.

A: Write your own Custom Adapter. You will create your own layout, in which you can set any kind of an item which is created based on your own custom layout. Check out the following link.It will definitely help you.
You can add your calculation once you are done with the basic ListView Adapters. For adding a layout at the top, One way of doing is to use a function called adapt.insert(object, index) where you basically provide an index of where to add an item. As an example, the link given above have a method called getOrders().


text:
Q: JSplitPane is painting over JMenu when I create JSplitPane and JMenu:
JSplitPane pane = new JSplitPane();
pane.setLeftComponent(new SidePanel()); // extends JPanel
pane.setRightComponent(new LibraryPanel()); // extends JPanel

add(pane);

JMenuBar menuBar = new JMenuBar();
// Creating menuBar
setJMenuBar(menuBar);

After resizing JSplitPane, JMenu's in JMenuBar component are drawing under JPanel elements. How to fix?

A: Solved. There was my typo :) And instead correct "JLabel" there was "Label". Sorry.
Check your code :) Cause, I already wrote my own Split Panel :)
Thanks for help!


text:
Q: How do I save QRcode as image in C I am using libqrenode for generating QRcodes in C. I would like then save generated QRcode as bitmap. How to do that? Can anyone give me a piecie of code?

A: The QRencode library cannot export as a bitmap directly. what you need to do is the following
QRcode my_qr;  //this is the code you want to print

for (int h=0; h<my_qr.height; h++)
  for (int w=0; w<my_qr.width; w++) {
    if (my_qr.data[h*my_qr.width+w]%2 == 1) printf("#"); // black pixel
    else printf(" "); // white pixel
  }
  printf("\n");

Of course this will result in simple text, not in a bitmap, but this text could easily be imported as XPM image or you can extend the above code slightly, by prepending the correct header for a bitmap.
The library itself contains a test/example for writing the QRCode in a PNG file. You can view it here: https://github.com/fukuchi/libqrencode/blob/1b565c7b599029818fc596e7da4371a3083da36c/tests/create_frame_pattern.c It uses the approach I explained above.


text:
Q: C# deserialization fails in Automation Addin but not in NUnit tests I have an automation addin (implementing Extensibility.IDTExtensibility2), written in C# 4, in which I'm trying to load some (binary) serialized data.  It works perfectly in unit tests, but fails when running from within Excel:
Unable to find assembly 'XXX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
   at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
   at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
   at

On the BinaryFormatter I'm setting the AssemblyFormat (for both serialization and deserialization) as follows:
serializationCodec.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;

Which I thought would ignore the version as per here.
Then thought it may be due to Excel's notion of "Trusted Location" so I added the project's directory and checked all subdirectories, but the error remained.
In vain I tried adding the System.Runtime.Serialization.OptionalFieldAttribute attribute, but it didn't help.
The unit tests can load the serialized files generated by itself or the same code executed in Excel, but Excel cannot load the serialized data regardless of whether it did the actual serialization.
The fact that Excel cannot deserialize what it has serialized itself hints that this is a redherring as it would obviously have access to the assembly used.
So the question is why does Excel deserialize differently compared to my unit test?  (Or perhaps more importantly; How can I get deserialization working in Excel?)
thanks.

A: I chased the red herring(s) and got no where with the assumption that it was a versioning issue (I'd looked at shims and all sorts).
It was in fact due to weird assembly binding;  although the automation addin's DLL could see and load classes from the DLLs it depended on, when it can to deserialization it failed to find the necessary assemblies - even though the deserialization call was from a class belonging to a DLL that it claimed it couldn't find!
Solution is certainly a hack but it's got me past this, so in case anyone else is stuck as i was, here's the hack(s):
Inside a class X, that depends on classes Y and Z each from their respective project DLLs (named ProjectForX, ProjectForY and ProjectForZ)
private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
    {
        if(args.Name.StartsWith("ProjectForX,")) {
            return typeof(X).Assembly;
        } else if(args.Name.StartsWith("ProjectForY,")) {
            return typeof(Y).Assembly;
        } else if(args.Name.StartsWith("ProjectForZ,")) {
            return typeof(Z).Assembly;
        }
        return null;
    }

    public static X LoadX(string filename)
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        ResolveEventHandler handler = new ResolveEventHandler(MyResolveEventHandler);
        currentDomain.AssemblyResolve += handler;
        try {
            Stream stream = new FileStream(@filename, FileMode.Open);
            try {
                BinaryFormatter deserializer = createBinaryFormatter();
                X model = (X)deserializer.Deserialize(stream);
                return model;
            } finally {
                stream.Close();
            }
        } finally {
            currentDomain.AssemblyResolve -= handler;
        }
    }

Basically it just hooks into the resolve events and provides the correct assembly based on the requested type name - this isn't particularly safe (I'm using the comma in the assembly descriptor to try to minimize any clashes).
There's almost certainly a clear way to do this, and the issue is probably just a result of poor configuration and my limited experience with MS products and C# in particular.
This wouldn't have been an issue if I'd just built a monolithic DLL =)


text:
Q: Remove a carriage return with sed I have a large CSV file. One of the fields contains an error. This error appears as a new line in the file.
Since now i've been using notepad++ with this command to correct the problem :

\r";"   =>   ";"

How can I do the same with sed ?
I've already tried
sed -i 's/\r";"/";"/g' /path/file.csv
sed -i 's/^";"/";"/g' /path/file.csv

no success, someone here know probably the right command

A: It is important to understand that sed works on a line by line basis. What sed does is basically : read a line into its buffer without the newline, execute your commands on the buffer, print the buffer (provided you haven't specified the -n flag), read the next line into its buffer, etc. So to merge two lines with sed requires that you explicitly force sed to treat more than a single line at a time. To do that, the N, P and D commands are your friend.
Now for your specific problem, to give you a specific and tested answer would require you to put a specific type of input, but here are some examples of what can be done :
This will merge every two lines together :
sed $'N;s/[\\n\r]//g'

or if you are sure to always have \r\n line endings :
sed 'N;s/.\n//'

For a more tailored approach to what I understood of your question, although not the best solution, this should do the work provided you use bash or another shell that supports C escape via the $'str' construct :
sed $':l;N;/\r\\n";"/{;s/\r\\n";"/";"/g;n;};bl'

or without the C-style escape construct and with \r\n line endings (non-negotiable) :
sed ':l;N;/\n";"/{;s/.\n";"/";"/g;n;};bl'

What it does is basically append the next line to its buffer (N) and test for the string you want (/\r\\n";"/). The script loops (bl --> branch to label :l defined at the beginning) as long as it doesn't find a match. When a match is found, it executes the sed script between the curly braces : replace all occurrences of \r\\n";" by ";" (s/\r\\n";"/";"/g) and flush the buffer and input the next line (n).
Of course, if the file is big and the "errors" are infrequent, this could run for a long time and take a lot of memory. If this is the case, another algorithm could be used, but I would need to have a better example of what you are up against to be sure that I understood your problem correctly.
Also, if you would like to learn a little more about sed, I strongly recommend this site which might not have the best background color, but is the best tutorial of sed out there IMO.

A: If you can live with a perl solution:
perl -pe 's/\r";"/";"/g' foo.csv >foo_r.csv

A: If you want to drop the \r characters, it's simpler with the tr command filter:
cat file.csv | tr -d '\r' >newfile.csv

or directly:
tr -d '\r' <file.csv >newfile.csv

man tr is yout friend. Caveat: tr is meant to be used as a filter reading from its standard input and it cannot process a file in-place like sed -i.

A: I had a similar problem to solve, but I ended up using a slightly different version of  @Fjor 's answer
cat file.csv | tr -d '\n'
(Tr is TRanslate, which is usually a search/replace command, but with -d it will simply delete all occurrences of the single-quoted search string)
Would've offered it as a comment to Fjor's answer if i had the rep to. Oh well, here it is anyways.