text:
Q: Tikz angles library: draw arc while setting anchor I am using the Tikz library angles to draw an arc between two edges. My goal is to create this:

However, I don't know how to set the anchors for the \pic command. I set it for the edges, but (logically), this doesn't give the desired result:
\begin{tikzpicture}
\node[draw,circle] (n3) at (0,0) {3};
\node[draw,circle] (n4) at (1,0.5) {4};
\node[draw,circle] (n5) at (1,-0.5) {5};
\draw[->] (n3) to (n4);
\draw[->] (n3) to (n5);

\pic[draw]{angle=n5--n3--n4};
\end{tikzpicture}

How can i set the anchors in the \pic command? The following didn't work:
\pic[draw]{angle=n5--n3.east--n4};

A:
\documentclass{standalone}
\usepackage{tikz}

\usetikzlibrary{calc,positioning,angles,arrows.meta,quotes,intersections}
\usetikzlibrary{through}

\begin{document}
    \begin{tikzpicture}
    \node[draw,circle] (n3) at (0,0) {3};
    \node[draw,circle] (n4) at (1,0.5) {4};
    \node[draw,circle] (n5) at (1,-0.5) {5};
    \draw[->] (n3.east) to (n4);
    \draw[->] (n3.east) to (n5);
%   \pic[draw]{angle=n5--n3--n4};
\draw[thick,red] ([shift=(-15:0.5cm)]0,0) arc (-15:15:0.5cm);
\end{tikzpicture}
\end{document}

A: Perhaps the example under the link will help you (Draw angle between two line). So you can define a certain radius for the angle.

A: I have solved it. The solution is to create an additional coordinate east of the node, and draw things from there:
\begin{tikzpicture}
\node[draw,circle] (n3) at (0,0) {3};
\coordinate[right=0mm of n3]  (n3e);
\node[draw,circle] (n4) at (1,0.5) {4};
\node[draw,circle] (n5) at (1,-0.5) {5};
\draw[->] (n3e) to (n4);
\draw[->] (n3e) to (n5);

\pic[draw,angle radius=2mm]{angle=n5--n3e--n4};
\end{tikzpicture}

Resulting in:


text:
Q: sign in form is working fine on localhost but not on host this sign in process is working fine in my localhost but when i upload it on host and try to test it on live server it fails!
i uploaded my database to server and tried to sign in with a registered user, but when i submitted the form nothing happened!
i use ajax and alert the data returned from server and it just alerted a blank message, no error, no warning, no data echoed!
<?php

$username = $_POST['username'];
$password = $_POST['password'];
$id;
$status = 1;

require_once("../scripts/config.php");

$stmt = $con->stmt_init();
if ($stmt = $con->prepare("SELECT COUNT(email) AS counte FROM users WHERE email=?"))
{
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $obj = $stmt->get_result()->fetch_object();
    $counte = $obj->counte;
    $stmt->close();
}

if($counte == 1) // email mojud ast
{
    if ($stmt = $con->prepare("SELECT COUNT(*) AS countr, id, fname, lname, img FROM users LEFT JOIN userd ON users.id = userd.userid WHERE email=? AND password=?"))
{
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $obj = $stmt->get_result()->fetch_object();
    $countr = $obj->countr;
    $id = $obj->id;
    $fname = $obj->fname;
    $lname = $obj->lname;
    $img = $obj->img;
    $stmt->close();
    if($countr == 0)
    {
        echo "incorrect";
    }
    else if($countr == 1)
    {
        session_start();
        $_SESSION['userid'] = $id;
        echo $img."*".$fname." ".$lname."*".$id."*";
    }
}
}
else if($counte == 0)
{
echo "notexist";
}
mysqli_close($con);
?>

A: instead of
if($counte == 1) // email mojud ast
{
   }

try this
if($counte > 0)
{
   }

this is what I use on my login module
if ever you want to consider using PDO here is my code feel free to use it as reference
$con = new PDO("mysql:host=". DB_host .";dbname=db", DB_username , DB_password);

      $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

      //checking if  valid
      $sql="SELECT * FROM users WHERE username=:var1 AND password=:var2 ";
      $stmt=$con2->prepare($sql);
      $stmt->bindParam(':var1',$var1, PDO::PARAM_STR);
      $stmt->bindParam(':var2',$var2, PDO::PARAM_STR);
      $stmt->execute();

       if($stmt->rowCount() > 0 ){

      }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I convert a string with single quotes into double for json parse I have an array that is being encoded in php using json_encode
 $params = array(1=>'something','2'=>'two');

When I encode it using json encode it will encode it with double quotes which in itself is fine but I'm trying to embed this in an anchor tag and the double quotes are messing up the attributes.
       test ajax link
obviously the second double quote in the data-params attribute is breaking the link.
So what I did was convert the string into single quotes but I need to re-convert it to double quotes to be able to parse in javascript;
 var string = {'one':'something','2':'two'} ;

JSON.parse will fail on that string, i tried
 var jsonString = dataParams.replace('\'', '"');

but that seems to only convert the first single quote then stops. Any ideas?

A: A better approach would be to use the htmlentities() function to encode the " as ", meaning you can insert it as data-*. When you retrieve it using JavaScript, they'll show up as ", meaning you can JSON.parse it immediately;
<a data-foo="<?php echo htmlentities(json_encode(array('demo' => 'test'))); ?>">Hey

A: Use this instead:
var jsonString = dataParams.replace(/'/g, '"');


text:
Q: Conexão mysql dentro de uma classe Olá, estou com bastante dificuldades em realização uma conexão com o banco dados. Para realizar a conexão eu criei uma classe chamada Conexao e estou usando PDO, quando preciso fazer um select, por exemplo, faço a chamada da classe de conexão dentro da classe Credenciais que possui o método PegaCredenciais, onde será feito o select.
Quando realizo a instancia da classe Credenciais dentro do arquivo Classes/Credenciais.php, onde ela está, funciona perfeitamente. Más quando a instancia é feita no arquivo index.php, eu recebo erro 500 ao carregar a página e só resolve o erro quando retiro a classe Conexao de dentro do método PegaCredenciais.
Já fiz testes e a classe de seleção é visível no arquivo index.php, estou usando o Composer.
index.php
require __DIR__.'/vendor/autoload.php';
use \Classes\Credenciais;

$credenciais = new Credenciais();
$credenciais->PegaCredenciais();

Classes/Credenciais.php
namespace Classes;

class Conexao{
     private static function connect(){
        return new PDO("mysql:host=localhost;dbname=meu_banco", "meu_banco", "root");
     }
}

class Credenciais{
    public function PegaCredenciais(){
        $db = Conexao::connect();
        $dados = $db->query("SELECT * FROM credenciais WHERE id = '1'");
        $dados = $dados->fetch(PDO::FETCH_OBJ);
        return $dados->token;
    }
}

composer.json
"autoload":{
    "psr-4":{
         "Classes\\":"Classes/"
    }
}

A: Consegui resolver o problema. A classe PDO não estava sendo localizada, para usa namespace preciso inserir uma barra ao contrario antes de definir PDO.
Ex:
$dados->fetch(\PDO::FETCH_OBJ);


text:
Q: fully stretch text horizontally on page Is there a way to fully stretch one line of text on the full width of the page, without manually setting the letter spacing, no matter how many characters on the line?

A: if you want to stretch all the letters evenly rather than words you can use:
\makeatletter
\def\spreadeven#1{%
\@tfor\next:=#1\do{%
  \next\hfill
 }%
}

\spreadeven{A fox jumped over the lazy dog}
\madeatother

This uses the LaTeX kernel @tfor to iterate over all the letters and add hfill between them.

A: In ConTeXt there is the \stretched macro for this purpose. Example:
\starttext
    \stretched{Here is some text}
\stoptext

A: I assume you are referring to the spacing between words (or inter-word spacing) when you reference "a line text".
If the number of characters will always fit on the line, then the optional s-parameter for \makebox alignment inserts enough inter-word spacing stretch to fill the box. If the text is greater than the box width, an overfull \hbox warning is generated:

\documentclass{article}
\setlength{\parindent}{0pt}% Just for this example.
\begin{document}
\makebox[\linewidth][s]{Here is some text.} \par
\makebox[\linewidth][s]{Here is some more text.} \par
\makebox[\linewidth][s]{Here is a whole whack of text, plus some punctuation.} \par
\makebox[\linewidth][s]{Here is a whole whack of text, plus some punctuation, and then some more text.} \par
\makebox[\linewidth][s]{Here is a whole whack of text, plus some punctuation, and then some more text, and nothing else.} \par
\end{document}

The last line stretches beyond the text margin. In the above minimal working example (MWE), replacing \linewidth with \textwidth would also work.

For inter-letter spacing, the soul package can be of help. You define your own inter-letter, inner and outer spaces via a command \sodef{<cmd>}{<font>}{<inter-letter>}{<inner space>}{<outer space>}:

\documentclass{article}
\usepackage{soul}% http://ctan.org/pkg/soul
\setlength{\parindent}{0pt}% Just for this example.
\begin{document}
\sodef\spaceout{}{0pt plus 1fil}{.4em plus 1fil}{0pt}
\makebox[\linewidth][l]{\spaceout{Here is some text.}} \par
\makebox[\linewidth][l]{\spaceout{Here is some more text.}} \par
\makebox[\linewidth][l]{\spaceout{Here is a whole whack of text, plus some punctuation.}} \par
\makebox[\linewidth][l]{\spaceout{Here is a whole whack of text, plus some punctuation, and then some more text.}} \par
\makebox[\linewidth][l]{\spaceout{Here is a whole whack of text, plus some punctuation, and then some more text, and nothing else.}} \par
\end{document}

Since I am unfamiliar with this kind of modification, consider this just a guide to get you going. The soul package documentation (section 3 Letter spacing, p 8 onward) is filled with examples.
I'm sure microtype would also be able to facilitate your needs.

A: spread as a command to a box instruction is built into tex (texbook, p.77):
\documentclass{article}
\begin{document}
\hbox spread \linewidth{Here is some text.}
\end{document}

A: Using the soul package

\documentclass{article}

\usepackage{soul}
\sodef\ugg{}{.4em plus 1fill}{1em plus 2 fill}{2em plus 2fill minus.1em}

\begin{document}

\noindent\ugg{one two three\\four five six}

\end{document}


