Q: BeginInvoke vs Invoke in EventHandler with no code afterwards What exactly is the difference between these two snippets:
A:
MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) => {
    if ((bool)e.NewValue == true)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
        {
            // do something
        }));
    }
};

B:
MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) => {
    if ((bool)e.NewValue == true)
    {
        Dispatcher.Invoke(DispatcherPriority.Loaded, new Action(() =>
        {
            // do something
        }));
    }
};

I thought the only difference between Invoke and BeginInvoke is that the first one waits for the task to be finished while the latter retuns instantly. Since the Dispatcher call is the only thing that happens in the EventHandler, I assumed that using Invoke would have the exact same effect as using BeginInvoke in this case. However I have a working example where this is clearly not the case. Take a look for yourself:
MainWindow.xaml
<Window x:Class="DataGridFocusTest.MainWindow"
        x:Name="MyWindow"
        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:DataGridFocusTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <TextBox DockPanel.Dock="Top"></TextBox>
        <DataGrid x:Name="MyDataGrid" DockPanel.Dock="Top" SelectionUnit="FullRow"
                  ItemsSource="{Binding SomeNumbers, ElementName=MyWindow}"
                  AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Data" Binding="{Binding Data}"
                                    IsReadOnly="True" />
                <DataGridTemplateColumn Header="CheckBox">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </DockPanel>