text:
Q: Make opening of cmd window optional in a tkinter app? Is there a way I can make the opening of the cmd window optional in a python GUI app, like if option xyz is given, open an cmd window otherwise don't?
import sys
import tkinter
master = tkinter.Tk()
#tk gui stuff goes here
if sys.argv[1] == "console":
    #open cmd winow
master.mainloop()

I was planning to only open the cmd window if the user wants to see the debugging output etc.

A: This may not be a complete solution, but it works. And is dead simple:
If you run the python script using pythonw instead of the usual python, it will run without a cmd window in the background.
For example:
> pythonw my_app.py

And if you want the cmd window open,
> python my_app.py

You could also change the extension of the script from .py to .pyw to avoid opening the cmd window.

A: you need to save your python file as a .pyw file instead of a .py
Note that you might need to copy the text of your program into textedit or Notepad and save it as a .pyw from there.


text:
Q: Ultisnips transformations with regex seem to not work I am trying to remove whitespace at the beginning of a tabstop using transformations. I have found that the regex \S+ should return all characters that aren't whitespace.
snippet getset "Create a get/set pair" b
${1:type} get${2:name}(){ return ${2/.*/\l$0/}; }
void set$2(${1/(\S+)/$0/g} new$2){ ${2/.*/\l$0/} = new$2; }
endsnippet

The regex that makes trouble is in the third line. I always get back the entire unaltered tabstop, including the whitespace, no matter that the regex is. I've tried (a) and I still got the entire tabstop back:
    arma::vec3 getname(){ return name; }
    void setname(   arma::vec3 newname){ name = newname; }

Are there any obvious things I am missing, or did I stumble upon a bug?


text:
Q: ImageView in LinearLayout in Scrollview with CardStackView and Picasso Picture does not show I am developing an Android application.
I am using "com.yuyakaido.android:card-stack-view:2.3.4" for card stack library.
The ImageView is in LinearLayout in ScrollView in CardView.
What I want to do is to fit the image in the card's size as per the picture below when the card is loaded at first.

And if you scroll down, it will display some texts as per the picture below

I use Picasso to fit the image to ImageView but the image does not show.
This is the fragment which has the CardStackView
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return inflater.inflate(R.layout.fragment_card_stack, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    initCardStackView()
}

private fun initCardStackView() {
    manager = CardStackLayoutManager(context)
    manager.setCanScrollVertical(false)
    manager.setSwipeableMethod(SwipeableMethod.Manual)
    adapter = CardStackAdapter(context, createDummyProfiles())
    cardStackView.layoutManager = manager
    cardStackView.adapter = adapter
    cardStackView.itemAnimator = DefaultItemAnimator()
}

This is the Fragment layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.yuyakaido.android.cardstackview.CardStackView
        android:id="@+id/cardStackView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="80dp"
        android:clipToPadding="false"/>

</LinearLayout>

This is the CardStackAdapter, here I crop and fit the image to ImageView with Piccaso
class CardStackAdapter(private var context: Context?, private var movies: MutableList<Movies>) :
    RecyclerView.Adapter<CardStackAdapter.ViewHolder>() {

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return ViewHolder(inflater.inflate(R.layout.card_view, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        Picasso.get().load(R.drawable.person3).fit().centerCrop().into(holder.itemView.imageView)
    }

    override fun getItemCount(): Int {
        return movies.size
    }

    fun setItems(items: MutableList<Profile>) {
        this.movies = items
    }
}

This is the card_view which is the layout for viewHolder of CardStackAdapter
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/selectableItemBackground"
    android:foreground="?attr/selectableItemBackground"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="18dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/lipsum"/>

        </LinearLayout>

    </ScrollView>

</androidx.cardview.widget.CardView>

When I run the application, I get the card without the image but only texts as per the picture below

How can I display the image in the size of the card when the card is loaded?

------------------------- UPDATE ----------------------------
** NOTE: The image will be retrieved from the server not local drawable. I just used the images in local drawable for testing purpose.
I am not sure why the image does not show. But if I set the height and width of layoutParams of imageView as per code below, then the image shows up.
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.itemView.imageView.layoutParams.height = 1918
    holder.itemView.imageView.layoutParams.width = 970
    Picasso.get().load(R.drawable.person3).fit().centerCrop().into(holder.itemView.imageView)
}

So, now the question is whether I can set the height and width of ImageView equal to the height and width of ScrollView (imageView's parent's parent) or CardView (imageView's parent's parent's parent) NOT LinearLayout (parent) because LinearLayout's height should be "wrap_content".

------------------------- UPDATE ----------------------------
It seems like your solution is based on image's height and width, but I need to fit the image in the CardView or ScrollView
here is my onBindViewHolder code. I just removed Picasso.
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.itemView.imageView.setImageResource(R.drawable.person2)
}

Here is my CardView layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/selectableItemBackground"
    android:foreground="?attr/selectableItemBackground"
    app:cardCornerRadius="18dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true">

    <androidx.core.widget.NestedScrollView
        android:fillViewport="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView"
                android:src="@drawable/person2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/lipsum"/>

        </LinearLayout>

    </androidx.core.widget.NestedScrollView>

</androidx.cardview.widget.CardView>

This is what I have got on my AVD. The image does not fill the bottom of CardView because it scales based on its height and width?

A: What i understand from your updated question you need to to fill the ImageView upto CardView Height and the textView will be visible after scrolling. This Seems tricky  to with ScrollView because we somehow need to set height dynamically match_parent won't work with ScrollView.
I have made a Solution below see if this workout for you. Create a custom Image view and use inside CardView.
class FillImageView : AppCompatImageView {
constructor(context: Context?) : super(context!!) {}
constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context!!, attrs, defStyleAttr) {}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    val parentWidth = MeasureSpec.getSize(widthMeasureSpec)
    setMeasuredDimension(parentWidth, (parent.parent as View).measuredHeight)
}
}

And add the NestedScrolllView below inside CardView
<androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:fillViewport="true"
            android:layout_height="match_parent">
        <LinearLayout
                android:layout_width="match_parent"
                android:orientation="vertical"
                android:layout_height="wrap_content">
            <com.ace.myapplication.FillImageView
                    android:layout_width="match_parent"
                    android:src="@drawable/hello"
                    android:adjustViewBounds="true"
                    android:layout_height="match_parent"
                    android:scaleType="centerCrop"/>
            <TextView
                    android:layout_width="match_parent"
                    android:textSize="23sp"
                    android:padding="10dp"
                    android:layout_height="wrap_content"/>
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>

PS- It might be an ugly solution with setting height with (parent.parent as View).measuredHeight but this is all i can thing of right now . love to see some elegant solution for this. I haven't tested it with CardStackView.
Update
Now with RecyclerView the problem is item drawn after the adapter is set and we need to listen for the layoutManager callback of Item drawn since.
One way to tackle this without making it complex Set the cadStackView height to the imageView . See the code below adding only essential code.
class CardStackAdapter(val stackViewHeight:Int, private var movies: MutableList<Moview>) :
    RecyclerView.Adapter<CardStackAdapter.ViewHolder>() {

   inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView:ImageView = itemView.findViewById(R.id.imageView)
        init {
            imageView.layoutParams.height= stackViewHeight
        }
    }
}

Now in your fragment
cardStackView.post {
       initCardStackView()
   }

And change the dapter creation inside initCardStackView as follows. Also you do not have to pass Context to adapter each view has a context attached to it . Also do not use FillImageView in this case use normal ImageView in xml layout.
// Since you are using android:padding it will be same for all sides
    val cardHeight=cardStackView.height- (2*cardStackView.paddingTop)
    val adapter = CardStackAdapter(cardHeight, createDummyProfiles())

A: Why are you using Picasso to load a local drawable? You could just apply your source drawable to the ImageView.
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:scaleType="fitCenter"
    android:src="@drawable/person3"
    android:layout_height="wrap_content" />

Besides that, I strongly advice you to use NestedScrollView instead of ScrollView and then, please, set fillViewPort (ScrollView's attribute) as true to extend its height as equals as the child's height

Update:
If you want to really use Picasso to load an external URL, please do the following configuration:
Picasso
    .get()
    .load([url_you_want_to_load])
    .placeholder([placeholder_you_want_to_pre_load])
    .into(imageView)

and then, configure your ImageView to fit center and preserve its aspect ratio:
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop" />


text:
Q: Mordecai's Gun Crazy skill + burst fire, what happens? What happens when Mordecai's Gun Crazy skill is combined with a burst fire repeater?

Gun Crazy
When using Pistols you have 8% chance
to fire 2 shots with each pull of the
trigger instead of just 1.

A: When using any burst fire pistol, Mordecai's gun crazy has a chance to double the amount of rounds in the spread. This applies to both burst fire repeaters and mashers.


text:
Q: How to upload Metapackage Extensions in Magento Marketplace? How to Upload Metapackage extension in Magento Marketplace?
I have two dependent extensions. Can I upload the dependent extension as individual extension?
How to create shared package while uploading the Metapackage extension?
Thanks in advance.

A: You need to do into the following ways.

*

*Submit 2 dependent extension as Shared Package and First approve that one. For Submit the Shared package you find the options on top menu, see this one : https://i.imgur.com/73BIRPu.png

*Now you need to submit Main Extension where select those 2 extension as Shared Package. You can found option here : https://i.imgur.com/H9L7ai4.png


text:
Q: When I set the Owner property of a WPF child window, am I preventing it from getting garbage collected? If parent window A passes a reference to itself to child window B (via constructor) so that B can set its Owner property to A, does that mean child window B won't be garbage collected because parent window A stays alive for the duration of the application?
If this is the case, what is the best approach for creating clean parent/child relationships between WPF windows?  Is there a concept of weak references for this type of relationship?
UPDATE: Brain FAIL.  Okay, I shouldn't have asked this question so late in the afternoon.  I was over-complicating the problem.  My brain reversed the logic of the GC and was thinking the child couldn't collect because it referenced something else which is totally false.  Thanks to all who answered anyway.

A: Objects are eligible for garbage collection as soon as no references to them exist in the stack.  For this reason as long as you hold a reference to window B within window A then it will never be garbage collected.
In order to make it eligible for GC you'll have to explicitly set any reference to it to null or another object reference.

A: I created the Windows you mention, and added some code:
// XAML in Window A

<StackPanel>
    <Button Click="Button_Click">Show Window</Button>
    <Button Click="Button_Click_1">Garbage Collect</Button>
</StackPanel>

// Code in Window A
 private void Button_Click(object sender, RoutedEventArgs e)
        {
            WindowB windowB = new WindowB(this);
            windowB.Show();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            GC.Collect();
        }

    // Code in WindowB
    public WindowB(WindowA windowA)
    {
        this.Owner = windowA;
        InitializeComponent();
    }

    ~WindowB()
    {
        Console.WriteLine("Gone up in a puff of smoke");
    }

Once B had been closed and the second button pressed, the destructor ran. Hopefully this answers the question.

A:
If parent window A passes a reference to itself to child window B (via
  constructor) so that B can set its Owner property to A, does that mean
  child window B won't be garbage collected because parent window A
  stays alive for the duration of the application?

Correct, child window B lives until parent Window A lives, because there is a live reference from Parent window to WindowB.

If this is the case, what is the best approach for creating clean
  parent/child relationships between WPF windows? Is there a concept of
  weak references for this type of relationship?

Clear the Parent window reference to Window B when the WindowB close. In this way, there is no live reference to WindowB and it's eligible to garbage collected.
parentWindow.WindowB = null;

One more thing, it's a good practice to call the Dispose method for all the Disposable objects before they go out of scope. You can use using statement for local/disposable objects.


text:
Q: How to update a WPF DataGrid per keystroke I'm making a simple file renaming program with a WPF UI. I take in a directory, read text into a grid, then apply changes. One of the parameters, however, which is the length of the file path, I would like to have updated on the fly as a user is typing in changes to their filename. Disclaimer: I'm very new to WPF and relatively new to C# (just trying to get back into programming, annoyingly, implementing WPF is more complicated than the C#, but I can't use WinForms for this one). I'm sure this is an INotifyPropertyChanged thing, though, from what I've seen online so far, there are quite a few ways to implement it-- so here I am. Thank you to all.
XAML
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Files;assembly=FileCollection"
        mc:Ignorable="d"
        WindowStyle="SingleBorderWindow" WindowStartupLocation="CenterScreen"
        Title="SLU Renamer" FontFamily="Segoe UI" Height="500" Width="1000" MinHeight="250" MinWidth="250" ResizeMode="CanResize">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Border BorderBrush="LightBlue" BorderThickness="1">
            <StackPanel Grid.Row="0">
                <Grid Height="25">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Button Grid.Column="0" x:Name="BtnBrowse" Content="Browse" Click="BtnBrowse_Click" Background="AliceBlue" FontFamily="Segoe UI" FontSize="13" BorderBrush="LightBlue" BorderThickness="0"/>
                    <Button Grid.Column="3" x:Name="BtnApply" Content="Apply" Click="BtnApply_Click" Background="AliceBlue" FontFamily="Segoe UI" FontSize="13" BorderBrush="LightBlue" BorderThickness="0"/>
                </Grid>
            </StackPanel>

        </Border>
        <DockPanel Grid.Row="2">
            <Grid x:Name="DataGridHolderGrid">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="727*"/>
                    <ColumnDefinition Width="33*"/>
                </Grid.ColumnDefinitions>
                <DataGrid Grid.Column="0" x:Name="DataGridFileNames" AutoGenerateColumns="False" ItemsSource="{Binding}" FontSize="13" FontFamily="Segoe UI Semibold" Background="White"
                          CanUserReorderColumns="True" CanUserSortColumns="True" CanUserResizeRows="False" CanUserResizeColumns="True" AlternatingRowBackground="LightBlue"
                          VerticalGridLinesBrush="DeepSkyBlue" HorizontalGridLinesBrush="DeepSkyBlue" BorderBrush="DeepSkyBlue" BorderThickness="0"
                          ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" Grid.ColumnSpan="2"
                          SourceUpdated="DataGridFileNames_SourceUpdated">
                    <DataGrid.Columns>
                        <DataGridTextColumn x:Name="OriginalFileNamesColumn" Header="Original Name" Width=".5*"
                                            IsReadOnly="True" Binding="{Binding OriginalFileName}" />
                        <DataGridTextColumn x:Name="NewFileNamesColumn" Header="New Name" Width=".5*"
                                            IsReadOnly="False" Binding="{Binding NewFileName, Mode=TwoWay}" />
                        <DataGridTextColumn x:Name="FileExensionColumn" Header="Ext." Width=".125*"
                                            IsReadOnly="True" Binding="{Binding FileExtension}" />
                        <DataGridTextColumn x:Name="FinalFileNamesColumn" Header="File Path" Width=".75*"
                                            IsReadOnly="True" Binding="{Binding NewPath}" />
                        <DataGridTextColumn x:Name="PathLengthColumn" Header="Length" Width=".125*"
                                            IsReadOnly="True" Binding="{Binding PathLen, UpdateSourceTrigger=PropertyChanged}" />
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </DockPanel>
    </Grid>
</Window>

XAML.cs (Code Behind??)
using System;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using IronXL;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.IO;

namespace RenamerApp_3._0
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
        Microsoft.Win32.OpenFileDialog openExcelWkbkDialog = new Microsoft.Win32.OpenFileDialog();
        FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
        //Dictionary<string, string> browseOptions = new Dictionary<string, string>();

        public ObservableCollection<FileName> observableFileNames = new ObservableCollection<FileName>();

        public MainWindow()
        {
            InitializeComponent();
            InitDataGrid();
            InitializeOpenFileDialog();
            //DataGridFileNames.HeadersVisibility = ;
            //InitializeComboBox();
        }

        private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            //OpenFileDialog();
            OpenFolderDialog();
            DataGridFileNames.Visibility = Visibility.Visible;
        }
        private void BtnApply_Click(object sender, RoutedEventArgs e)
        {
            foreach (var file in observableFileNames)
            {
                File.Move(file.OriginalPath + @"\" + file.OriginalFileName + file.FileExtension, file.NewPath + @"\" + file.NewFileName + file.FileExtension);
                FileNameInit(file);
                UpdateLen(file);
                DataGridFileNames.Items.Refresh();
            }
        }

        private void InitializeOpenFileDialog()
        {
            this.openFileDialog.Multiselect = true;
        }
        private void OpenFileDialog()
        {
            Nullable<bool> result = openFileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                foreach (string filename in openFileDialog.FileNames)
                {
                    FileName fileName = new FileName(filename);
                    observableFileNames.Add(fileName);
                }
                DataGridFileNames.DataContext = observableFileNames;
            }
        }
        private void OpenFolderDialog()
        {
            DialogResult result = folderBrowserDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string path = folderBrowserDialog.SelectedPath;
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                FileInfo[] files = directoryInfo.GetFiles();
                foreach (FileInfo file in files)
                {
                    FileName fileName = new FileName(file);
                    observableFileNames.Add(fileName);
                }
                DataGridFileNames.DataContext = observableFileNames;
            }
        }

        private void FileNameInit(FileName file)
        {
            file.OriginalFileName = file.NewFileName;
            file.OriginalPath = file.NewPath;
        }
        private void InitDataGrid()
        {
            DataGridFileNames.Visibility = Visibility.Hidden;
        }

        private void DataGridFileNames_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            UpdateLen(observableFileNames);
            DataGridFileNames.Items.Refresh();
        }

        public void UpdateLen(ObservableCollection<FileName> observableFileNames)
        {
            int currentRowIndex = DataGridFileNames.Items.IndexOf(DataGridFileNames.CurrentItem);
            FileName file = observableFileNames[currentRowIndex - 1];
            file.PathLen = file.NewPath.Length + +@"\".Length + file.NewFileName.Length + file.FileExtension.Length;
        }

        public void UpdateLen(FileName file)
        {
            file.PathLen = file.NewPath.Length + +@"\".Length + file.NewFileName.Length + file.FileExtension.Length;
        }

Data
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using IronXL;

namespace Files
{
    public class FileName : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public FileInfo OriginalFile { get; set; }
        public string FileExtension { get; set; }
        public int PathLen { get; set; }

        public string OriginalFileName { get; set; }
        public string NewFileName { get; set; }

        public string OriginalPath { get; set; }
        public string NewPath { get; set; }

        public FileName()
        {

        }

        public FileName(string filename)
        {
            OriginalFile = new FileInfo(filename);
            OriginalPath = NewPath = Path.GetDirectoryName(filename);
            OriginalFileName = NewFileName = Path.GetFileNameWithoutExtension(filename);
            FileExtension = Path.GetExtension(filename);
            PathLen = filename.Length;
        }

        public FileName(FileInfo file)
        {
            OriginalFile = file;
            OriginalPath = NewPath = OriginalFile.DirectoryName;
            OriginalFileName = NewFileName = Path.GetFileNameWithoutExtension(OriginalFile.Name);
            FileExtension = Path.GetExtension(OriginalFile.Name);
            string path = OriginalFile.ToString();
            PathLen = path.Length;
        }

        public string index { get; set; }
        public FileName(WorkBook workbook, string index)
        {
            WorkSheet sheet = workbook.WorkSheets.First();

            foreach (var cell in sheet[index])
            {
                string path = cell.ToString();
                OriginalFile = new FileInfo(path);
                OriginalPath = NewPath = OriginalFile.DirectoryName;
                OriginalFileName = NewFileName = path;
                PathLen = path.Length;
            }
        }

        //String pathHolder;
        //private void FileName_PropertyChanged(object sender, PropertyChangedEventArgs e)
        //{
        //    pathHolder = NewPath + NewFileName + FileExtension;
        //    PathLen = pathHolder.Length;
        //}

    }
}

Updated Data Class
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using IronXL;

namespace Files
{
    public class FileName : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public FileInfo OriginalFile { get; set; }
        public string FileExtension { get; set; }

        public string OriginalFileName { get; set; }
        public string NewFileName { get; set; }

        public string OriginalPath { get; set; }
        private string _newPath;
        public string NewPath
        {
            get { return _newPath; }
            set
            {
                _newPath = NewPath;
                PathLen = NewPath.Length + @"\".Length + NewFileName.Length + FileExtension.Length;
                OnPropertyChanged();
            }
        }
        private int _pathLen;
        public int PathLen
        {
            get { return _pathLen; }
            set
            {
                _pathLen = value;
                OnPropertyChanged();
            }
        }
        //public int PathLen { get; set; }

        public FileName()
        {

        }

        public FileName(string filename)
        {
            OriginalFile = new FileInfo(filename);
            OriginalPath = NewPath = Path.GetDirectoryName(filename);
            OriginalFileName = NewFileName = Path.GetFileNameWithoutExtension(filename);
            FileExtension = Path.GetExtension(filename);
            PathLen = filename.Length;
        }