</Window>

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace DataGridFocusTest
{
    public class MyDataClass
    {
        public string Data { get; set; }
    }

    public partial class MainWindow : Window
    {
        public IList<MyDataClass> SomeNumbers
        {
            get
            {
                Random rnd = new Random();
                List<MyDataClass> list = new List<MyDataClass>();

                for (int i = 0; i < 100; i++)
                {
                    list.Add(new MyDataClass() { Data = rnd.Next(1000).ToString() });
                }

                return list;
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            MyDataGrid.IsKeyboardFocusWithinChanged += (sender, e) =>
            {
                if ((bool)e.NewValue == true)
                {
                    // whenever MyDataGrid gets KeyboardFocus set focus to
                    // the selected item
                    // this has to be delayed to prevent some weird mouse interaction
                    Dispatcher.Invoke(DispatcherPriority.Loaded, new Action(() =>
                    {
                        if (MyDataGrid.IsKeyboardFocusWithin &&
                            MyDataGrid.SelectedItem != null)
                        {
                            MyDataGrid.UpdateLayout();
                            var cellcontent = MyDataGrid.Columns[1].GetCellContent(MyDataGrid.SelectedItem);
                            var cell = cellcontent?.Parent as DataGridCell;
                            if (cell != null)
                            {
                                cell.Focus();
                            }
                        }
                    }));
                }
            };
        }
    }
}

What we have here is a DataGrid which rows include a CheckBox. It implements two specific behaviors:

*

*When the DataGrid gets keyboard focus it will focus it's selected row (which for some reason is not the default behavior).

*You can change the state of a CheckBox with a single click even when the DataGrid is not focused.

This works already. With the assumption at the top of the post, I thought that it would not matter whether I use Invoke or BeginInvoke. If you change the code to BeginInvoke however, for some reason the 2cnd behavior (one-click-checkbox-selection) does not work anymore.
I don't look for a solution (the solution is just using Invoke) but rather want to know why Invoke and BeginInvoke behave so differently in this case.


Q: Cut string in PHP at nth-from-end occurrence of character I have a string which can be written in a number of different ways, it will always follow the same pattern but the length of it can differ.
this/is/the/path/to/my/fileA.php
this/could/also/be/the/path/to/my/fileB.php
another/example/of/a/long/address/which/is/a/path/to/my/fileC.php

What I am trying to do is cut the string so that I am left with
path/to/my/file.php

I have some code which I got from this page and modified it to the following
$max = strlen($full_path);
$n = 0;
for($j=0;$j<$max;$j++){
    if($full_path[$j]=='/'){
        $n++;
        if($n>=3){
            break 1;
        }
    }
}
$path = substr($full_path,$j+1,$max);

Which basically cuts it at the 3rd instance of the '/' character, and gives me what is left. This was fine when I was working in one environment, but when I migrated it to a different server, the path would be longer, and so the cut would give me too long an address. I thought that rather than changing the hard coded integer value for each instance, it would work better if I had it cut the string at the 4th from last instance, as I always want to keep the last 4 'slashes' of information
Many thanks
EDIT - final code solution
$exploded_name = explode('/', $full_path);
$exploded_trimmed = array_slice($exploded_name, -4);
$imploded_name = implode('/', $exploded_trimmed);

A: just use explode with your string and if pattern is always the same then get last element of the array and your work is done
$pizza  = "piece1/piece2/piece3/piece4/piece5/piece6";
$pieces = explode("/", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

Then reverse your array get first four elements of array and combine them using "implode"
to get desired string

A: This function below can work like a substr start from nth occurrence
function substr_after_nth($str, $needle, $key)
{
    $array = explode($needle, $str);
    $temp = array();
    for ($i = $key; $i < count($array); $i++) {
        $temp[] = $array[$i];
    }
    return implode($needle, $temp);
}

Example
$str = "hello-world-how-are-you-doing";

substr after 4th occurrence of "-" to get "you-doing"
call the function above as
echo substr_after_nth($str, "-", 4);

it will result as
you-doing


Q: MySQL table with composite primary key LIMIT 1 is very slow while Limit 2 is fast I have ProductInfo table with following indexes -
Primary:  ProductCode, Model, Added_Date, id
Index: id

The composite primary key are the columns I use in the following query
SELECT * FROM ProductInfo WHERE
ProductCode='45678' AND
Model='PQA-1'  AND
(Added_Date >='2021-08-01 00:00:00' AND Added_Date <='2021-08-14 23:59:59')
ORDER BY Added_Date ASC;

This query works pretty fine
Problem
The following query is fast
select * from ProductInfo WHERE ProductCode="45678" order by id desc limit 1;

Here is the explain

But the following query is very very slow. Please note that query is same but just ProductCode is different
select * from ProductInfo WHERE ProductCode="78342" order by id desc limit 1;

Here is the explain.

However, same query with Limit 2 is fast
select * from ProductInfo WHERE ProductCode="78342" order by id desc limit 2;

Here is the explain

What is the cause? Is my indexing correct? What will be the solution?
Thanks

A: The first query benefits from this index:
PRIMARY KEY(ProductCode, Model, Added_Date)

All the other queries could not fully benefit from either of your indexes.  The Optimizer guessed at one index in one case; the other index in the other.  This would work well for both cases:
INDEX(ProductCode, Id)

One reason for the timing differences is the distribution of data in the table.  Your examples may not show the same timings if you change the 78342 to some other value.
The new index I recommend will make those queries "fast" regardless of the ProductCode searched on.  And "Rows" will say "1" or "2" instead of about "25000".
It sounds like there are about 25K rows with ProductCode = 78342.


Q: docker: SSH access directly into container Up to now we use several linux users:

*

*system_foo@server

*system_bar@server

*...

We want to put the system users into docker container.

*

*linux user system_foo --> container system_foo
The changes inside the servers are not problem, but remote systems use these users to send us data.
We need to make ssh system_foo@server work. The remote systems can't be changed.
I would be very easy if there would be just one system per linux operating system (pass port 22 to the container). But there are several.
How can we change from the old scheme to docker containers and keep the service ssh system_foo@server available without changes at the remote site?
Please leave a comment if you don't understand the question. Thank you.

A: Let's remember however that having ssh support in a container is typically an anti-pattern (unless it's your container only 'concern' but then what would be the point of being able to ssh in. Refer to http://techblog.constantcontact.com/devops/a-tale-of-three-docker-anti-patterns/ for information about that anti-pattern

A: nsenter could work for you. First ssh to the host and then nsenter to the container.
PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)`
nsenter --target $PID --mount --uts --ipc --net --pid

source http://jpetazzo.github.io/2014/06/23/docker-ssh-considered-evil/

A: Judging by the comments, you might be looking for a solution like dockersh. dockersh is used as a login shell, and lets you place every user that logins to your instance into an isolated container.
This probably won't let you use sftp though.
Note that dockersh includes security warnings in their README, which you'll certainly want to review:

WARNING: Whilst this project tries to make users inside containers
  have lowered privileges and drops capabilities to limit users ability
  to escalate their privilege level, it is not certain to be completely
  secure. Notably when Docker adds user namespace support, this can be
  used to further lock down privileges.

A: Some months ago, I helped my like this. It's not nice, but works. But
pub-key auth needs to be used.
Script which gets called via command in .ssh/authorized_keys
#!/usr/bin/python
import os
import sys
import subprocess
cmd=['ssh', 'user@localhost:2222']
if not 'SSH_ORIGINAL_COMMAND' in os.environ:
    cmd.extend(sys.argv[1:])
else:
    cmd.append(os.environ['SSH_ORIGINAL_COMMAND'])
sys.exit(subprocess.call(cmd))

file system_foo@server: .ssh/authorized_keys
command="/home/modwork/bin/ssh-wrapper.py" ssh-rsa AAAAB3NzaC1yc2EAAAAB...

If the remote system does ssh system_foo@server the SSH-Daemon at server executes the comand given in .ssh/authorized_keys. This command does a ssh to a different ssh-daemon.
In the docker container, there needs to run ssh-daemon which listens on port 2222.


Q: external disc works bad on 1 of 3 usb port I have a new pc with 3 usb ports (1 usb-2, and 2 usb-3).
My external disc works nicely on 2 usb ports.
But on one usb-3 ports, it's not working well.
The disk frequently stops (like every 5 minutes), and when it stops I have to wait 2-3 minutes for the disk to wake up.
Software ? Hardware ?

A: I had a call with HP support.
They made me upgrade the bios and reset windows.
Problem was still there.
So I'll send the pc to them and they'll change the usb part from the pc.
I'll see then if problem is solved.


Q: XSS Protection on Yii I need to protect my web application against xss attacks via URL.
what is the best way to do this?
the application is huge, so I can not edit each of the actions, need something general.
Examples:

*

*http://example.com/[anyproductpage.html]?source=alert('Xss')

*http://example.com/catalog/?baseUrl=alert('Xss')&q=1

*http://example.com/catalog/productimagezoom?index=alert('Xss')

A: If you aim to manipulate your actions before handle them you can use beforeAction in your controller/component, with something like this:
protected function beforeAction($action) {

    #check a preg_match on a url sanitization pattern, like "[^-A-Za-z0-9+&@#/%?=~_|!:,.;\(\)]", for instance

    return parent::beforeAction($action);
}

A: This articles shows how you can make your application secure with SQL Injections, XSS Attacks and CSRF.
Hope it helps you.

A: Firstly, you can use regular expressions to validate your inputs, you can generalize your inputs in some regular expresions, something like this:
$num = $_GET["index"];

if (preg_match("^\d{2}$", $num)) {
   //allowed
} else {
   //not allowed
}

Also you can create a white list or black list, if your inputs can be grouped into what is allowed in your application, use a white list, otherwise use a black list. This lists can be sotored in your database or files, something you can easily upgrade without affecting your application. You just have to compare your inputs with that list before proccesing your inputs.
My last recommendation is encoding, you should encode your inputs and outputs, because your data from database can contain malicious code, maybe someone put it by mistake or mischief, always think in all possibilities. For this case, I remember the functions htmlspecialchars and utf8_encode, I think you should the first function, also you can analyze your inputs and build your own encoding function.
I share the following links:

*

*http://php.net/manual/es/function.preg-match.php

*http://php.net/manual/es/function.utf8-encode.php

*http://php.net/manual/es/function.htmlspecialchars.php

*https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
I hope this information helps you.
Good Luck.

A: for all actions in same just add a event handle to onBeginRequest:
    $this->attachEventHandler('onBeginRequest', [$this, 'purifyParams']);

public function purifyParams($event)
{
    $userAgent = $this->getRequest()->getUserAgent();
    $isIE = preg_match('/(msie)[ \/]([\w.]+)/i', $userAgent, $version);
    if (!empty($isIE) && (int) $version[2] < 11) {
        $purifier = new CHtmlPurifier();
        $_GET = array_map(function ($param) use ($purifier) {
            return $purifier->purify($param);
        }, $_GET);
    }
}


Q: Why is the Layout style being applied to all of my JPanels? I am giving myself a crash course on re-learning Java. I am writing a very simple program that simply changes the place of the button when you click it to a random panel. There is no real problem, I pretty much finished the program that I wanted. However, I was wondering why is it that when I apply the Layout Style to the first panel (buttonPanel1), it is automatically applied to every panel?
 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package buttonswitch;

import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.util.*;

/**
 *
 * @author Supreme Lenova
 */
import java.util.Random;
public class ButtonWindow extends JFrame{

    private JPanel buttonPanel1;
    private JPanel buttonPanel2;
    private JPanel buttonPanel3;
    private JPanel buttonPanel4;
    private JButton Button;

    private Border raisedbevel, loweredbevel;
    private Border compound;

    public ButtonWindow(){
        setTitle("Button Game");
        setLocation(600,50);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        GridLayout grid = new GridLayout(2,2);
        setLayout(grid);

        raisedbevel = BorderFactory.createRaisedBevelBorder();
        loweredbevel = BorderFactory.createLoweredBevelBorder();
        compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel);

        buildPanels();

        Button = new JButton("Click!");
        Button.setAlignmentX(Component.CENTER_ALIGNMENT);
        Button.addActionListener(new ButtonListener());

        buttonPanel1.add(Button);
        buttonPanel1.add(Box.createVerticalGlue());

        setSize(300,300);
        setVisible(true);

}
    private void buildPanels(){
        buttonPanel1 = new JPanel();
        buttonPanel2 = new JPanel();
        buttonPanel3 = new JPanel();
        buttonPanel4 = new JPanel();

        buttonPanel1.setLayout(new BoxLayout(buttonPanel1, BoxLayout.PAGE_AXIS));
        buttonPanel1.add(Box.createVerticalGlue());

        buttonPanel1.setBorder(compound);
        buttonPanel2.setBorder(compound);
        buttonPanel3.setBorder(compound);
        buttonPanel4.setBorder(compound);

        this.add(buttonPanel1);
        this.add(buttonPanel2);
        this.add(buttonPanel3);
        this.add(buttonPanel4);
    }

    private class ButtonListener implements ActionListener{

        public void actionPerformed(ActionEvent e){

            generateButton();

        }

        private void generateButton(){
        int last = 5;
        int place = 5;
        Random rand = new Random();
        while(place==last){
        place = rand.nextInt(4)+1;
        }
        last = place;

        switch (place){

            case 1:
                repaint();
                buttonPanel1.add(Button);
                break;
            case 2:
                repaint();
                buttonPanel2.add(Button);
                break;
            case 3:
                repaint();
                buttonPanel3.add(Button);
                break;
            case 4:
                repaint();
                buttonPanel4.add(Button);
                break;

        }
    }

}
}

A: Setting a layout manager to buttonPanel1
buttonPanel1.setLayout(new BoxLayout(buttonPanel1, BoxLayout.PAGE_AXIS));
buttonPanel1.add(Box.createVerticalGlue());

Does not change the layout manager to other panels which use FlowLayout by default.
It does effect the button size. Print out
System.out.println(Button.getSize()); //use button, not Button

Now change the layout manager of buttonPanel1
buttonPanel1.setLayout(new BorderLayout());

and change the code to add the button to the panel :
buttonPanel1.add(Button, BorderLayout.CENTER);

and print again.
The layout manager changes the initial size of the button. The FlowLayout manager of the other 3 panels, does not change the size.


Q: Applications of Generalized Geometry to Theoretical Physics I'm looking for some topics on Generalized Geometry applied to Physics for a master thesis. I took an introductory course last year, and I have a degree in both Mathematics and Physics. I would appreciate any suggestions.
Edit: For a short explanation of what I refer to with Generalized Geometry check the comment by Joseph.

A: Not an answer, only an attempt to clarify.
I'm guessing this is what is meant by "generalized geometry":

"Generalized geometry is based on two premises – the first is to replace the tangent
  bundle $T$ of a manifold $M$ by $T \oplus T^*$, and the second to replace the Lie bracket on
  sections of $T$ by the Courant bracket. The idea then is to use one’s experience of
  differential geometry and by analogy to define and develop the generalized version.
  Depending on the object, this may or may not be a fertile process, but the intriguing
  fact is that, by drawing on the intuition of a mathematician, one may often obtain
  this way a topic which is also of interest to the theoretical physicist."

The quote is from:

Hitchin, Nigel. "Lectures on generalized geometry."
  arXiv:1008.0973 (2010).
  52 pages; based on JCAS Lecture Series in Hong Kong.


Q: How to use calloc to init struct I have struct
struct Person
{
    char name[50];
    int citNo;
    float salary;
};

Now I do this code:
struct Person* p = malloc (sizeof(struct Person));
memset (p,0x00,sizeof(struct Person));

now I want to convert that to calloc (clean code) , how can I do that?
struct Person* p = calloc(sizeof(struct Person) ,1);

Or maybe put 1 it's not correct? what is the right way?

A: calloc() description from man7
 #include <stdlib.h>
 void *calloc(size_t nelem, size_t elsize);

The calloc() function shall allocate unused space for an array of
  nelem elements each of whose size in bytes is elsize.  The space shall
  be initialized to all bits 0. The order and contiguity of storage
  allocated by successive calls to calloc() is unspecified. The pointer
  returned if the allocation ...

I encourage you to keep reading in the link man7_calloc.
now after reading the description above, calling calloc seems easy to me:
in your case we allocating array of one struct person
struct Person* p = NULL;
struct Person* p = calloc(1, sizeof(struct Person));

you must check the return value of calloc(if calloc succedd to allocate, like malloc):
if(p == NULL){
  puts("calloc failed");
  ...
  ...
}


Q: Validation spanning a group of text boxes I'm trying to achieve the following:

Where:

*

*Surname is always required

*NI Number OR Reference Number is required

Is this beyond the scope of the ASP.NET Validation Controls?  The only solution I can think of is writing some bespoke javascript (for client side) and backing that up with some server side code.

A: One thing you can try is to have a CustomValidator(see here) check that both textboxes are not
empty. Then validate both textboxes with a regular expression. The expression should check for either a valid entry OR a blank field.

A: You can create a CustomValidator and handle it there
http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic7


Q: Azure Search on searching articles with images I have 500+ articles with Images, I want to retrieve those articles with images and show the same in in chatbot using Microsoft bot Framework and Azure Search. But, Azure search isn't able to index images. In this scenario where do I need to store these images, how do I map these images to appropriate article?

A: You can either populate the documents in the index via code or use an indexer that can create your documents.  Here is the Indexer data source drop down showing the different data sources available.

You could put the information about the image and a path to the image in any of these data sources and have an indexer pick it up and create your documents within the index.
If you don't want to use a formal database, you could also upload your images into blob storage and decorate each blob with custom metadata.  When creating your index with an indexer, it will find the custom metadata and it can become fields on documents within your index.
There are lots of options, but my advice is to keep your documents within your index as small as possible to control your costs.  That's usually done by having as few a fields as possible and have fields that reference where the stuff is located.  The documents within an index are for discovering where things are located and NOT for storing the actual data.  When you index start occupying lots of space, your cost will go up a LOT.


Q: Is there an in-universe reason that Inklings evolved to be human-like? In Splatoon, Inklings, who evolved from squids to replace humans as the dominant species after rising sea levels caused them to go extinct, look like stylized humans other than their eyes and hair in their main form:

Is there an in-universe explanation as to how Inklings became so similar to humans?
note to reflexive annoying commenters and close voters: this game is very much science fiction. Sci-fi video games are on-topic.


Q: How to make a calculation on the list of HashMaps in Java? I currently have the following sorted set of maps of data:
[
   {"name":"john", "date":2015, "status":"success"},
   {"name":"john", "date":2013, "status":"fail"},
   {"name":"chris", "date":2013, "status":"success"},
   {"name":"john", "date":2012, "status":"fail"},
   {"name":"john", "date":2009, "status":"success"},
   {"name":"chris", "date":2007, "status":"fail"},
   {"name":"john", "date":2005, "status":"fail"},
]

I'm trying to calculate the failure duration for each of the names until 2022. Status for each name is in failure until the next success status.
So, let's say for the name john, it was failed on 2005, next success was 2009, which means 4 years of failure. Then it got failed again on 2012, and again on 2013, which overall until 2015 would be 3 years of failure. Combining them would result in 7 years for john.
With the same logic, for chris we have 6 years of failure.
I'm stuck in the implementation of this. Does anyone have an efficient solution for this problem?

A: Suppose you have a Record class for each entry
public class Record {
    public String name;
    public Integer date;
    public String status;

    public Record(String name, Integer date, String status) {
        this.name = name;
        this.date = date;
        this.status = status;
    }
}

You can use Stream API to achieve your goals
public static Map<String, Integer> useStream(List<Record> records) {
    return records.stream()
        .collect(Collectors.groupingBy(r -> r.name))
        .entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> {
            Integer[] lastFail = new Integer[]{null};
            return e.getValue().stream()
                .sorted(Comparator.comparing(r -> r.date))
                .mapToInt(t -> {
                    if (t.status.equals("fail") && lastFail[0] == null) {
                        lastFail[0] = t.date;
                    } else if (t.status.equals("success") && lastFail[0] != null) {
                        int last = lastFail[0];
                        lastFail[0] = null;
                        return t.date - last;
                    }
                    return 0;
                })
                .sum();
        }));
}

Or you can use better Seq API with smoother code
public static Map<String, Integer> useSeq(List<Record> records) {
    return Seq.of(records)
        .groupBy(r -> r.name)
        .toList()
        .toMap(Map.Entry::getKey, e -> {
            Integer[] lastFail = new Integer[]{null};
            return Seq.of(e.getValue())
                .sortBy(r -> r.date)
                .sumInt(t -> {
                    if (t.status.equals("fail") && lastFail[0] == null) {
                        lastFail[0] = t.date;
                    } else if (t.status.equals("success") && lastFail[0] != null) {
                        int last = lastFail[0];
                        lastFail[0] = null;
                        return t.date - last;
                    }
                    return 0;
                });
        });
}

Both of these methods result as {chris=6, john=7}


Q: A package for formatting Linux terminal excerpts? I know about minted and listings, but either of those are intended for formatting of programming languages excerpts.  Is there a package that would do the same for Linux terminal excerpts?
Such as:
peter@kbpet:~$ echo $(uname -i)
x86_64

The minimal solution would be to automatically embolden the peter@kbpet: to every line and indent the leading line of each block.
The other major convenience sought is math symbols like $ and _ should be automatically interpreted as escaped.

A: What do you think about this suggestion:
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstdefinestyle{Bash}
{language=bash,
keywordstyle=\color{blue},
basicstyle=\ttfamily,
morekeywords={peter@kbpet},
alsoletter={:~$},
morekeywords=[2]{peter@kbpet:},
keywordstyle=[2]{\color{red}},
literate={\$}{{\textcolor{red}{\$}}}1
         {:}{{\textcolor{red}{:}}}1
         {~}{{\textcolor{red}{\textasciitilde}}}1,
}

\begin{document}

\begin{lstlisting}[style=Bash]
peter@kbpet:~$ echo $(uname -i)
x86_64

\end{lstlisting}
\end{document}


Q: How to verify schedules I need to verify if a certain time are between another two. For example:
Today: Thursday, 11:39PM
The store X is open from 00:00AM to 11:59PM on thursdays (in plural, its recorrent). So, a function isOpen returns true.
I have made a workaround for this, writing this on the database (Firebase):
{
  "open" : 7200000,
  "day" : "Thursday",
  "close" : 93540000
}

Where open and close is milliseconds from 01/01/1970
In the function I check if there is a day in the database that matches the current day, after this i need to create a Date from 01/01/1970 with 11:39PM and check if open is smaller and close is bigger than current time.
let open = false;
if (store.schedule) {
    for (sch in store.schedule) {
        if (store.schedule[sch].day == day) {
            open = self.checkHour(store.schedule[sch].open, store.schedule[sch].close);
        }
    }
}
return open;

And checkHour
checkHour = function (open, close) {
    return moment().year(1970).month(0).date(1).isBetween(moment(open), moment(close));
};

PS: I'm using moment.js
Terrible, terrible solution, I know. I'm sure there is a better way.

A: Don't try to manually query your database, let the database do its own querying.
You never explained which database you're using, but most a "datetime" field of some sort you can use. You can then pass a formatted date string in your query and check if it's greater than the open field and less than the close field.
For example, in SQL you would do:
SELECT * FROM stores WHERE {date} >= open and {date} <= close;

In this case {date} would be the formatted date you're passing into the query.
That said, if you already have the store in question, you can simply compare the data you already have in your javascript object.
var store = {
  "open" : 7200000,
  "day" : "Thursday",
  "close" : 93540000
};

var now = Date.now();

if (now >= store.open && now <= store.close) {
  // you are in range
}


Q: One to Many relationship issue in .net core web api I have two tables in my database Student and Course. Using these two tables, I have created a relationship like one student can have multiple courses.
Student table :
Id |    FirstName  | LastName  |    AddressNo | City      | CourseId
----------------------------------------------------------------
1  |  Sandanuwan     Dharmarathna      52      Kurunegala      1

Course table :
Id |   CourseName
--------------------
1  |  English Course

in my ASP.NET Core Web API, I have created two model classes called Student and Course:
public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; } = null!;
    public string LastName { get; set; } = null!;
    public string AddressNo { get; set; } = null!;
    public string City { get; set; } = null!;
    public List<Course> Courses { get; set; }
}

public class Course
{
    public int Id { get; set; }
    public string CourseName { get; set; } = null!;
}

Now I want to get response like this
{
  "data": [
    {
      "id": 0,
      "firstName": "string",
      "lastName": "string",
      "addressNo": "string",
      "city": "string",
      "country": "string",
      "street": "string",
      "grade": "string",
      "className": "string",
      "courses": [
        {
          "id": 0,
          "courseName": "string"
        }
      ]
    }
  ],
  "success": true,
  "message": "string"
}

But after call get function I am getting this response. It's always sending empty array in payload.
{
  "data": [
    {
      "id": 1,
      "firstName": "Sandanuwan",
      "lastName": "Dharmarathna",
      "addressNo": "52",
      "city": "Kurunegala",
      "country": "Sri Lanka",
      "street": "Piduruwella",
      "grade": "10",
      "className": "B",
      "courses": []
    }
  ],
  "success": true,
  "message": "Successfully received all Students details"
}

This is my GET method:
public async Task<ServiceResponse<List<GetStudentDto>>> GetAllStudents()
{
    var response = new ServiceResponse<List<GetStudentDto>>();
    var dbStudents = await _dataContext.Student.ToListAsync();
    response.Data = dbStudents.Select(c => _mapper.Map<GetStudentDto>(c)).ToList();
    response.Message = "Successfully received all Students details";
    return response;
}

GetStudentDto class
public class GetStudentDto
{
        public int Id { get; set; }
        public string FirstName { get; set; } = null!;
        public string LastName { get; set; } = null!;
        public string AddressNo { get; set; } = null!;
        public string City { get; set; } = null!;
        public string Country { get; set; } = null!;
        public string Street { get; set; } = null!;
        public string Grade { get; set; } = null!;
        public string ClassName { get; set; } = null!;
        public List<GetCourseDto> Courses  { get; set; }
}

public class GetCourseDto
{
    public int Id { get; set; }
    public string CourseName { get; set; } = null!;
}

Errors

Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid object name 'CourseStudent'.
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__188_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location ---

Db Context Class
public partial class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> options): base(options)
        {
        }

        public virtual DbSet<Course> Course { get; set; } = null!;
        public virtual DbSet<Student> Student { get; set; } = null!;
    }

enter image description here

A: include courses into student instance
 var dbStudents = await _dataContext.Student
                                     .Include(i=>i.Courses)
                                     .ToListAsync();

and fix Course class
public class Course
{
    public int Id { get; set; }
    public string CourseName { get; set; } = null!;
    public virtual List<Student> Students { get; set; }
}

you have to repeat ef migration to database. New table will be created
public class CourseStudent
{
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }
    public int StudentId { get; set; }
    public virtual Student Student { get; set; }
}


Q: How can I brand my patternlabs installation with new colors, fonts etc? Im trying to figure out how I can change the look of the UI in patternlab. I would like to change the entire UI to something that fits my company brand more.
I know there are some settings that I can change (logo for example) but I can't seem to find more changes. I would like to use our brand font and also change menu colors and so on. Mabey even move the entire menu, at least play around with it a bit.
I changed the logo through the settings config but that is basically what I've found so far in regards of changing the UI.
Everything I've tried so far in using my own styles mostly regard patterns and the actual components rendering. I want to style the patternlab UI including menus, text and colors.


Q: Docker Containers with different Network Interface Problem:
I want to have multiple VPN Servers running in Docker containers each with there own public IP.
With the -p parameter I am able to connect to each one separately but the Public ip that I see is the eth0 interface not the one that I want it to be (eth0:1) so how can I create a new docker0 interface that uses eth0:1 as interface for the traffic?
Best regards and thanks.

A: Docker doesn't uses network outside of it .
For the connection between the host to container from outside the world use port bindings.
Expose the port in Dockerfile when creating docker image
Expose Docker Container to Host :
      Exposing container is very important for the host to identify in which port container runs.
      -p in docker run command used to expose the ports.
      Syntax : docker run -p host_ip:host_port:container_port image_name
       e.g., docker run -itd -p 192.168.134.122:1234:1500 image_name
      This binds port 1500 of the container to port 1234 on 192.168.134.122 of the host machine.
      Use Iptables to view the network process  –  iptables -L -n -t nat
  Now the request send to host_ip (192.168.134.122) and port (1243) is redirect to container with ip (172.17.0.2) and port (1500).


Q: Como usar popover em texto sem usar Href Boa tarde, como eu coloco um popover em um texto sem usar um <a href ... ?
É possível ?
Meu código:

 Suporte Técnico - 1

A: Pelo o que aparenta, você está utilizando o Bootstrap, estão vou dar uma solução em Bootstrap. Nele, existe o componente Popover, que você pode ler melhor sua definição aqui.
Abaixo está um código de como você pode utilizar em um outro elemento, no caso um simples , sem ter que utilizar <a href ...:

$(function () {
  $('[data-toggle="popover"]').popover()
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

   Clique Aqui


Q: Using a custom variable in livecharts I am using the LiveCharts package in a .NET framework 4.7.2 C# form. I am trying to get data from a database into a chart, but have found that LiveCharts isn't very fond of me trying to use my own variables. I have not yet found a way to link these two with eachother.
new StackedColumnSeries
                {
                    Values = new ChartValues<double> {5},
                    StackMode = StackMode.Values,
                    DataLabels = true,
                    Fill = Brushes.DodgerBlue

                },
                new StackedColumnSeries
                {
                    Values = new ChartValues<double> {3},
                    StackMode = StackMode.Values,
                    DataLabels = true,
                    Fill = Brushes.LawnGreen
                },

                new StackedColumnSeries
            {
                Values = new ChartValues<double> {1},
                StackMode = StackMode.Values,
                DataLabels = true,
                Fill = Brushes.DimGray
            },

                new StackedColumnSeries
            {
                Values = new ChartValues<double> {1},
                StackMode = StackMode.Values,
                DataLabels = true,
                Fill = Brushes.IndianRed
            }
            };

I want to change the {5}, {3}, ... into a custom variable, let's say "VarDataSize". Is this possible?
I am pretty new to Visual Studio 2019, so I would appreciate a lot of explanation. If I am missing any necessary information I'll gladly add it.

A: Someone taught me how to do it. I had to add the following below namespace.
static class global
{
    public static int Var1;
    public static int Var2;
    public static int Var3;
    public static int Var4;
}

And then define their values in the same place as InitializeComponent(); is.
global.Var1 = 5;
global.Var2 = 3;
global.Var3 = 1;
global.Var4 = 1;

And then just change the numbers with the correct variable name.
It's fairly easy I suppose, but I din't know it and I hope it might help someone else too.


Q: Permission denied issue while doing CD even after having group permission I'm getting Permission denied while doing a cd into directory  /tct/foxprod_t2b_002/cilin/cust_test/testcases/level1 and user is a member of this group; other users on the group can easily accessing the files but only this user can not. Below is a snipped output of the strace from the user's home dir..
 Prod- > strace csh -c 'cd /tct/foxprod_t2b_002/cilin/cust_test/testcases/level1'
    execve("/bin/csh", ["csh", "-c", "cd /tct/foxprod_t2b_002/cilin/cu"...], [/* 57 vars */]) = 0
    brk(0)                                  = 0xb2a000
    mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f0dd0ef2000
    access("/etc/ld.so.preload", R_OK)      = 0
    open("/etc/ld.so.preload", O_RDONLY)    = 3
    fstat(3, {st_mode=S_IFREG|0644, st_size=26, ...}) = 0
    mmap(NULL, 26, PROT_READ|PROT_WRITE, MAP_PRIVATE, 3, 0) = 0x7f0dd0ef1000
    close(3)                                = 0
    open("/dgagent/lib64/preload.so", O_RDONLY) = 3
    read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0(\25\0\0\0\0\0\0"..., 832) = 832
    fstat(3, {st_mode=S_IFREG|0700, st_size=25895, ...}) = 0
    mmap(NULL, 2115192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f0dd0acf000
    mprotect(0x7f0dd0ad4000, 2093056, PROT_NONE) = 0
    mmap(0x7f0dd0cd3000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x4000) = 0x7f0dd0cd3000
    close(3)                                = 0
    munmap(0x7f0dd0ef1000, 26)              = 0
    open("/grid/common/pkgs/gcc/v4.8.3/lib/tls/x86_64/libtinfo.so.5", O_RDONLY) = -1 ENOENT (No such file or directory)
    open("/grid/common/pkgs/gcc/v4.8.3/lib64/libtinfo.so.5", O_RDONLY) = -1 ENOENT (No such file or directory)
    stat("/grid/common/pkgs/gcc/v4.8.3/lib64", {st_mode=S_IFDIR|0755, st_size=8192, ...}) = 0
    open("/etc/ld.so.cache", O_RDONLY)      = 3

    open("/usr/lib64/gconv/gconv-modules.cache", O_RDONLY) = 3
    fstat(3, {st_mode=S_IFREG|0644, st_size=26060, ...}) = 0
    mmap(NULL, 26060, PROT_READ, MAP_SHARED, 3, 0) = 0x7f0dd0edf000
    close(3)                                = 0
    gettimeofday({1550755896, 639009}, NULL) = 0
    getrusage(RUSAGE_SELF, {ru_utime={0, 0}, ru_stime={0, 1999}, ...}) = 0
    getrusage(RUSAGE_CHILDREN, {ru_utime={0, 0}, ru_stime={0, 0}, ...}) = 0
    open("/dev/null", O_RDONLY)             = 3
    close(3)                                = 0
    getuid()                                = 34400
    getgid()                                = 1001
    geteuid()                               = 34400
    getegid()                               = 1001
    gettimeofday({1550755896, 640019}, NULL) = 0
    dup2(0, 16)                             = 16
    fcntl(16, F_SETFD, FD_CLOEXEC)          = 0
    dup2(1, 17)                             = 17
    fcntl(17, F_SETFD, FD_CLOEXEC)          = 0
    dup2(2, 18)                             = 18
    fcntl(18, F_SETFD, FD_CLOEXEC)          = 0
    dup2(16, 19)                            = 19
    fcntl(19, F_SETFD, FD_CLOEXEC)          = 0
    ioctl(18, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0
    ioctl(17, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0
    ioctl(16, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0
    readlink("/proc/self/fd/16", "/dev/pts/5"..., 4095) = 10
    rt_sigaction(SIGALRM, {0x4439d0, [], SA_RESTORER, 0x7f0dd03156a0}, NULL, 8) = 0
    rt_sigprocmask(SIG_UNBLOCK, [ALRM], NULL, 8) = 0
    getcwd("/home/myuser", 4096)           = 14
    stat("/home/myuser", {st_mode=S_IFDIR|0777, st_size=12288, ...}) = 0
    stat("/home/myuser", {st_mode=S_IFDIR|0777, st_size=12288, ...}) = 0
    uname({sys="Linux", node="sj-myuser", ...}) = 0
    rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER, 0x7f0dd03156a0}, NULL, 8) = 0
    pipe([3, 4])                            = 0
    dup(3)                                  = 5
    dup(5)                                  = 6
    close(5)                                = 0
    close(3)                                = 0
    fcntl(6, F_SETFD, FD_CLOEXEC)           = 0
    dup(4)                                  = 3
    dup(3)                                  = 5
    dup(5)                                  = 7
    close(5)                                = 0
    close(3)                                = 0
    close(4)                                = 0
    fcntl(7, F_SETFD, FD_CLOEXEC)           = 0
    clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f0dd0e969d0) = 5257
    socket(PF_FILE, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3
    connect(3, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = 0
    sendto(3, "\2\0\0\0\v\0\0\0\7\0\0\0passwd\0", 19, MSG_NOSIGNAL, NULL, 0) = 19
    poll([{fd=3, events=POLLIN|POLLERR|POLLHUP}], 1, 5000) = 1 ([{fd=3, revents=POLLIN|POLLHUP}])
    recvmsg(3, {msg_name(0)=NULL, msg_iov(2)=[{"bin/xae", 7}, {"\30m\30\31\377\177\0\0", 8}], msg_controllen=0, msg_flags=MSG_CMSG_CLOEXEC}, MSG_CMSG_CLOEXEC) = 0
    close(3)                                = 0
    socket(PF_FILE, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3
    connect(3, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = 0
    sendto(3, "\2\0\0\0\0\0\0\0\10\0\0\0nanosrc\0", 20, MSG_NOSIGNAL, NULL, 0) = 20
    poll([{fd=3, events=POLLIN|POLLERR|POLLHUP}], 1, 5000) = 1 ([{fd=3, revents=POLLIN|POLLHUP}])
    read(3, "\2\0\0\0\1\0\0\0\10\0\0\0\2\0\0\0\351\\\0\0\222u\0\0\10\0\0\0\16\0\0\0"..., 36) = 36
    read(3, "nanosrc\0x\0Nanosrc\0/home/nanosrc\0"..., 41) = 41
    fcntl(9, F_SETFD, FD_CLOEXEC)           = 0
    clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f0dd0e969d0) = 5290
    gettimeofday({1550755896, 842153}, NULL) = 0
    close(9)                                = 0
    read(8, "2\n", 4096)                    = 2
    --- SIGCHLD (Child exited) @ 0 (0) ---
    rt_sigreturn(0x11)                      = 2
    wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], WNOHANG|WSTOPPED, {ru_utime={0, 999}, ru_stime={0, 0}, ...}) = 5290
    wait4(-1, 0x7fff19181af0, WNOHANG|WSTOPPED, 0x7fff19181a60) = -1 ECHILD (No child processes)
    read(8, "", 4096)                       = 0
    close(8)                                = 0

    lstat("so", 0x7fff19186c20)             = -1 ENOENT (No such file or directory)
    close(0)                                = 0
    close(1)                                = 0
    close(2)                                = 0
    alarm(0)                                = 0
    alarm(0)                                = 0
    close(0)                                = -1 EBADF (Bad file descriptor)
    dup(19)                                 = 0
    fcntl(0, F_SETFD, 0)                    = 0
    close(1)                                = -1 EBADF (Bad file descriptor)
    dup(17)                                 = 1
    fcntl(1, F_SETFD, 0)                    = 0
    close(2)                                = -1 EBADF (Bad file descriptor)
    dup(18)                                 = 2
    fcntl(2, F_SETFD, 0)                    = 0
    dup(18)                                 = 2
    fcntl(2, F_SETFD, 0)                    = 0
    chdir("/tct/foxprod_t2b_002/cilin/cust_test/testcases/level1") = -1 EACCES (Permission denied)
    chdir("/tct/foxprod_t2b_002/cilin/cust_test/testcases/level1") = -1 EACCES (Permission denied)
    open("/usr/share/locale/locale.alias", O_RDONLY) = 3
    fstat(3, {st_mode=S_IFREG|0644, st_size=2512, ...}) = 0
    mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f0dd0ede000
    read(3, "# Locale name alias data base.\n#"..., 4096) = 2512
    read(3, "", 4096)                       = 0
    close(3)                                = 0
    munmap(0x7f0dd0ede000, 4096)            = 0
    open("/usr/share/locale/en_US.UTF-8/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
    open("/usr/share/locale/en_US.utf8/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
    open("/usr/share/locale/en_US/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
    open("/usr/share/locale/en.UTF-8/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
    open("/usr/share/locale/en.utf8/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
    open("/usr/share/locale/en/LC_MESSAGES/libc.mo", O_RDONLY) = -1 ENOENT (No such file or directory)
    write(2, "/tct/foxprod_t2b_002/cilin/cust_"..., 74/tct/foxprod_t2b_002/cilin/cust_test/testcases/level1: Permission denied.
    ) = 74
    lseek(16, 0, SEEK_END)                  = -1 ESPIPE (Illegal seek)
    fstat(0, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 5), ...}) = 0
    close(0)                                = 0
    fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 5), ...}) = 0
    close(1)                                = 0
    fstat(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 5), ...}) = 0
    close(2)                                = 0
    fstat(3, 0x7fff19189d10)                = -1 EBADF (Bad file descriptor)
    fstat(94, 0x7fff19189d10)               = -1 EBADF (Bad file descriptor)
    fstat(95, 0x7fff19189d10)               = -1 EBADF (Bad file descriptor)
    fstat(96, 0x7fff19189d10)               = -1 EBADF (Bad file descriptor)
    fstat(97, 0x7fff19189d10)               = -1 EBADF (Bad file descriptor)
    fstat(98, 0x7fff19189d10)               = -1 EBADF (Bad file descriptor)
    fstat(99, 0x7fff19189d10)               = -1 EBADF (Bad file descriptor)
    fstat(207, 0x7fff19189d10)              = -1 EBADF (Bad file descriptor)
    fstat(208, 0x7fff19189d10)              = -1 EBADF (Bad file descriptor)
    fstat(209, 0x7fff19189d10)              = -1 EBADF (Bad file descriptor)
    fstat(210, 0x7fff19189d10)              = -1 EBADF (Bad file descriptor)

    fstat(255, 0x7fff19189d10)              = -1 EBADF (Bad file descriptor)
    exit_group(1)                           = ?

As being a Linux Admin I have added more than 3 users, all are fine, but this particular user is having a problem.
Groups are maintained by LDAP, so the group in LDAP group for all.


Q: How to improve speed with Stanford NLP Tagger and NLTK Is there any way to use the Standford Tagger in a more performant fashion?
Each call to NLTK's wrapper starts a new java instance per analyzed string which is very very slow especially when a larger foreign language model is used...
http://www.nltk.org/api/nltk.tag.html#module-nltk.tag.stanford

A: Using nltk.tag.stanford.POSTagger.tag_sents() for tagging multiple sentences.
The tag_sents has replaced the old batch_tag function, see https://github.com/nltk/nltk/blob/develop/nltk/tag/stanford.py#L61

DEPRECATED:
Tag the sentences using batch_tag instead of tag, see http://www.nltk.org/_modules/nltk/tag/stanford.html#StanfordTagger.batch_tag

A: Found the solution. It is possible to run the POS Tagger in servlet mode and then connect to it via HTTP. Perfect.
http://nlp.stanford.edu/software/pos-tagger-faq.shtml#d
example
start server in background
nohup java -mx1000m -cp /var/stanford-postagger-full-2014-01-04/stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTaggerServer -model /var/stanford-postagger-full-2014-01-04/models/german-dewac.tagger -port 2020 >& /dev/null &

adjust firewall to limit access to port 2020 from localhost only
iptables -A INPUT -p tcp -s localhost --dport 2020 -j ACCEPT
iptables -A INPUT -p tcp --dport 2020 -j DROP

test it with wget
wget http://localhost:2020/?die welt ist schön

shutdown server
pkill -f stanford

restore iptable settings
iptables -D INPUT -p tcp -s localhost --dport 2020 -j ACCEPT
iptables -D INPUT -p tcp --dport 2020 -j DROP


Q: Return is happening before the loop finishes execution I am using for loop and return is happening before the loop finishes execution. I cant use .Map method because i have some conditions in between and want to break the loop in between.
 const getCompanies = async(searchURL,reqBody) => {
    const html = await rp(baseURL + searchURL);
    businessMap = cheerio('a.business-name', html);
      for(var i=0; i < businessMap.length; i++) {
        linkNew =  baseURL + businessMap[i].attribs.href;
        const innerHtml = await rp(linkNew);
        ..
        ...My Code with conditions here
        .....
        ......
        ......
        values.push( [a,b,c,d,e,f]);

      }
     return values

}

A: I see 2 options here:

*

*You have a break that gets executed where it is says My code with conditions here.

*rp doesn't return a Promise.

As for the second option, here's a quick code to show you that the final line of an async function gets executed only when all awaits are finished:

const delay = (ms) => {
   return new Promise(r => {
      setTimeout(r, ms);
      console.log("delayed", ms);
   });
}
const run = async () => {
   for (var i = 0; i < 3; i++) {
       await delay(1000);
   }
   console.log("finished");
}
run();


Q: How to test for multiple command line arguments (sys.argv I want to test againts multiple command line arguments in a loop
> python Read_xls_files.py group1 group2 group3

No this code tests only for the first one (group1).
hlo = []
for i in range(len(sh.col_values(8))):
   if sh.cell(i, 1).value == sys.argv[1]:
      hlo.append(sh.cell(i, 8).value)

How should I modify this that I can test against one, two or all of these arguments? So, if there is group1 in one sh.cell(i, 1), the list is appended and if there is group1, group2 etc., the hlo is appended.

A: You can iterate over sys.argv[1:], e.g. via something like:
for grp in sys.argv[1:]:
  for i in range(len(sh.col_values(8))):
   if sh.cell(i, 1).value == grp:
      hlo.append(sh.cell(i, 8).value)

A: outputList = [x for x in values if x in sys.argv[1:]]

Substitute the bits that are relevant for your (spreadsheet?) situation.  This is a list comprehension.  You can also investigate the optparse module which has been in the standard library since 2.3.

A: I would recommend taking a look at Python's optparse module. It's a nice helper to parse sys.argv.

A: argparse is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts.

A: I believe this would work, and would avoid iterating over sys.argv:
hlo = []
for i in range(len(sh.col_values(8))):
   if sh.cell(i, 1).value in sys.argv[1:]:
      hlo.append(sh.cell(i, 8).value)

A: # First thing is to get a set of your query strings.
queries = set(argv[1:])
# If using optparse or argparse, queries = set(something_else)
hlo = []
for i in range(len(sh.col_values(8))):
    if sh.cell(i, 1).value in queries:
        hlo.append(sh.cell(i, 8).value)

=== end of answer to question ===
Aside: the OP is using xlrd ... here are a couple of performance hints.
Doesn't matter too much with this simple example, but if you are going to do a lot of coordinate-based accessing of cell values, you can do better than that by using Sheet.cell_value(rowx, colx) instead of Sheet.cell(rowx, colx).value which builds a Cell object on the fly:
queries = set(argv[1:])
hlo = []
for i in range(len(sh.nrows)): # all columns have the same size
    if sh.cell_value(i, 1) in queries:
        hlo.append(sh.cell_value(i, 8))

or you could use a list comprehension along with the Sheet.col_values(colx) method:
hlo = [
    v8
    for v1, v8 in zip(sh.col_values(1), sh.col_values(8))
    if v1 in queries
    ]


Q: flask url_for returns internal server error I am tryin to have a form submit to a python script using flask. the form is in my index.html -
<form action="{{ url_for('/predict') }}" method="POST">

Enter Mileage

    <input type="text" name="mileage">

Enter Year

    <input type="text" name="year">
    <input type="submit" value="Predict">
</form>

Here is my flask page (my_flask.py)-
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=("POST", "GET"))
def predict():
    df = pd.read_csv("carprices.csv")
    X = df[['Mileage','Year']]
    y = df['Sell Price($)']
    X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
    clf = LinearRegression()
    clf.fit(X_train, y_train)

if request.method == 'POST':
    mileage = request.form['mileage']
    year = request.form['year']
    data = [[mileage, year]]
    price = clf.predict(data)
return render_template('prediction.html', prediction = price)

But when I go to my index page I get internal server error because of the
Why would this be happening?
    {{ url_for('/predict') }}

A: Instead of url_for('/predict'), drop the leading slash and use url_for('predict').
url_for(...) takes the method name and not the route name.

A: I was not importing url_for.
from flask import Flask, request, render_template, url_for


Q: Getting error while writing dataframe to Ceph Storage In my organisation I'm currently exploring how we can use Ceph to replace HDFS to run out AI/ML workloads. As part of this initiative we setup a Ceph Cluster and imported it into Kubernetes using Rook.
During my testing with Ceph I was able to access Ceph Storage using S3CMD CLI and also able to read data from Ceph using Spark on Kubernetes. However, I'm getting an error while writing data back to Ceph Storage.
Below is my code and error which I'm getting while writing data back. Hoping someone can help with this.
from pyspark.sql import SparkSession

spark = SparkSession.builder \
        .appName("prateek-pyspark-ceph") \
        .config("spark.kubernetes.driver.master", "k8s://https://xxx:6443") \
        .config("spark.kubernetes.namespace", "jupyter") \
        .config("spark.kubernetes.container.image", "spark-executor-3.0.1") \
        .config("spark.kubernetes.container.image.pullPolicy" ,"Always") \
        .config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \
        .config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \
        .config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \
        .config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \
        .config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \
        .config("spark.hadoop.fs.s3a.access.key", "xxxx") \
        .config("spark.hadoop.fs.s3a.secret.key", "xxxx") \
        .config("spark.hadoop.fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider") \
        .config("spark.hadoop.fs.s3a.endpoint", "{}:{}".format("http://xxxx", "8080")) \
        .config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \
        .config("spark.hadoop.fs.s3a.path.style.access", "true") \
        .config("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") \
        .config("spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version", "2") \
        .config("spark.hadoop.fs.AbstractFileSystem.s3a.impl", "org.apache.hadoop.fs.s3a.S3A") \
        .config("spark.hadoop.fs.s3a.multiobjectdelete.enable", "false") \
        .config("spark.hadoop.fs.s3a.fast.upload","true") \
        .config("spark.eventLog.dir", "s3a://bucket/spark-event-log/") \
        .config("spark.executor.instances", "1") \
        .config("spark.executor.cores", "3") \
        .config("spark.executor.memory", "55g") \
        .config("spark.eventLog.enabled", "false") \
        .getOrCreate()

# Read Source Datasets

musical_data= spark.read.json("s3a://bucket/input-data/Musical_Instruments_data.json")
musical_metadata= spark.read.json("s3a://bucket/input-data/Musical_Instruments_metadata.json")

# Register dataframes as temp tables

musical_metadata.registerTempTable("musical_metadata")
musical_data.registerTempTable("musical_data")

# Top products based on unique user reviews

top_rated = spark.sql("""
select musical_data.asin as product_id,
        count(distinct musical_data.reviewerID) as unique_reviewer_id_count,
        musical_metadata.price as product_price
from musical_data left outer join musical_metadata
on musical_data.asin == musical_metadata.asin
group by product_id, product_price
order by unique_reviewer_id_count desc
limit 10
""")

# Display top 10 products

top_rated.show(truncate=False)

# Save output as csv

top_rated.write.format("csv") \
        .option("header","true") \
        .mode("overwrite") \
        .save("s3a://bucket/output-data/")

# Stop Spark Context to release resources

spark.stop()

Error while writing Dataframe.
Py4JJavaError: An error occurred while calling o740.save.
: org.apache.hadoop.fs.s3a.AWSBadRequestException: PUT 0-byte object  on output-data/_temporary/0/: com.amazonaws.services.s3.model.AmazonS3Exception: null (Service: Amazon S3; Status Code: 400; Error Code: InvalidRequest; Request ID: tx0000000000000000002b3-00604055fa-1ea62-sg; S3 Extended Request ID: 1ea62-sg-sg; Proxy: null), S3 Extended Request ID: 1ea62-sg-sg:InvalidRequest: null (Service: Amazon S3; Status Code: 400; Error Code: InvalidRequest; Request ID: tx0000000000000000002b3-00604055fa-1ea62-sg; S3 Extended Request ID: 1ea62-sg-sg; Proxy: null)
    at org.apache.hadoop.fs.s3a.S3AUtils.translateException(S3AUtils.java:224)
    at org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:111)
    at org.apache.hadoop.fs.s3a.Invoker.lambda$retry$3(Invoker.java:265)
    at org.apache.hadoop.fs.s3a.Invoker.retryUntranslated(Invoker.java:322)
    at org.apache.hadoop.fs.s3a.Invoker.retry(Invoker.java:261)
    at org.apache.hadoop.fs.s3a.Invoker.retry(Invoker.java:236)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.createEmptyObject(S3AFileSystem.java:2786)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.createFakeDirectory(S3AFileSystem.java:2761)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.innerMkdirs(S3AFileSystem.java:2088)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.mkdirs(S3AFileSystem.java:2021)
    at org.apache.hadoop.fs.FileSystem.mkdirs(FileSystem.java:2275)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.setupJob(FileOutputCommitter.java:354)
    at org.apache.spark.internal.io.HadoopMapReduceCommitProtocol.setupJob(HadoopMapReduceCommitProtocol.scala:163)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:168)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:178)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:108)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:106)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:131)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:175)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:213)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:210)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:171)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:122)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:121)
    at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:963)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:100)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:160)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:87)
    at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:764)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:64)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:963)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:415)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:399)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:288)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: null (Service: Amazon S3; Status Code: 400; Error Code: InvalidRequest; Request ID: tx0000000000000000002b3-00604055fa-1ea62-sg; S3 Extended Request ID: 1ea62-sg-sg; Proxy: null), S3 Extended Request ID: 1ea62-sg-sg
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1828)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1412)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1374)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1145)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:802)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:770)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:744)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:704)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:686)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:550)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:530)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5212)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:5158)
    at com.amazonaws.services.s3.AmazonS3Client.access$300(AmazonS3Client.java:398)
    at com.amazonaws.services.s3.AmazonS3Client$PutObjectStrategy.invokeServiceCall(AmazonS3Client.java:6113)
    at com.amazonaws.services.s3.AmazonS3Client.uploadObject(AmazonS3Client.java:1817)
    at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1777)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.putObjectDirect(S3AFileSystem.java:1545)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.lambda$createEmptyObject$13(S3AFileSystem.java:2788)
    at org.apache.hadoop.fs.s3a.Invoker.once(Invoker.java:109)
    ... 44 more

Versions -
Spark 3.0.1
Hadoop 3.2

A: Finally the job worked in both Client and Cluster mode
Cluster Mode via Spark Submit
./spark-submit \
--master k8s://https://xxxx:6443 \
--deploy-mode cluster \
--name prateek-ceph-pyspark \
--conf spark.kubernetes.namespace=jupyter \
--conf spark.executor.instances=1 \
--conf spark.executor.cores=3 \
--conf spark.executor.memory=55g \
--conf spark.kubernetes.container.image=spark-executor-3.0.1 \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
--conf spark.kubernetes.authenticate.executor.serviceAccountName=spark \
--conf spark.kubernetes.container.image.pullPolicy=Always \
--conf spark.kubernetes.container.image.pullSecrets=gcr \
--conf spark.kubernetes.authenticate.submission.caCertFile=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
--conf spark.kubernetes.authenticate.submission.oauthTokenFile=/var/run/secrets/kubernetes.io/serviceaccount/token \
--conf spark.hadoop.fs.s3a.access.key=<ACCESS_KEY> \
--conf spark.hadoop.fs.s3a.secret.key=<SECRET_KEY> \
--conf spark.hadoop.fs.s3a.aws.credentials.provider=org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider \
--conf spark.hadoop.fs.s3a.endpoint=http://xxxx:8080 \
--conf spark.hadoop.fs.s3a.connection.ssl.enabled=false \
--conf spark.hadoop.fs.s3a.path.style.access=true \
--conf spark.eventLog.enabled=false \
s3a://ceph-bucket/scripts/Ceph_PySpark.py

Client Mode in Jupyter Notebook -
Spark Config with AWS Credential Provider - org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider
from pyspark.sql import SparkSession

spark = SparkSession.builder \
        .appName("prateek-pyspark-ceph") \
        .config("spark.kubernetes.driver.master", "k8s://https://xxxx:6443") \
        .config("spark.kubernetes.namespace", "jupyter") \
        .config("spark.kubernetes.container.image", "spark-executor-3.0.1") \
        .config("spark.kubernetes.container.image.pullPolicy" ,"Always") \
        .config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \
        .config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \
        .config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \
        .config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \
        .config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \
        .config("spark.hadoop.fs.s3a.access.key", "xxxxx") \
        .config("spark.hadoop.fs.s3a.secret.key", "xxxxx") \
        .config("spark.hadoop.fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider") \
        .config("spark.hadoop.fs.s3a.endpoint", "{}:{}".format("http://xxxx", "8080")) \
        .config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \
        .config("spark.hadoop.fs.s3a.path.style.access", "true") \
        .config("spark.executor.instances", "2") \
        .config("spark.executor.cores", "6") \
        .config("spark.executor.memory", "55g") \
        .getOrCreate()

Spark Config with AWS Credential Provider - com.amazonaws.auth.EnvironmentVariableCredentialsProvider
from pyspark.sql import SparkSession

spark = SparkSession.builder \
        .appName("prateek-pyspark-ceph") \
        .config("spark.kubernetes.driver.master", "k8s://https://xxxx:6443") \
        .config("spark.kubernetes.namespace", "jupyter") \
        .config("spark.kubernetes.container.image", "spark-executor-3.0.1") \
        .config("spark.kubernetes.container.image.pullPolicy" ,"Always") \
        .config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \
        .config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \
        .config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \
        .config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \
        .config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \
        .config("spark.hadoop.fs.s3a.aws.credentials.provider", "com.amazonaws.auth.EnvironmentVariableCredentialsProvider") \
        .config("spark.hadoop.fs.s3a.endpoint", "{}:{}".format("http://xxxx", "8080")) \
        .config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \
        .config("spark.hadoop.fs.s3a.path.style.access", "true") \
        .config("spark.executor.instances", "2") \
        .config("spark.executor.cores", "6") \
        .config("spark.executor.memory", "55g") \
        .getOrCreate()

To solve the issue in Writing to Ceph in Client Mode, add all properties related to fs.s3a.committer.staging.* mentioned here - https://hadoop.apache.org/docs/current/hadoop-aws/tools/hadoop-aws/committers.html in your core-site.xml file in both Driver and Executor image


Q: Flash not working on Chrome, FF, Safari, but it is working on IE I made the huge mistake of getting a template instead of just doing the development my self.  Now I've narrowed down the issue-  first, I thought it was an issue with the actual flash file.  Now I'm realizing it's every time I change the images in the HTML editor which just makes no logical sense to me.  This is the code for the flash file:

      <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="download.macromedia.com/pub/shockwave/cabs/flash/…; width="940" height="417"></object> <![endif]-->

Again, it works great on IE, but nothing else, which is a twist I haven't seen online.
Appreciate any feedback you can offer.

A: Im sure this answer is here already but i will post a generic code i always use.
Just place the whole block and change related values, swf properties.
     <object id="FlashID" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="950" height="377">
         <param name="movie" value="myMovie.swf">
         <param name="quality" value="high">
         <param name="wmode" value="direct" >
         <param name="swfversion" value="6.0.65.0">

         <param name="expressinstall" value="Scripts/expressInstall.swf">
         <param name="SCALE" value="noborder">

         <object type="application/x-shockwave-flash" data="myMovie.swf" width="950" height="377">

         <param name="quality" value="high">
         <param name="wmode" value="direct" >
         <param name="swfversion" value="6.0.65.0">
         <param name="expressinstall" value="Scripts/expressInstall.swf">
         <param name="SCALE" value="noborder">

Content on this page requires a newer version of Adobe Flash Player.

        </object>

     </object>


Q: Div Alignment when using twitter Favorite animation I saw an example for Twitter Favorite animation and I used in my design for testing and now i have problem with alignment for the icons and I don't know how to fix it? Can anyone explain things to me, please?
Below you will the actual code use and I need all the icon with the text to be in one column some thing similar to twitter icon but very basic one.

/* when a user clicks, toggle the 'is-animating' class */
$(".heart").on('click touchstart', function(){
  $(this).toggleClass('is_animating');
});

/*when the animation is over, remove the class*/
$(".heart").on('animationend', function(){
  $(this).toggleClass('is_animating');
});
.postfooter {
    display: flex;
    justify-content: flex-start;
    color: #b3b3b3;
    margin-top: 30px;
    font-size: 25px;
}

.postfooter .fa {
    margin-left: 40px;
}

.heart {
    cursor: pointer;
    height: 70px;
    width: 70px;
    background-image:url( 'https://abs.twimg.com/a/1446542199/img/t1/web_heart_animation.png');
    background-position: left;
    background-repeat:no-repeat;
    background-size:2900%;
  }

  .heart:hover {
    background-position:right;
  }

  .is_animating {
    animation: heart-burst .8s steps(28) 1;
  }

  @keyframes heart-burst {
    from {background-position:left;}
    to { background-position:right;}
  }
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>test</title>

  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

 2

 30

 16

A: The reason why your elements aren't aligning is because the div element containing your heart animation is a block-level element (versus the i elements with the font-awesome icons, which are inline).
To fix that part, you just have to add display: inline-block to the heart element. The height of your heart element is also 70px, so to align the other elements, you'll also need to add height: 70px and line-height: 70px; to your post-footer.  Finally, to adjust for the fact that the heart element is much wider than the other elements, you can wrap the heart counts in a span and give it a negative margin.

/* when a user clicks, toggle the 'is-animating' class */
$(".heart").on('click touchstart', function(){
  $(this).toggleClass('is_animating');
});

/*when the animation is over, remove the class*/
$(".heart").on('animationend', function(){
  $(this).toggleClass('is_animating');
});
.postfooter {
    display: flex;
    justify-content: flex-start;
    color: #b3b3b3;
    margin-top: 30px;
    font-size: 25px;
    height: 70px;
    line-height: 70px;
}

.postfooter .fa {
    margin-left: 40px;
}

.heart {
    display: inline-block;
    cursor: pointer;
    height: 70px;
    width: 70px;

    background-image:url( 'https://abs.twimg.com/a/1446542199/img/t1/web_heart_animation.png');
    background-position: left;
    background-repeat:no-repeat;
    background-size:2900%;
  }
  .heart-text {
    margin-left: -20px;
  }
  .heart:hover {
    background-position:right;
  }

  .is_animating {
    animation: heart-burst .8s steps(28) 1;
  }

  @keyframes heart-burst {
    from {background-position:left;}
    to { background-position:right;}
  }
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>test</title>

  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

 2

 30

16


Q: SSL connection failed when loading JS SDK I followed the info from this post : here to load the JS SDK into my page.
Here is the page : https://www.tkwk.be/client/babyboom/www/
It works great (SSL connection is valid) until I use the SDK.
The problem is that when I try to use the function setAutoGrow() just before my /head I got an error.

The page at about:blank displayed insecure content from
  http://static.ak.facebook.com/connect/canvas_proxy.php?version=3#behavior=p&method=setSize&params=%7B%22height%22%3A892%2C%22width%22%3A1630%2C%22frame%22%3A%22iframe_canvas%22%7D.

However I did load the JS SDK with https like this :

I would like to understand where I made a mistake.
Thanks in advance for your time.


Q: I can not configure e-mail Jenkins Extension Shortly:
I'm using "E-mail Notification" on my Jenkins, its setuped on my local machine. I can not configure emial notifications.
My configuration:

*

*SMTP server: smtp.gmail.com

*Default user e-mail suffix:

*Use SMTP Authentication: Checked

*User Name: My Gmail mail (i turn off only safe app)

*Password: ****

*Use SSL: Checked

*SMTP Port: 465

Failed to send out e-mail

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)

    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)

    at java.security.cert.CertPathBuilder.build(Unknown Source)

Caused: sun.security.validator.ValidatorException: PKIX path building failed

    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)

    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)

    at sun.security.validator.Validator.validate(Unknown Source)

    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)

    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)

    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)

Caused: javax.net.ssl.SSLHandshakeException

    at sun.security.ssl.Alerts.getSSLException(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)

    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)

    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)

    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)

    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)

    at sun.security.ssl.Handshaker.processLoop(Unknown Source)

    at sun.security.ssl.Handshaker.process_record(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)

    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:507)

    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)

    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)

Caused: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)

    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)

    at javax.mail.Service.connect(Service.java:295)

    at javax.mail.Service.connect(Service.java:176)

    at javax.mail.Service.connect(Service.java:125)

    at javax.mail.Transport.send0(Transport.java:194)

    at javax.mail.Transport.send(Transport.java:124)

    at hudson.tasks.Mailer$DescriptorImpl.doSendTestMail(Mailer.java:613)

    at java.lang.invoke.MethodHandle.invokeWithArguments(Unknown Source)

    at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:396)

    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:408)

    at org.kohsuke.stapler.interceptor.RequirePOST$Processor.invoke(RequirePOST.java:77)

    at org.kohsuke.stapler.PreInvokeInterceptedFunction.invoke(PreInvokeInterceptedFunction.java:26)

    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:212)

    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:145)

    at org.kohsuke.stapler.MetaClass$11.doDispatch(MetaClass.java:535)

    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)

    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:747)

    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:878)

    at org.kohsuke.stapler.MetaClass$4.doDispatch(MetaClass.java:280)

    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)

    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:747)

    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:878)

    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:676)

    at org.kohsuke.stapler.Stapler.service(Stapler.java:238)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)

    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:873)

    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1623)

    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:154)

    at hudson.plugins.locale.LocaleFilter.doFilter(LocaleFilter.java:42)

    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:151)

    at jenkins.telemetry.impl.UserLanguages$AcceptLanguageFilter.doFilter(UserLanguages.java:128)

    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:151)

    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:157)

    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)

    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:99)

    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)

    at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)

    at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)

    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)

    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:135)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)

    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)

    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)

    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)

    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)

    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)

    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:90)

    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)

    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)

    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)

    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)

    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)

    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)

    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)

    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)

    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540)

    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)

    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)

    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)

    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)

    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1701)

    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)

    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345)

    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)

    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)

    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1668)

    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)

    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247)

    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)

    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)

    at org.eclipse.jetty.server.Server.handle(Server.java:502)

    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:370)

    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:267)

    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)

    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)

    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:117)

    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333)

    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310)

    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168)

    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126)

    at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366)

    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)

    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)

    at java.lang.Thread.run(Unknown Source)

I think everythink is ok, email should be send.

A: Go to https:///systemInfo >> javax.net.ssl.trustStore.
This is the truststore where the certificate should be added.
You can open the keystore with keytool or if you prefer a GUI take a look at Keystore Explorer
The default password of the truststore is changeit.


Q: (standard_in) 1: syntax error I am new to bash and linux and can't understand why do i have this error ((standard_in) 1: syntax error) in my code.
#!/bin/bash
file_data=$(<merge.bmp)
counter=0
file_size=$(stat -c%s "merge.bmp")
touch file1.bmp
touch file2.bmp
while [ $counter -lt 10 ]; do
    if [ `echo "$counter % 2" | bc` -eq 0 ]; then
            var=`xxd -p -l1 -s $counter merge.bmp`
            hex_var=$(echo "obase=16; $var" | bc)
    else
            var=`xxd -p -l1 -s $counter merge.bmp`
            hex_var=$(echo "obase=16;$var" | bc)
    fi
    let counter=counter+1
done
echo "DONE!"

A: That's the error coming out of the tool bc you had used for arithmetic evaluation. I suspect the variable assignment, $var leading to echo "obase=16; $var" | bc has a malformed/empty value which bc did not like.
If you are using the bash shell, you could very well use its over arithmetic evaluation using the $((..)) construct as
for (( counter=0; counter<10; counter++ )); do
    if (( counter % 2 == 0 )); then
        var=$(xxd -p -l1 -s "$counter" merge.bmp)
        printf -v hex_var '%x' "$var"
    fi
done

The %x applies the necessary decimal to hex conversion needed. Moreover you are doing the same action in both if and else clause. Also remove the outdated back-ticks syntax for command substitution, rather use $(..).


Q: MySQL query help as attached format I have a MySQL table which is as like this:
# Structure for table "audit"
#
DROP TABLE IF EXISTS `audit`;
CREATE TABLE `audit` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `item` varchar(255) DEFAULT NULL,
  `amount` varchar(255) DEFAULT NULL,
  `myDate` date DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;
#
# Data for table "audit"
#
INSERT INTO `audit` VALUES
    (1,'audit','0','2015-12-23'),
    (2,'fs_delete','4206','2015-12-23'),
    (3,'log_print','27443','2015-12-23'),
    (4,'sys_error','10102','2015-12-23'),
    (5,'sys_info','150','2015-12-23'),
    (6,'sys_proxy','30','2015-12-23'),
    (7,'users','2','2015-12-23'),
    (8,'audit','7','2015-12-22'),
    (9,'fs_delete','4206','2015-12-22'),
    (10,'log_print','27443','2015-12-22'),
    (11,'sys_error','10102','2015-12-22'),
    (12,'sys_info','150','2015-12-22'),
    (13,'sys_proxy','30','2015-12-22'),
    (14,'users','2','2015-12-22');

I would like to have a output like the image below

A: I think you need a query like this:
SELECT `myDate`
    , MAX(CASE WHEN `item` = 'audit' THEN `amount` END) AS `audit`
    , MAX(CASE WHEN `item` = 'fs_delete' THEN `amount` END) AS `fs_delete`
    , MAX(CASE WHEN `item` = 'log_print' THEN `amount` END) AS `log_print`
    , MAX(CASE WHEN `item` = 'sys_error' THEN `amount` END) AS `sys_error`
    , MAX(CASE WHEN `item` = 'sys_info' THEN `amount` END) AS `sys_info`
FROM `audit`
GROUP BY `myDate`;

[SQL Fiddle Demo]


Q: Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null. But app still renders Hi im fairly new to Meteor and react and am working on a customer portal. I have adapted the meteor react tutorial to work how i need it to work and am using Flow Router for routing. Everything currently works as it should except i am still getting this error Uncaught Error: AppMount(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null., no matter what i do.
Here is my code for routing aswell as most of the code for the main homepage:
main.jsx
import AppMount from '/imports/ui/AppMount'
import "./routes"

Meteor.startup(() => {
  render(<AppMount />, document.getElementById('root'))
})

AppMount.jsx
const AppMount = props => {
  return (props.content);
}

export default AppMount

App.jsx
const App = () => {

  const user = useTracker(() => Meteor.user());

  const { tasks, isLoading } = useTracker(() => {
    const noDataAvailable = { tasks: [] };

    if (!Meteor.user()) {
      return (noDataAvailable);
    }
    const handler = Meteor.subscribe('tasks');

    if (!handler.ready()) {
      return ({ ...noDataAvailable, isLoading: true });
    }

    const tasks = TasksCollection.find(
      userFilter,
      {
        sort: { status: 1 },
      }
    ).fetch();

    return ({ tasks });

  });

  return(

        {user ? (
          <Fragment>

              {user.admin && (
                <Fragment>
                  <button className="addUser" onClick={newUser} >
                    Add New User
                  </button>

                  <button className="addTask" onClick={addTask} >
                    Add Task
                  </button>

                </Fragment>
              )}

              <button className="changePass" onClick={changePass} >
                Change Password
              </button>

              <button className="user" onClick={logout} >
                Logout: {user.username}
              </button>

            {isLoading &&
loading..
}

              {tasks.map(task => (
                <Task
                  key={task._id}
                  task={task}
                  onCheckboxClick={toggleChecked}
                  onDeleteClick={deleteTask}
                  advanceStage={advanceStage}
                  revertStage={revertStage}
                />
              ))}

          </Fragment>
        ) : (
            <LoginForm />
          )}

  );
}

export default App

routes.jsx
FlowRouter.route('/', {
  name: 'Home',
  action() {
    mount(AppMount, {
      content: <App />
    })
  }
})

I know this question has been asked before but i believe i have tried every solution to no avail.
Any help is appreciated.

A: props.content need {}
const AppMount = props => {
  return {props.content};
}


Q: CI return just Validation_error and not the entire form page I have a view with both login and register forms on the same page. I would like to return just the error message and not refresh the entire page. How can I do that?
public function signup() {

        $this->form_validation->set_rules('user_name', 'User name', 'min_length[4]|is_unique[ts_user.user_name]|xss_clean');
        $this->form_validation->set_rules('user_twitter_id', 'User Twitter ID', 'is_unique[ts_user.user_twitter_id]|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[ts_user.email]');

        if($this->input->post('submit') == TRUE) {
            if($this->form_validation->run()) {
                $twitterid = $this->input->post('user_twitter_id');
                $username = $this->input->post('user_name');
                $email = $this->input->post('email');
                $password = $this->input->post('password');

                $this->Usermodel->add_user($twitterid, $username, $email, $password);
                echo 'Successful.';
            } else {
                echo validation_errors();
                /*$this->load->view('registration_view');*/
            }
        }
    }

A: Do not use post, use ajax
sample:
var paperData = 'name=' + sourceFileName + '&' + 'file=' + uploadFileName;
 var url = encodeURI('/Paper/Create?' + paperData);
            ajax

            ({

                block: false,

                url: url,

                success: function (r) {

                    if (r.success) {

                                    var html='
';

                                        html = html + r.displayName;

                                        html = html + '	';

                                        html = html + '';

                                        html = html + r.type;

                                        html = html + '	';

                                        html = html + '';

                                        html = html + '修改';

                                        html = html + '┊' ;

                                        html = html + '删除';

                                        html = html + '
';

                                    $('#tbPaperList').append(html);

                    }

                    else {

                        alert(r.message);

                        //$.unblockUI();

                    }

                }

            });