        public FileName(FileInfo file)
        {
            OriginalFile = file;
            OriginalPath = NewPath = OriginalFile.DirectoryName;
            OriginalFileName = NewFileName = Path.GetFileNameWithoutExtension(OriginalFile.Name);
            FileExtension = Path.GetExtension(OriginalFile.Name);
            string path = OriginalFile.ToString();
            PathLen = path.Length;
        }

        public string index { get; set; }
        public FileName(WorkBook workbook, string index)
        {
            WorkSheet sheet = workbook.WorkSheets.First();

            foreach (var cell in sheet[index])
            {
                string path = cell.ToString();
                OriginalFile = new FileInfo(path);
                OriginalPath = NewPath = OriginalFile.DirectoryName;
                OriginalFileName = NewFileName = path;
                PathLen = path.Length;
            }
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

A: When you want to use an INotifyPropertyChanged, you have to do something like this:
public class FileName : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public FileInfo OriginalFile { get; set; }
    public string FileExtension { get; set; }

    private int _pathLen;

    public int PathLen
    {
       get { return _pathLen; }
       set
       {
          _pathLen = value;
          OnPropertyChanged();
       }
    }

    public string OriginalFileName { get; set; }
    public string NewFileName { get; set; }

    public string OriginalPath { get; set; }
    public string NewPath { get; set; }

    public FileName()
    {

    }

    public FileName(string filename)
    {
        OriginalFile = new FileInfo(filename);
        OriginalPath = NewPath = Path.GetDirectoryName(filename);
        OriginalFileName = NewFileName = Path.GetFileNameWithoutExtension(filename);
        FileExtension = Path.GetExtension(filename);
        PathLen = filename.Length;
    }

    public FileName(FileInfo file)
    {
        OriginalFile = file;
        OriginalPath = NewPath = OriginalFile.DirectoryName;
        OriginalFileName = NewFileName =
           Path.GetFileNameWithoutExtension(OriginalFile.Name);
        FileExtension = Path.GetExtension(OriginalFile.Name);
        string path = OriginalFile.ToString();
        PathLen = path.Length;
    }

    public string index { get; set; }
    public FileName(WorkBook workbook, string index)
    {
        WorkSheet sheet = workbook.WorkSheets.First();

        foreach (var cell in sheet[index])
        {
            string path = cell.ToString();
            OriginalFile = new FileInfo(path);
            OriginalPath = NewPath = OriginalFile.DirectoryName;
            OriginalFileName = NewFileName = path;
            PathLen = path.Length;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


text:
Q: Polygamma sum problem I have a problem evaluating the following sum,
$$\sum_{n=1}^{+\infty}\frac{4nx(3\pi ^{2}(n+1)^{2}+x^{2})}{(x^{2}-\pi ^{2}(n+1)^{2})^{3}}$$
The sum obviously is of the form of a polygamma function. What i think is the right path is to do partial fractions and write it in the form $$\frac{4nx(3\pi ^{2}(n+1)^{2}+x^{2})}{(x^{2}-\pi ^{2}(n+1)^{2})^{3}}=\frac{A}{(x-\pi (n+1)))^{3}}+\frac{B}{(x+\pi (n+1))^{3}}$$ But funnily enough i have a problem finding what A and B are. Also im not 100% sure if this is the right way, but i think it is. Please help me if you can!

A: Hint
Write
$$4nx(3\pi ^{2}(n+1)^{2}+x^{2})=A (x+\pi  (n+1))^3+B (x-\pi  (n+1))^3$$
Make $x=-\pi  (n+1)$ to get
$$-16 \pi ^3 n (n+1)^3=-8 \pi ^3  (n+1)^3 B$$ which does not look too difficult.
Do the same with $x=\pi  (n+1)$ to get $A$


text: Q: How to configure default database in Ubuntu In my computer i have  PostgreSQL, using this command i have checked its running systemctl status postgresql and i have install MySQL. now i'm stopping PostgreSQL using this systemctl stop postgresq   while i'm trying to install Drupal 8 with MySQL Database type is taking  PostgreSQL as default i have stop PostgreSQL still its selecting postgres as database type i want to install with MySQL. I don't want to uninstall PostgreSQL Thanks.


text:
Q: Pagination numbers not updating properly Hey, I'm trying to get my pagination numbers to update when the user uses the filter options at the side of the page.
Here is what I'm working on: Click Here
The problem is, when you click the color - Yellow - you should only get 1 result(Giant) and only 1 page number should display. however the pagination is not updating properly and still displays all page numbers.
EDIT:
I have placed the paginateIt() function at the end of the filter script but now I get an unresponsive script warning
I have updated the script with my recent changes below:
$(document).ready(function(){

function paginateIt(){
 //how much items per page to show
 var show_per_page = 3;
 //getting the amount of elements inside content div
 var number_of_items = $('#content ul').filter(":not(.hidden)").children().size();

 //calculate the number of pages we are going to have
 var number_of_pages = Math.ceil(number_of_items/show_per_page);

 //set the value of our hidden input fields
 $('#current_page').val(0);
 $('#show_per_page').val(show_per_page);

 //now when we got all we need for the navigation let's make it '

 /*
 what are we going to have in the navigation?
  - link to previous page
  - links to specific pages
  - link to next page
 */
 var navigation_html = 'Prev';
 var current_link = 0;
 while(number_of_pages > current_link){
  navigation_html += ''+ (current_link + 1) +'';
  current_link++;
 }
 navigation_html += 'Next';

 $('#page_navigation').html(navigation_html);

 //add active_page class to the first page link
 $('#page_navigation .page_link:first').addClass('active_page');

 //hide all the elements inside content div
 $('#content ul').filter(":not(.hidden)").children().css('display', 'none');

 //and show the first n (show_per_page) elements
 $('#content ul').filter(":not(.hidden)").children().slice(0, show_per_page).css('display', 'block');

// Start filter script
(function($) {

  $.fn.randomize = function(){
    return $(this).sort(function() {return 0.5 - Math.random()});
  }

  $.fn.filterprojects = function(settings) {
    settings = $.extend({
      animationSpeed: 900,
      animationPulse: 100,
      animationEase: "linear",
      activeClass: "active",
      allTag: "all",
      randomize: true,
      show: { width: "show", opacity: "show" },
      hide: { width: "hide", opacity: "hide" },
      filterTagSelector: [] // specify at least one
      }, settings);

      $(this).each(function(i, o){
        var _elements = $(this).children();

        /* Binding the filter */
        $(this).bind("filter", function(){
          var _groups = [];
          var _filtered_elements = _elements;
          $.each(settings.filterTagSelector, function(k, j){
            _groups[k] = [];
            $(this + "." + settings.activeClass).each(function(){
              if(!$(this).hasClass(settings.allTag) && this.hash != undefined) { _groups[k].push(this.hash.substring(1)); }
            });
            if(_groups[k].length > 0){
              _filtered_elements = _filtered_elements.filter("." + _groups[k].join(",."));
            }
          });

          /* Randomize */
          if(settings.randomize){
            _filtered_elements = _filtered_elements.randomize();
            _elements = _elements.randomize();
          }
          /* Show */
          _filtered_elements.each(function(i,o){
            $(this).queue(function(){
              $(this).animate({left: "+0"}, (settings.animationPulse*i)); // dirty trick :)
              $(this).animate(settings.show, settings.animationSpeed);
              $(this).dequeue()
            });
          });

          /* Hide */
          _elements.not(_filtered_elements).each(function(i,o){
            $(this).queue(function(){
              $(this).animate({left: "+0"}, (settings.animationPulse*i)); // dirty trick :)
              $(this).animate(settings.hide, settings.animationSpeed);
              $(this).dequeue()
            });
          });
        });
        /* Setup filter selectors */
        $.each(settings.filterTagSelector, function(k, j){
          $(""+this).click(function(e){
            e.preventDefault();
            if($(this).hasClass(settings.allTag)){
              $(j).removeClass(settings.activeClass);
              $(this).addClass(settings.activeClass);
            } else {
              $(this).hasClass(settings.activeClass) ? $(this).removeClass(settings.activeClass) : $(this).addClass(settings.activeClass);
              $(j+"."+settings.activeClass).length > 0 ? $(j+"."+settings.allTag).removeClass(settings.activeClass) : $(j+"."+settings.allTag).addClass(settings.activeClass);
            }
            /* Triggering the filter */
            $(o).trigger("filter");
          })
        });
      });
      return this
    };
})(jQuery); // End filter script
paginateIt();
} // End PaginateIt script
paginateIt();

}); // End of JS script.

function previous(){

 new_page = parseInt($('#current_page').val()) - 1;
 //if there is an item before the current active link run the function
 if($('.active_page').prev('.page_link').length==true){
  go_to_page(new_page);
 }

}

function next(){
 new_page = parseInt($('#current_page').val()) + 1;
 //if there is an item after the current active link run the function
 if($('.active_page').next('.page_link').length==true){
  go_to_page(new_page);
 }

}
function go_to_page(page_num){
 //get the number of items shown per page
 var show_per_page = parseInt($('#show_per_page').val());

 //get the element number where to start the slice from
 start_from = page_num * show_per_page;

 //get the element number where to end the slice
 end_on = start_from + show_per_page;

 //hide all children elements of content div, get specific items and show them
 $('#content ul').filter(":not(.hidden)").children().css('display', 'none').slice(start_from, end_on).css('display', 'block');

 /*get the page link that has longdesc attribute of the current page and add active_page class to it
 and remove that class from previously active page link*/
 $('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');

 //update the current page input field
 $('#current_page').val(page_num);
}

A: Since paginateIt is responsible for rendering the page numbers below, shouldn't you call it every time a new filter is applied?


text:
Q: Is it ok to have multiple files table for a different entity? I have two entities A and B.
A and B can have multiple files associated to them, each of those files can be a document or an image.
Does it make sense to create a_files and b_files tables with the the following structure?
id | a_id | url | type(enum)
id | b_id | url | type(enum)
I thought about creating a generic files table too and then reference it through a/b_files, but it seems to me a kind of over-killing joins.

A: If your two tables are exactly the same in structure then very likely they should be a single table. Your example with two separate tables appears redundant making it more work to maintain in the long run and potentially more error prone.
"I thought about creating a generic files table too and then reference it through a/b_files, but it seems to me a kind of over-killing joins." - Design your tables in the way that makes the most logical sense to your use cases and object structure, worry about performance after that if it's even necessary. Modern relational database systems can handle large numbers of rows just fine when indexed properly, even when joining.
Generically speaking, it sounds like all you need is a single table defined as (id, url, type, entity_id).


text:
Q: Why is IE not resolving host names in /etc/hosts but all other browsers does I have multiple hosts set up in /etc/hosts file in windows machine. My issue is that I am not able to access any of the host entries in /etc/hosts file in IE browsers. But I can access the hosts in all other browsers except IE browsers.
My host file looks like :
127.0.0.1       localhost
127.0.0.1       apache.local.com
127.0.0.1       iis.local.com

If I take apache.local.com or iis.local.com in IE browser it just loads forever but in other browsers it loads fine and take me to the wamp server localhost page.
pinging those hosts looks ok
ping apache.local.com
C:\Windows\system32>ping apache.local.com

Pinging apache.local.com [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

ping iis.local.com
C:\Windows\system32>ping iis.local.com

Pinging iis.local.com [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

This is looking weird because other browsers works OK but only IE does have the issue it just loads forever.
I tried resetting the IE browser and flushed the DNS entries and rebooted the machine several time but still it does not work.
My system is Windows8 64 bit and have wamp and IIS with PHP and MySQL extensions installed.
Can anyone help with this?

A: You can try follwoing steps taking a note of fact that *

Resetting will reset IE to factory settings. You'll lose your existing
  configuration and any settings or data in IE. Judging by your love for
  this browser, I'm assuming there isn't any data in there that you care
  about. ;) However, be sure you're okay with this before following
  these steps

*
Steps :

*

*Open Tools -> Internet Options

*Click on the "Advanced" tab.

*Click    "Reset"

*Click the checkbox for "Delete personal settings"

*In the    Reset Internet Explorer Settings dialog box, click "Reset".

*When    changes are done, click "Close" and then restart the browser.

A: I was able to resolve the issue. I see that if I start IIS server and visit the hosts in IE browsers everything worked fine. The issue happens only when I start Apache and browse on to that hosts.
My Apache version was 2.4.4. I switched to Apache 2.2.2 and everything worked fine. I think it would have been an issue with Apache 2.4.4. But I am still confused of the fact that it worked in other browsers, the issue was only with IE browsers.
Anyway switching on the Apache version did the trick for me.
Thanks for all your help :)

A: IPv6 may be something you want to look into here: https://superuser.com/questions/433258/ipv6-local-address-in-hosts-file
Could be IE is looking for IPv6 and the other browsers are using the traditional IPv4.


text:
Q: Basic GUI window not appearing Doing a basic two panel code panel is to give the information and provide a box to input data, and the second simply to quit or execute. Initially, the blank window would appear, but after adding panelTwo and the window no longer appears.
The program compiles and shows no errors, except in the main class it tells me "New instance ignored" pertaining to new SalesClassGUI ();. Unsure how to procede any help would be appreciated!
public class SalesClassGUI extends JFrame {

    private JPanel panelOne;
    private JPanel panelTwo;

    private JLabel associateNameLabel;
    private JLabel associateNumberLabel;
    private JLabel productSoldLabel;
    private JLabel productPriceLabel;
    private JLabel stateCodeLabel;
    private JLabel regionCodeLabel;
    private JLabel productNumberLabel;
    private JLabel productDescripLabel;

    private JTextField associateNameField;
    private JTextField associateNumberField;
    private JTextField productSoldField;
    private JTextField productPriceField;
    private JTextField stateCodeField;
    private JTextField regionCodeField;
    private JTextField productNumberField;
    private JTextField productDescripField;

    private JButton calcButton;
    private JButton exitButton;

    private final int WINDOW_WIDTH = 500;
    private final int WINDOW_HEIGHT = 500;

    public void SalesClassGUI() {

        setTitle("Associate Tracker");
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout (new GridLayout (8,1));
        buildPanel();
        add(panelOne);
        add(panelTwo);
        setVisible(true);
    }

    private void buildPanel() {

        associateNameLabel = new JLabel("Enter name of associate");
        associateNumberLabel = new JLabel("Enter associate number");
        productSoldLabel = new JLabel("Enter number of product sold");
        productPriceLabel = new JLabel("Enter price of the product");
        stateCodeLabel = new JLabel("Enter state code");
        regionCodeLabel = new JLabel("Enter region code");
        productNumberLabel = new JLabel("Enter product number");
        productDescripLabel = new JLabel("Enter product description");

        associateNameField = new JTextField();
        associateNumberField = new JTextField();
        productSoldField = new JTextField();
        productPriceField = new JTextField();
        stateCodeField = new JTextField();
        regionCodeField = new JTextField();
        productNumberField = new JTextField();
        productDescripField = new JTextField();

        //associate name
        panelOne = new JPanel();
        /*panelOne.setLayout(new GridLayout(8, 2));*/

        panelOne.add(associateNameLabel);
        panelOne.add(associateNameField);

        //associate number
        panelOne.add(associateNumberLabel);
        panelOne.add(associateNumberField);

        //prouct sold
        panelOne.add(productSoldLabel);
        panelOne.add(productSoldField);

        //product price
        panelOne.add(productPriceLabel);
        panelOne.add(productPriceField);

        //state code
        panelOne = new JPanel();
        panelOne.add(stateCodeLabel);
        panelOne.add(stateCodeField);

        //region code
        panelOne.add(regionCodeLabel);
        panelOne.add(regionCodeField);

        //product number
        panelOne.add(productNumberLabel);
        panelOne.add(productNumberField);

        //product description
        panelOne.add(productDescripLabel);
        panelOne.add(productDescripField);

        panelTwo = new JPanel();

        panelTwo.setLayout(new GridLayout(1, 2));

        // Define the button
        calcButton = new JButton("Calculate");

        // Add the buttons to the panel
        panelTwo.add(calcButton);
        panelTwo.add(exitButton);

    }

    public static void main(String[] args) {
        SalesClassGUI salesClassGUI = new SalesClassGUI();
    }
}

A: Your class has no constructor.  So when you call new SalesClassGUI(), the default constructor is invoked, which does nothing.  And then your program just terminates.
To properly declare a constructor, you need to omit the return type.
Change:
public void SalesClassGUI() {

to:
public SalesClassGUI() {

Note: you're going to get an NPE because your ctor has some bugs, but this will remove the "nothing happens" problem.  I found this by stepping through the code in a debugger.  You should learn to do that as well.
Also, another good debugging technique is just to add some print statements to track the flow of the program, and to verify that the code is reaching certain points.  This is what tipped me off that that the something was seriously off and I needed to use the debugger.
public SalesClassGUI() {
    setTitle("Associate Tracker");
    System.err.println( "ctor" );
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout (new GridLayout (8,1));
    buildPanel();
    add(panelOne);
    add(panelTwo);
    pack();
    System.err.println( "setvisible true" );
    setVisible(true);
}

When "ctor" didn't print I knew something was really wrong.


text:
Q: How to understand "tables" in Hierarchical Dirichlet Process(HDP)? In Hierarchical Dirichlet Process, the author gives an interpretation of HDP using Chinese Restaurant Franchise. It said that each restaurant has many tables and different tables may share a common dish in one restaurant. The dish here we can regarded as a topic in the document, then how to understand tables in every document? I think different tables should order different dishes, if two tables with the same dish, then why not merge them into one? Thanks a lot.

A: In the Chinese Restaurant Franchise (CRF), each document is a restaurant, each word is a customer, and cluster parameters are dishes served to tables from a global menu. A customer enters a restaurant and sits at a table with probability proportional to the number of customers already at a table, or sits at a new table with probability alpha. New tables are then assigned a particular dish with probability proportional to the number of tables already serving that dish, or a new dish with probability gamma.
Thus, for every customer we have an index that maps the customer to the table and for every table we have an index that maps the table to one of the dishes. A Gibbs sampling algorithm, first samples tables associated with data, and then samples dishes associated with each table. For more details see Yee Whye Teh's implementation.


text:
Q: How to have only inner margins in wrapped float left list I was wondering how I could have a wrapped list of <li> elements using float: left; that didn't have any outer margins, only margins in between the elements. Here is an example of what I DON'T want as it has margins around the outside of the list whereas I want the border of the outer list to be touching the borders of the inner list items. Here is an example of what I DO want however I find this solution to be hacky, as it requires the use of a second container outside the <ul> to act as the list border, if you stick a border on the <ul> itself you will see that it is still 10px away from the list items, I also prefer avoiding negative margins unless I really need to use them.
It seems as though float is designed to pull elements like pictures to the side and allow text to flow either side of them, and not as a way to make horizontal wrapping list, due to the natural behavior of not considering floated child elements when determining height. Because of this I was also wondering if it would be better to use something like flexbox for things like this.

A: You're correct, this is a fundamental abuse of float.  Flexbox would be one way to approach this, yes.


text:
Q: np.where() equivalent to df.loc() I am just practicing\learning pandas, and I am using the Pokemon dataset
from Kaggle.
The following two lines of code work fine, and produce the exact same result:
df.loc[df['Type 1'] == 'Fire', 'Type 1'] = 'Flamer'

df['Type 1'] = np.where(df['Type 1'] == 'Fire', 'Flamer', df['Type 1'])

Both replace the value 'Fire' in the column 'Type 1' with 'Flamer'.
However, I am trying to replicate that same behavior over multiple columns.
In the following two lines of code, the first one works, the second fails.
Exact error is also supplied:
df.loc[df['Total'] > 500, ['Generation', 'Legendary']] = 'TEST VALUE'

df[['Generation', 'Legendary']] = np.where(df['Total'] > 500, 'TEST VALUE', df[['Generation', 'Legendary']])

Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 152, in <module>
    df[['Generation', 'Legendary']] = np.where(df['Total'] > 500, 'TEST VALUE', df[['Generation', 'Legendary']])
ValueError: operands could not be broadcast together with shapes (800,) () (800,2)

I do not understand what that error is trying to tell me.
Can I not replicate:  df.loc[df['Total'] > 500, ['Generation', 'Legendary']] = 'TEST VALUE'  using np.where()?

A: As was pointed out by @Divakar , my syntax was wrong.  df['Total'] > 500 needed to be: df[['Total']] > 500 in my np.where() line of code.
df.loc[df['Total'] > 500, ['Generation', 'Legendary']] = 'TEST VALUE'

is successfully replicated by:
df[['Generation', 'Legendary']] = np.where(df[['Total']] > 500, 'TEST VALUE', df[['Generation', 'Legendary']])

I then took it a step further and gave the 'Generation' and 'Legendary' columns their own unique values.
The following two lines of code also generate the same, correct results:
df.loc[df['Total'] > 500, ['Generation', 'Legendary']] = ['Test 1', 'Test 2']

df[['Generation', 'Legendary']] = np.where(df[['Total']] > 500, [['TEST 1', 'TEST 2']], df[['Generation', 'Legendary']])


text:
Q: Django database migrations stop with addition of "Meta" class I've created a Django application and I have a model like such:
class Company(models.Model):
    name = models.TextField(max_length = 200)

When I run python3 manage.py makemigrations appname, everything works as expected, and a migration file for the class is created.
The problem happens if the class in the model defines a Meta class as well:
class Company(models.Model):
    name = models.TextField(max_length = 200)
    class Meta:
        app_label = "Companies"

Now, if I run the makemigrations command, I either get a "no changes detected" message, and no migration file is generated:
> python3 manage.py makemigrations myApp
No changes detected in app 'appname'

Or, worse yet, if the model with the Meta class had no dependencies (foreign keys), a migration is created that will drop the model/table entirely.
Or, if there is a dependency (foreign key reference from another model), I get an error like so:
matcher.OtherTable.foreignkeyref: (fields.E300) Field defines a relation with model 'Company', which is either not installed, or is abstract.

All models with a Meta class defined will not generate a migration, either an initial one or any subsequent migration for some reason. Classes that have Meta added after the fact will be removed at the next migration. It becomes as if they don't exist at all.
I'm using Python 3.8.3 and Django 3.0.6 on Mac OS 10.15.5.

A:
All models with a Meta class defined will not generate a migration, either an initial one or any subsequent migration for some reason. Classes that have Meta added after the fact will be removed at the next migration.

Well the problem is that you change the app_label, o now you say that this model does not belong in the app where it belonged to intially, but somewhere else. So for that app, the models have "vanished", and for a new app (Companies here), it appeared "out of thin air". As is specified in the documentation, one uses an app_label when:

If a model is defined outside of an application in INSTALLED_APPS, it must declare which app it belongs to (…).

It is quite rare to specify an app_label. If you do not specify it, it takes the name of app it is defined in.
It looks like you are however overriding the wrong setting. Based on the value you pass it, you likely want to specify the verbose_name_plural option [Django-doc]:
class Company(models.Model):
    name = models.TextField(max_length = 200)

    class Meta:
        verbose_name_plural = "Companies"


text:
Q: How can I set the index fill factor back to server default? I have some indexes that I was playing with on my dev server.  I set the fill factor of these indexes using the following command:
alter index all on dbo.Table
rebuild with (fillfactor=80)

That sets and rebuilds all of the index on dbo.Table.  Now what I want is to set the fillfactor back to the default of the server.  IE, at the server level all indexes are set to have a fillfactor of 95.  I want the indexes to use the server default again, not just have the fill factor set to 95.
The reason I want to do this is so that, if I script this index and move it to a new server, it will use the default fill factor of that server rather than the specified 95.

A: Through testing, it seems as though to get back to the default fillfactor on an index you need to drop and recreate it.  When you do an ALTER INDEX ... REBUILD, any unspecified parameters will remain the same in the index's metadata unless otherwise explicitly changed in the ALTER INDEX command.
drop index IX_YourIndex
on YourTable
go

create index IX_YourIndex
on YourTable(YourKeyColumn)
go

To verify this:
select
    name,
    fill_factor
from testdb.sys.indexes
where name = 'IX_YourIndex'

fill_factor should be set to 0 to denote that it is using the instance's default value.  (Note: 0 is for the default value, even if the instance configured fill factor is set to 95)


text:
Q: dicom header personal information conversion to a .txt file I have a series of DICOM Images which I want to anonymize, I found few Matlab codes and some programs which do the job, but none of them export a .txt file of removed personal information. I was wondering if there is a function which can also save removed personal information of a DICOM images in .txt format for features uses. Also, I am trying to create a table which shows the corresponding new images ID to their real name.(subjects real name = personal-information-removed image ID)
Any thoughts?
Thanks for considering my request!

A: I'm guessing you only want to output to your text file the fields that are changed by anonymization (either modified, removed, or added). First, you may want to modify some dicomanon options to reduce the number of changes, in particular passing the arguments 'WritePrivate', true to ensure private extensions are kept.
First, you can perform the anonymization, saving structures of pre- and post-anonymization metadata using dicominfo:
preAnonData = dicominfo('input_file.dcm');
dicomanon('input_file.dcm', 'output_file.dcm', 'WritePrivate', true);
postAnonData = dicominfo('output_file.dcm');

Then you can use fieldnames and setdiff to find fields that are removed or added by anonymization, and add them to the post-anonymization or pre-anonymization data, respectively, with a nan value as a place holder:
preFields = fieldnames(preAnonData);
postFields = fieldnames(postAnonData);

removedFields = setdiff(preFields, postFields);
for iField = 1:numel(removedFields)
  postAnonData.(removedFields{iField}) = nan;
end

addedFields = setdiff(postFields, preFields);
for iField = 1:numel(addedFields)
  preAnonData.(addedFields{iField}) = nan;
end

It will also be helpful to use orderfields so that both data structures have the same ordering for their field names:
postAnonData = orderfields(postAnonData, preAnonData);

Finally, now that each structure has the same fields in the same order we can use struct2cell to convert their field data to a cell array and use cellfun and isequal to find any fields that have been modified by the anonymization:
allFields = fieldnames(preAnonData);
preAnonCell = struct2cell(preAnonData);
postAnonCell = struct2cell(postAnonData);
index = ~cellfun(@isequal, preAnonCell, postAnonCell);
modFields = allFields(index);

Now you can create a table of the changes like so:
T = table(modFields, preAnonCell(index), postAnonCell(index), ...
          'VariableNames', {'Field', 'PreAnon', 'PostAnon'});

And you could use writetable to easily output the table data to a text file:
writetable(T, 'anonymized_data.txt');

Note, however, that if any of the fields in the table contain vectors or structures of data, the formatting of your output file may look a little funky (i.e. lots of columns, most of them empty, except for those few fields).

A: One way to do this is to store the tags before and after anonymisation and use these to write your text file. In Matlab, dicominfo() will read the tags into a structure:
% Get tags before anonymization
tags_before = dicominfo(file_in);

% Anoymize
dicomanon(file_in, file_out); % Need to set tags values where required

% Get tags after anonymization
tags_after = dicominfo(file_out);

% Do something with the two structures
disp(['Patient ID:', tags_before.PatientID ' -> ' tags_after.PatientID]);
disp(['Date of Birth:', tags_before.PatientBirthDate ' -> ' tags_after.PatientBirthDate]);
disp(['Family Name:', tags_before.PatientName.FamilyName ' -> ' tags_after.PatientName.FamilyName]);

You can then write out the before/after fields into a text file. You'd need to modify dicomanon() to choose your own values for the removed fields, since by default they are set to empty.


text:
Q: jQuery dialog modal being called twice on click So... I have a site here...
The jQuery dialog is sending an ajax request to here.
There's an auto-popup when you arrive on the page. Please Dismiss that one.
When you click on this image...

which is associated with this function call...
$(function() {
    $("#compliance").dialog({
        autoOpen: true,
        modal: true,
        width: 750,
        height: 'auto',
        show: 'fade',
        hide: 'fade',
        position: {my: "center top", at:"center top", of: window },
        buttons: {
            "Dismiss": function() {
                $(this).dialog("close");
            }
        }
    });
    $(".dialogify").on("click", function(e) {
        e.preventDefault();
        $("#compliance").html("");
        $("#compliance").dialog("option", "title", "Loading...").dialog("open");
        $("#compliance").load(this.href, function() {
            $(this).dialog("option", "title", $(this).find("h1").text());
            $(this).find("h1").remove();
    });
    });
});

Or this one...

which is associated with this function...
$(function() {
    $("#switch").dialog({
        autoOpen: false,
        modal: true,
        width: 750,
        height: 'auto',
        show: 'fade',
        hide: 'fade',
        position: {my: "center top", at:"center top", of: window },
        buttons: {
            "Dismiss": function() {
                $(this).dialog("close");
            }
        }
    });
    $(".dialogify").on("click", function(e) {
        e.preventDefault();
        $("#switch").html("");
        $("#switch").dialog("option", "title", "Loading...").dialog("open");
        $("#switch").load(this.href, function() {
            $(this).dialog("option", "title", $(this).find("h1").text());
            $(this).find("h1").remove();
    });
    });
});

...a modal comes up. But it appears that two modals come up. The opaque background is darker than it should be. And, when you dismiss the first one, there's another one, as the background gets lighter.
Why is this? I only have one function call for each.

A: Well, you have two event handlers that display the dialog, and both are triggered by the same action (a click on any .dialogify). So both handlers are attempting to handle a click on both .dialogify elements; clicking on any one causes both dialogs to appear (although they load the same content, as this.href is unique to each click target). You can confirm this by putting an alert("a") inside your first handler and alert("b") inside the second.
Instead of this, simply use a selector that uniquely identifies the click target for each event and the problem will be solved.


text:
Q: Find and example of two elements $a,b$ in a finite group $G$ such that $|a| = |b| = 2, a \ne b$ and $|ab|$ is odd. Find and example of two elements $a,b$ in a finite group $G$ such that $|a| = |b| = 2, a \ne b$ and $|ab|$ is odd. Any ideas as to how I would go about finding it?
Thanks

A: There is a very general example you should know about, that of dihedral groups. A dihedral group has order $2n$, for any $n \ge 2$, and it is generated by two elements of order $2$, whose product has order $n$.
Probably the simplest way to see these groups is as a group of bijective maps on $\mathbf{Z}_{n}$,
$$
a : x \mapsto -x, \qquad b: x \mapsto -x-1.
$$
(Coefficients are written as integers, but meant to be in $\mathbf{Z}_{n}$.) These are clearly elements of order $2$, while because of
$$
a \circ b(x) = (a(b(x)) = -(-x - 1) = x + 1
$$
$ab = a \circ b$ has order $n$.
(Geometrically, such a group is the group of congruences of a regular $n$-gon.)
If you do the same thing over $\mathbf{Z}$, you find that $ab$ has infinite order.

A: In $S_3$ the multiplication of $(a,b)$ and $(b,c)$ is $(a,b,c)$


text:
Q: beginner question on investigating on samples in Weka I've just used Weka to train my SVM classifier under "Classify" tag.
Now I want to further investigate which data samples are mis-classified,I need to study their pattern,but I don't know where to look at this from Weka.
Could anyone give me some help please?
Thanks in advance.

A: You can enable the option from:

You will get the following instance predictions:
=== Predictions on test split ===

 inst#     actual   predicted  error prediction
   1   2:Iris-ver  2:Iris-ver         0.667
  ...
  16   3:Iris-vir  2:Iris-ver   +     0.667

EDIT
As I explained in the comments, you can use the StratifiedRemoveFolds filter to manually split the data and create the 10-folds of the cross-validation.
This Primer from the Weka wiki has some examples of how to invoke Weka from the command line. Here's a sample bash script:
#!/bin/bash

# I assume weka.jar is on the CLASSPATH

# 10-folds CV
for f in $(seq 1 10); do
    echo -n "."

    # create train/test set for fold=f
    java weka.filters.supervised.instance.StratifiedRemoveFolds -i iris.arff \
        -o iris-f$f-train.arff -c last -N 10 -F $f -V
    java weka.filters.supervised.instance.StratifiedRemoveFolds -i iris.arff \
        -o iris-f$f-test.arff -c last -N 10 -F $f

    # classify using SVM and store predictions of test set
    java weka.classifiers.functions.SMO -C 1.0 \
        -K "weka.classifiers.functions.supportVector.RBFKernel -G 0.01" \
        -t iris-f$f-train.arff -T iris-f$f-test.arff \
        -p 0 > f$f-pred.txt
        #-i > f$f-perf.txt
done
echo

For each fold, this will create two datasets (train/test) and store the predictions in a text file as well. That way you can match each index with the actual instance in the test set.
Of course the same can be done in the GUI if you prefer (only a bit more tedious!)


text:
Q: Matplotlib colorbar with consistent size for multiple subplots I am trying to create a figure with several subplots that have a common colorbar. The subplots have to have an equal aspect ratio and the colorbar has to have the same height as the subplots. However, I don't manage to get a narrow colorbar with the same height as the other subplots.
I am using this recipe to generate a colorbar with a range suitable for all subplots; hence this issue is not addressed in the MWE.
When using the axes divider recipe to attach the colorbar, the height of the subplot changes due to the aspect ratio.
Here's the MWE
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

import itertools as it
import numpy as np

mean = [0, 0]
cov = [[1, 0.5],
       [0.5, 4]]
n_samples = 10000
hrange = [[-5,5],[-5,5]]
bins = 20

# RANDOM DATA
Z_random = np.random.multivariate_normal(mean, cov, size=n_samples)
Z, xedges, yedges = np.histogram2d(Z_random[:,0], Z_random[:,1], bins=bins, range=hrange, normed=True)
X, Y = np.meshgrid(xedges, yedges)

# PLOT PCOLORMESHS
fig, axes = plt.subplots(2,3, subplot_kw=dict(aspect="equal"))
axes = dict(enumerate(fig.get_axes(),1))

for i,ax in axes.items():
    if i==6:
        break
    pcm = ax.pcolormesh(X,Y,Z)

# PLOT COLORBAR
divider = make_axes_locatable(axes[6])
cax = divider.append_axes("left", size="15%", pad=0.0)
fig.colorbar(pcm, cax=cax, label=r"Colorbar label")

I can plot the colorbar over the complete subplot, in which case the height is correct, but it's much to wide to be appealing.
Does anybody have a "robust" solution, i.e. without manually fiddling around with the dimension of the subplots holding the colorbar?
Thanks in advance!
EDIT: Increased width of colorbar to emphasize that it becomes smaller in height.

A: If the only aim is to get the height of the colorbar correctly aligned with its horizontal neighbor, the last solution from this answer would help.
If however you also want the colorbar to be left-aligned with the plot on top of it, the solution is probably more complicated.
You may use a callback to set the position of the colorbar explicitely as follows:
from matplotlib import pyplot as plt
from matplotlib.transforms import Bbox
import numpy as np

mean = [0, 0]
cov = [[1, 0.5],
       [0.5, 4]]
n_samples = 10000
hrange = [[-5,5],[-5,5]]
bins = 20

# RANDOM DATA
Z_random = np.random.multivariate_normal(mean, cov, size=n_samples)
Z, xedges, yedges = np.histogram2d(Z_random[:,0], Z_random[:,1], bins=bins, range=hrange, normed=True)
X, Y = np.meshgrid(xedges, yedges)

# PLOT PCOLORMESHS
fig, axes = plt.subplots(2,3, subplot_kw=dict(aspect="equal"))

for i,ax in enumerate(axes.flat):
    if i==5:
        break
    pcm = ax.pcolormesh(X,Y,Z)

# PLOT COLORBAR
cax = fig.add_axes([0.6,0.01,0.1,0.4])
fig.colorbar(pcm, cax=cax, label=r"Colorbar label")

def align_cbar(cax, hax, vax):
    hpos = hax.get_position()
    vpos = vax.get_position()
    bb = Bbox.from_extents(vpos.x0, hpos.y0, vpos.x0+vpos.width*.05,hpos.y1)
    if cax.get_position() != bb:
        cax.set_position(bb)
        fig.canvas.draw_idle()

align_cbar(cax, axes[1,1], axes[0,2])
fig.canvas.mpl_connect("draw_event", lambda x: align_cbar(cax, axes[1,1], axes[0,2]))

plt.show()


text:
Q: Hide  when there is nothing in gridview in ASP.NET using VB.NET I am trying to hide a TD named ImportnatInfo in a table when the gridview is empty. This gridview has one column from a table in a database to show. When this gridview is empty I want to hide the TD.
The following is the asp code:

                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderStyle="None"
                    DataSourceID="ImportantSqlDataSource">
                    <Columns>
                        <asp:BoundField DataField="Importatnat_Info" SortExpression="Importatnat_Info">
                            <ControlStyle BorderStyle="None" Height="10px" />
                            <FooterStyle BorderStyle="None" Height="10px" />
                            <HeaderStyle BorderStyle="None" Height="10px" />
                            <ItemStyle BorderStyle="None" Height="10px" HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField>
                    </Columns>
                </asp:GridView>
                <asp:SqlDataSource ID="ImportantSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AgainConnectionString %>"
                    SelectCommand="SELECT [Importatnat_Info] FROM [StationInfoTable] WHERE ([StationNo] = @StationNo)">
                    <SelectParameters>
                        <asp:ControlParameter ControlID="ddlStationNames" Name="StationNo" PropertyName="SelectedValue"
                            Type="Int32" />
                    </SelectParameters>
                </asp:SqlDataSource>

And the VB.net code is the following:
If GridView1.Rows.Count = 0 Then
        ImportnatInfo.Visible = False
    Else
        ImportnatInfo.Visible = True
    End If

I have dropdownlist and i choose something everytime so if there is nothing in the grid to view, i want the whole TD to be invisible. the TD that im trying to hide when it is empty, the thing the TD is always visible because when there is nothing in the gridView Vb add   so it won't be empty. so i thought i should use the datasource and still not sure what to do. Any idea how to do that?

A: Check the type of row (via row.RowType); it's probably not a data row, but an empty row or header row or something else. So you need to make sure rows with an ItemType of Item or AlternateItem are the type you are counting.  You can see more detailed information about this property here.
EDIT: You can use LINQ to filter the results of the appropriate type:
Dim cnt = GridView1.Rows.Where( _
  Function(i) i.RowType = DataControlRowType.Item OrElse _
              i.RowType = DataControlRowType.AlternateItem).Count()
If cnt = 0 Then
    ImportnatInfo.Visible = False
Else
    ImportnatInfo.Visible = True
End If

A: Try hooking into the Selected event of your data source
<asp:SqlDataSource ID="ImportantSqlDataSource" OnSelected="SqlDataSource1_Selected" runat="server" ConnectionString="<%$ ConnectionStrings:AgainConnectionString %>"
  SelectCommand="SELECT [Importatnat_Info] FROM [StationInfoTable] WHERE ([StationNo] = @StationNo)">
  <SelectParameters>
        <asp:ControlParameter ControlID="ddlStationNames" Name="StationNo" PropertyName="SelectedValue" Type="Int32" />
  </SelectParameters>

Note OnSelected="SqlDataSource1_Selected"
Then in your code behind
Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Selected
    ImportnatInfo.Visible = e.AffectedRows > 0

End Sub

Your gridview may have rows even if no data is returned: headers, footers and/or a now data found message.
UPDATE
Also try the following
Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Selected
    ImportnatInfo.Visible = e.AffectedRows > 0
    Gridview1.Visible = e.AffectedRows > 0

End Sub

This should also set the gridview to not show when there are no rows, regardless of the visibility of the td. I would also try moving your datasource outside of the td it shouldn't make a difference, but it may.
If after trying this if the gridview is hidden, but the td remains visible there may be something happening later in the page life cycle that is affecting the visibility of the td.

A:   GridView1.DataBind()
    ImportantInfo.Visible = True
    If GridView1.Rows.Count = 1 Then
        If GridView1.Rows(0).Cells.Count = 1 Then
            If GridView1.Rows(0).Cells(0).Text.Trim() = " " Then
                ImportantInfo.Visible = False

            End If

        End If
    Else
        ImportantInfo.Visible = False
    End If

ASP.NET always leave a space   when there is nothing in the GridView. So, I check if it is empty or not if not i check if it is the space or the GridView has some data.

A:         GridView1.DataBind()
    ImportnatInfo.Visible = True
    If GridView1.Rows.Count >= 1 Then
        If GridView1.Rows(0).Cells.Count >= 1 Then
            If GridView1.Rows(0).Cells(0).Text.Trim() = " " Then
                ImportnatInfo.Visible = False
            Else
                ImportnatInfo.Visible = True
            End If
        End If
    Else
        ImportnatInfo.Visible = False
    End If

Yours is working good but you just need to add Else to show the TD after you check it is not


text:
Q: How could I find the number of movies every two actors had played the below Data Frame? I have a Data Frame:
pd.DataFrame({'movie':['HT','TP','Wi','kah','MB'],'actors':[['QQ','AA','ZZ','WW','SS','XX'],['QQ','WW','EE','DD','SS','AA'],['EE','DD','CC','RR','FF','VV'],['VV','CC','XX','ZZ','FF','DD'],['SS','AA','RR','EE','WW','QQ']]})

that is a movie DataFrame with all the actors in each movie, I want to find out the number of movies every two actors had played together. e.g. the number of movies the artistic couple 'AA' and 'QQ' had played with each other.

A: Let's try exploding actors then self-merge:
s = df.explode('actors')
(s.merge(s, on='movie')
  .query('actors_x<actors_y')
  .groupby(['actors_x','actors_y']).size()
  .unstack('actors_y', fill_value=0)
)

Output:
actors_y  DD  EE  FF  QQ  RR  SS  VV  WW  XX  ZZ
actors_x
AA         1   2   0   3   1   3   0   3   1   1
CC         2   1   2   0   1   0   2   0   1   1
DD         0   2   2   1   1   1   2   1   1   1
EE         0   0   1   2   2   2   1   2   0   0
FF         0   0   0   0   1   0   2   0   1   1
QQ         0   0   0   0   1   3   0   3   1   1
RR         0   0   0   0   0   1   1   1   0   0
SS         0   0   0   0   0   0   0   3   1   1
VV         0   0   0   0   0   0   0   0   1   1
WW         0   0   0   0   0   0   0   0   1   1
XX         0   0   0   0   0   0   0   0   0   2

A: Another option is below. Quang Hong's answer above is probably far faster and more in the spirit of using pandas, but here's another way to do it:
from itertools import combinations, chain
# chain.from_iterable concatenates all of the lists in actors into one list.
# set gets only the unique elements
unique_actors = set(chain.from_iterable(df["actors"]))
num_movies_for_actor_pair = {}

# combinations gets every unique combination of 2 actors
for combination in combinations(unique_actors, 2):
    actor_1 = combination[0]
    actor_2 = combination[1]
    # creates a 1 or 0 binary column for whether the current actor pair was in the movies together,
    # then sums it to get the total number of movies
    num_movies = np.sum(df.apply(lambda row: actor_1 in row["actors"] and actor_2 in row["actors"], axis=1))
    # makes a string of the two actor names to act as a key in the dictionary
    actor_pair = "{},{}".format(actor_1, actor_2)
    # adds the number of movies to the dictionary for this actor pair
    num_movies_for_actor_pair[actor_pair] = num_movies

print(num_movies_for_actor_pair)


text:
Q: how to sort string array in ascending order using sort function in C Suppose I have a structure named dictionary which contains two char array. I want to sort the dictionary type array 'pair' in ascending order according to the second char array . how to do that using sort function? How do I need to modify the comp?

A: #include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct
{
    unsigned char message[100];   // string to be sorted
                                  // (totally arbitrary length)
    unsigned char sortOrder[256]; // string containing ASCII chars
                                  // in their sort order
} Pair;

unsigned char rank[256]; // rank of each ASCII character

// qsort() comparison function
int sortByRank(const void *a, const void *b)
{
    return ((int)rank[*(signed char *)a] - (int)rank[*(signed char *)b]);
}

// Creates an array by which a character's relative position can be found
// solely from its value.  Characters of rank 0 will appear first when sorted.
// Characters not specified by sortOrder will appear first, since rank is
// global and automatically initialized to zeros.
void initRank(Pair pair)
{
    int i;

    for (i = 0; i < strlen(pair.sortOrder); i++)
        rank[pair.sortOrder[i]] = i;

    return;
}

int main()
{
    // Create an example pair.  Spaces will be the first characters in the
    // sorted result.
    Pair pair;
    strcpy(pair.message, "this is a test message (123).");
    strcpy(pair.sortOrder, " 321abcdefghijklm.nopqrstuvwxyz()");

    // In this solution, initRank() will need to be called any time the
    // sortOrder is changed.
    initRank(pair);

    // Sort using the global rank array set by initRank()
    qsort(pair.message, strlen(pair.message), sizeof(char), sortByRank);

    printf("Sorted message: %s\n", pair.message);

    // Output:
    // Sorted message:      321aaeeeghiim.sssssttt()

    return 0;
}

Since rank[] is global, this isn't as elegant as might be, but the above solution generally demonstrates how to make use of C's sorting function to do a custom sort based on a second string in a fairly straightforward manner.


text:
Q: I am getting error while implementing ngx-Spinner 8.0.3 I want a spinner loader to be implemented in my app.
I am following the process given here
[ https://www.npmjs.com/package/ngx-spinner ]
I installed and Saved it.
And When I am importing and adding it to "imports", I am getting the following error.
Uncaught TypeError: Object(...) is not a function
    at ngx-spinner.js:208
    at Module../node_modules/ngx-spinner/fesm5/ngx-spinner.js (ngxspinner.js:210)
    at webpack_require (bootstrap:78)
    at Module../src/app/app.module.ts (app.component.ts:23)
    at webpack_require (bootstrap:78)
    at Module../src/main.ts (main.ts:1)
    at webpack_require (bootstrap:78)
    at Object.0 (main.ts:12)
    at webpack_require (bootstrap:78)
    at checkDeferredModules (bootstrap:45)
npm i ngx-spinner
npm install ngx-spinner --save

aap.module.ts

    import { NgxSpinnerModule } from "ngx-spinner";

    imports: [
        // ...
        NgxSpinnerModule
    ]

I am not getting how to get out of this error If anyone can please help me.

A: This must be a version mismatch between your angular version and the version of ngx-spinner. Please make sure if you are on angular 7 then you must install 7.* version of this library. Similarly if on angular 8 then, use 8.* version of ngx-spinner.
Issue on github for further help - https://github.com/Napster2210/ngx-spinner/issues/100

A: First: When you got this error, first you need to remove the imports of Ngx from app.component.ts and from all other components aswell.
Second: Remove your Node Module folder and use the command npm install.
In my case, I'm using angular 11 .


text:
Q: Método PCA para feature selection - Como solucionar o erro raise Exception("Data must be 1-dimensional")? Estou tentando implementar o método PCA para feature selection a partir das seguintes funções:
#Função que permitirá rankear as features mais importantes em um barhplot
def ranks_PCA (x_train, y_train, features_train, RESULT_PATH='Results'):
    print("\nMétodo PCA")

    pca = PCA(n_components=58)
    pca.fit_transform(x_train)

    imp_array = np.array(pca.components_)
    imp_order = imp_array.argsort()
    ranks = imp_order.argsort()

    # Plot PCA
    imp = pd.Series(pca.components_, index=x_train.columns)
    imp = imp.sort_values()

    imp.plot(kind="barh")
    plt.xlabel("Importance")
    plt.ylabel("Features")
    plt.title("Feature importance using PCA")
    # plt.show()
    plt.savefig(RESULT_PATH + '/ranks_DT.png', bbox_inches='tight')

    return ranks

#Função para predição das features dos dados de teste
def predict_PCA(x_test_sel, k_vetor, y_train):
    model = decomposition.PCA()
    model.fit(k_vetor, y_train)
    y_predict = model.predict(x_test_sel)
    return(y_predict)

#Função que calcula o ranking dos dados de treinamento
ranks4 = frk.ranks_PCA(x_train, y_train, features_train, RESULT_PATH)

Tenho dúvidas se essa implementação é correta para obter features mais importantes. Ao tentar executar este código, eu recebo o seguinte erro:

Traceback (most recent call last):   File "feat_test.py", line 235, in

      'Results/PDBbind2018_F58_Delta_pKd')   File "feat_test.py", line 78, in run_experiment
      ranks4 = frk.ranks_PCA(x_train, y_train, features_train, RESULT_PATH)   File "C:\Users\Patricia\Desktop\VT-58 -
  Cópia\feature-importance\feature_rank_
  ensemble\Scripts\feature_ranks.py", line 121, in ranks_PCA
      imp = pd.Series(pca.components_, index=x_train.columns)   File "C:\Users\Patricia\Desktop\VT-58 -
  Cópia\feature-importance\feature_rank_
  ensemble\env\lib\site-packages\pandas\core\series.py", line 305, in
  init
      data = sanitize_array(data, index, dtype, copy, raise_cast_failure=True)   File "C:\Users\Patricia\Desktop\VT-58 -
  Cópia\feature-importance\feature_rank_
  ensemble\env\lib\site-packages\pandas\core\construction.py", line 482,
  in saniti ze_array
      raise Exception("Data must be 1-dimensional")

Alguém poderia me ajudar?

A: O atributo components_ de sklearn.decomposition.PCA retorna um array com shape igual à  (n_components, n_features). No seu caso (58, x.shape[0]).
Você está usando esse array para tentar criar um objeto do tipo pandas.Series, que aceita somente arrays de 1 dimensão.
O erro está em:
imp = pd.Series(pca.components_, index=x_train.columns)

Se você quer plotar somente um componente, você deve escolher ele ou mudar o número de componentes do PCA para 1.


text:
Q: Shell Script Error Can any one tell what wrong with this script ?. Because I am getting the error like
./timer: line 9: [13: command not found
./timer: line 12: [13: command not found

My script look like
#!/bin/bash

   while :
     do
    HOUR=$(date +%H)
    MINUTE=$(date +%M)
    SECOND=$(date +%S)

        if [$HOUR == 13] && [$MINUTE == 12] && [$SECOND == 1]
     then ./binary

    elif [$HOUR == 18] && [$MINUTE == 30] && [$SECOND == 1]
     then ./binary
    fi

    done

A: put a space between the [ ... ]
Example:
if [$HOUR == 13] && [$MINUTE == 12] && [$SECOND == 1]

Should become
if [ $HOUR == 13 ] && [ $MINUTE == 12 ] && [ $SECOND == 1 ]

A: I think you must use "${VARIABLE}" and respect spaces for square brackets
This would give :
if [ "${HOUR}" == 13 ] && [ "${HOUR}" == 12 ] && [ "${HOUR}" == 1 ]

Hope that helps !

A: the test operators in bash need to have a space by the opening and closing bracket, try
[ $HOUR == 13 ] && [ $MINUTE == 12 ] && [ $SECOND == 1 ]

and
[ $HOUR == 18 ] && [ $MINUTE == 30 ] && [ $SECOND == 1 ]

here is a link that you might find useful
http://tldp.org/LDP/abs/html/testconstructs.html

A: Several things:

*

*You have to put a space after [ and before ].

*It's a good practice to protect your variables using double quotes.

*You have to use the -eq operator to compare numeric values (see Bash conditional operators).

Like so:
if [ "$HOUR" -eq 13] && [ "$MINUTE" -eq 12 ] && [ "$SECOND" -eq 1 ]

elif [ "$HOUR" -eq 18 ] && [ "$MINUTE" -eq 30 ] && [ "$SECOND" -eq 1 ]