text:
Q: How to change focus in GridView on key navigation QML I'm trying to change focus of an image while pressing keys (left, right, up and down) in GridView. When I press left, right, up or down key, I should change image focus and change the image when focus on that image is true. Otherwise, if focus is not on the image, old image should be seen.
Here is what I have by now:

And here is my code:
import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 1920
    height: 1080
    visible: true
    title: qsTr("Hello World")
    Component.onCompleted: {
        mojgrid.focus = true
    }

    function dobioResponseNapraviModel(response) {
        console.log("dobioResponseNapraviModel", typeof response)

        mojgrid.model=response
    }

    function request(){
        console.log("BOK")

        const xhr=new XMLHttpRequest()
        const method="GET";
        const url="http://api.themoviedb.org/4/list/1";
        xhr.open(method, url, true);
        xhr.setRequestHeader( "Authorization", 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5YjBkOGVlMGQzODdiNjdhYTY0ZjAzZDllODM5MmViMyIsInN1YiI6IjU2MjlmNDBlYzNhMzY4MWI1ZTAwMTkxMyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.UxgW0dUhS62m41KjqEf35RWfpw4ghCbnSmSq4bsB32o');
        xhr.onreadystatechange=function(){
            if(xhr.readyState===XMLHttpRequest.DONE){
                var status=xhr.status;
                if(status===0 || (status>=200 && status<400)){
                    //the request has been completed successfully
//                    console.log(xhr.responseText.results)
                    dobioResponseNapraviModel(JSON.parse(xhr.responseText).results)
               }else{
                    console.log("There has been an error with the request", status, JSON.stringify(xhr.responseText))
                }
            }
        }
        xhr.send();
    }

   /* function request(url, callback) {
        var xhr=new XMLHttpRequest();

        xhr.open("GET", url, true)

        xhr.onreadystatechange = function() {
            if(xhr.readyState===4) {

                callback(xhr.responseText)

            }
        }
        xhr.open("GET", url)
        xhr.setRequestHeader( "Authorization", 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5YjBkOGVlMGQzODdiNjdhYTY0ZjAzZDllODM5MmViMyIsInN1YiI6IjU2MjlmNDBlYzNhMzY4MWI1ZTAwMTkxMyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.UxgW0dUhS62m41KjqEf35RWfpw4ghCbnSmSq4bsB32o');
        xhr.send()

    }*/

    GridView {
        id:mojgrid
        anchors.fill: parent
        cellWidth: 250
        cellHeight: 250
        model:request()
        currentIndex: modelData.id
        keyNavigationEnabled: true
        focus:true

        Keys.onPressed:{
                    if((event.key === Qt.Key_Left) || (event.key===Qt.Key_Right) || (event.key===Qt.Key_Up) || (event.key===Qt.Key_Down)){
                        image.source="http://image.tmdb.org/t/p/w400"+modelData.poster_path
                   }
        }

       /* Keys.onUpPressed: {
           request()
        }*/
      delegate: Rectangle{ id: rect; width: 350; height: 400; color:'gray';
          Image{id:img; width:parent.width; height:parent.height-200
                 //fillMode: Image.PreserveAspectFit
                 //source:"http://image.tmdb.org/t/p/w400" + modelData.backdrop_path
                source:focus?"http://image.tmdb.org/t/p/w400"+modelData.poster_path : "http://image.tmdb.org/t/p/w400" + modelData.backdrop_path

               Rectangle{
                   id:rect2
                   width:parent.width
                   height:text.height
                   anchors.top:img.bottom
                   color:'black'
                 Text{
                       id:text
                       text:modelData.title
                       font.pointSize: 11
                       //anchors.top:image.bottom
                       elide:Text.ElideNone
                       color:'white'
                   }

                }

                MouseArea{
                id:mouse
                anchors.fill:parent

                onClicked: {
                    parent.focus=true
                }
              }

          }

          Rectangle{
              id:rect3
              width:parent.width
              height:200
              anchors.top:rect.bottom
              color:'red'
              z:10

              Text{
                  text:modelData.release_date
                  anchors.left:rect.left
                  anchors.top:rect.bottom
                  color: 'white'

              }
          }

      }
    }
  }

I have Keys.onPressed here with an if condition, but it doesn't work. Can someone help me?

A: I simplified and reformat your code little bit but this code snippet is doing what do you want to do. When key navigation is enabled GridView is handling index update by itself. Actually key navigation is working and when you press keys current index is updated. GridView also handles limits on navigation, when you press down in the last row nothing happens as same as when you press left on the first column. The trick is using currentindex to update image.
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    width: 1920
    height: 1080
    visible: true
    title: qsTr("Hello World")

    function dobioResponseNapraviModel(response) {
        console.log("dobioResponseNapraviModel", typeof response)

        mojgrid.model = response
    }

    GridView {
        id: mojgrid
        anchors.fill: parent
        cellWidth: 250
        cellHeight: 250
        model: request()

        keyNavigationEnabled: true
        focus: true

        delegate: Rectangle {
            id: rect
            width: 350
            height: 400
            color: 'gray'

            property bool isCurrent: mojgrid.currentIndex === index

            Image {
                id: img
                width: parent.width
                height: parent.height - 200

                source: isCurrent ? "http://image.tmdb.org/t/p/w400"
                                + modelData.poster_path : "http://image.tmdb.org/t/p/w400"
                                + modelData.backdrop_path

                Rectangle {
                    id: rect2
                    width: parent.width
                    height: text.height
                    anchors.top: img.bottom
                    color: 'black'
                    Text {
                        id: text
                        text: modelData.title
                        font.pointSize: 11
                        //anchors.top:image.bottom
                        elide: Text.ElideNone
                        color: 'white'
                    }
                }

                MouseArea {
                    id: mouse
                    anchors.fill: parent

                    onClicked: {
                        mojgrid.currentIndex = index
                    }
                }
            }
        }
    }

    function request() {
        console.log("BOK")

        const xhr = new XMLHttpRequest()
        const method = "GET"
        const url = "http://api.themoviedb.org/4/list/1"
        xhr.open(method, url, true)
        xhr.setRequestHeader(
                    "Authorization",
                    'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI5YjBkOGVlMGQzODdiNjdhYTY0ZjAzZDllODM5MmViMyIsInN1YiI6IjU2MjlmNDBlYzNhMzY4MWI1ZTAwMTkxMyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.UxgW0dUhS62m41KjqEf35RWfpw4ghCbnSmSq4bsB32o')
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                var status = xhr.status
                if (status === 0 || (status >= 200 && status < 400)) {
                    dobioResponseNapraviModel(JSON.parse(
                                                  xhr.responseText).results)
                } else {
                    console.log("There has been an error with the request",
                                status, JSON.stringify(xhr.responseText))
                }
            }
        }
        xhr.send()
    }
}


text:
Q: Tcl script breaks out of foreach loop I have a tcl script to log into devices and print SUCCESS. This is the script:
The file: (the first IP is valid, and can be logged into, the next 3 are fake).
192.38.133.145
178.18.34.48
183.24.56.3
145.234.67.145

The script:
#!/bin/expect
package require Expect

set file [open "hosts" r]
set f_data [read $file]
set data [split $f_data "\n"]

foreach host $data {
set timeout 8
    if {$host > 0} {
                ## GETS THE HOST IP##
                set host_ip $host

                ##LOGS INTO THE DEVICE##
                spawn ssh test@$host_ip
                expect {
                        "password:" {
                                puts "SUCCESS"
                        } timeout {
                                puts "Could not connect to host: ${host_ip}"
                                #break
                        }

                }
        send "password\r"
        expect ">"
        send "en\r"
        }
}

If I do not include the break, I get the message could not connect to host, but instead of looping to the next host, it sends "en\r".
when I do include the break, it gives the message that it cannot reach the host (the second IP, which is expected) and the script ends there (it does not process the 3rd IP). How do I cannot seem to get it to process the 3rd and 4th IPs.
I used the method suggested by potrzebie in this thread: TCL: loops How to get out of inner most loop to outside?
and still cannot get it to work

A: break should work. The expect man page has this to say in the documentation for the expect command:

Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way.

I'd write your loop like this:
foreach host $data {
    # very basic data validation: an ipv4 address contains some dots
    if {[string match {*.*.*.*} $host]} {
        spawn ssh test@$host
        expect {
            "password:" {
                puts "SUCCESS"
                send "password\r"
                exp_continue
            }
            timeout {
                puts "Could not connect to host: $host"
                continue
            }
            ">" {
                # I see a prompt. Fall out of this "expect loop"
            }
        }
        send "en\r"
        expect ">"

        # do something to close the connection
        send "exit\r"
        expect eof
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿porque me sale null en la salida de este codigo? son estudiante y tengo este problema no se porque me sale el null despues de cada System.out.println(Jose.getobservarPlaneta()); oy System.out.println(Jose.getagujeroNegro());

A: El problema es que estas imprimiendo el retorno de tus funciones Jose.getobservarPlaneta() y Jose.getagujeroNegro(), como estas no tienen retorno tus impresiones son null.
Para que estos null no te aparezcan solo debes ejecutar las funciones:
Jose.getobservarPlaneta();
Jose.getagujeroNegro();

Con este cambio ya no tendrás esos null.

A: Tu código no devuelve nada entonces estas intentando imprimir un void
podrías cambiar tus métodos a que retornen un String
String getObservarPlaneta(){
  return "TEXTO";
}

o simplemente llamar a la función sin el System.out.println
Por ejemplo:
Jose.getObervarPlaneta();

A: Los métodos de la clase Astronauta (las clases deberían tener nombres que comienzan en mayúscula) no inicializan los valores de los atributos observarPlaneta y agujeroNegro. Así pues, cuando instancias a Jose, esos atributos tienen valor null. Por lo tanto, vas a imprimir null. Tu código hace lo que le dices que haga.

A: Debes poner los setter que te faltan.
Jose.setObservarPlaneta("aquí tu respuesta");
Jose.setAgujeroNegro("aquí tu respuesta");


text:
Q: What does this operator method do? I am working with some classes that were generated by someone else. Below is a section of the class, I have removed most of it because it is not relevant for this question
struct OrderStatus {
    enum Value {
        New             = (char)48,
        PartiallyFilled = (char)49,
        Filled          = (char)50,
        Cancelled       = (char)52,
        Replaced        = (char)53,
        Rejected        = (char)56,
        Expired         = (char)67,
        Undefined       = (char)85,
        NULL_VALUE      = (char)0
    };

private:
    Value m_val;

public:
    explicit OrderStatus(int    v) : m_val(Value(v))   {}
    explicit OrderStatus(size_t v) : m_val(Value(v))   {}
    OrderStatus()                  : m_val(NULL_VALUE) {}
    constexpr OrderStatus(Value v) : m_val(v) {}

    operator Value() const { return m_val; }
};

Two questions:

*

*What does operator Value() do?

*I will be working with an instance of this class and want to do a switch on that instance's m_val but that is private. Is this possible?

A: As pointed out in the comments, the Value() operator is an implicit conversion operator; because of this member, you can just use an instance of the OrderStatus class in order to use its (otherwise inaccessible) m_val member. You would use this as a variable of the enum type OrderStatus::Value.
Here is a short example of using it in a switch:
#include <iostream>
//
// Insert the code from your question here!
//
int main()
{
    OrderStatus q(48);
    switch (q) {
        case OrderStatus::New:
            std::cout << "New";
            break;
        default:
            std::cout << "Something else!";
    }
    std::cout << std::endl;
    return 0;
}


text:
Q: How can I make a weapon shoot using Ursina? I am currently using Ursina Game Engine and am trying to make a basic FPS game. In the game, there is obviously a gun and a bullet.
The system I have for shooting the gun isn't working. First, it isn't moving forward the way I want it, and second, it isn't able to detect collision sufficiently.
I am wondering how I can make the gun shoot a bullet forward properly, and also how I can make it tell me when it hits something.
Here is the code I am using:
def shoot():
    print(globalvar.currentmag, globalvar.total_ammo)
    if globalvar.currentmag > 0:
        bullet = Entity(parent=weapon, model='cube', scale=0.1, color=color.brown, collision = True, collider = 'box')
        gunshot_sfx = Audio('Realistic Gunshot Sound Effect.mp3')
        gunshot_sfx.play()
        bullet.world_parent = scene
        bullet.y = 2
        for i in range(3000):
            bullet.position=bullet.position+bullet.right*0.01
        globalvar.currentmag -= 1
        hit_info = bullet.intersects()
        print(hit_info)

        if hit_info.hit:
            print("bullet hit")
            destroy(bullet, delay=0)
        destroy(bullet, delay=1)

    else:
        reload()

I have tried using the raycast method in Ursina but that did not work.

A: Don't update the bullet's position right after you create it. Instead, use its animate_position() method to let Ursina update it. Then you can check for collisions in the global update() function. Make sure that all involved entities have a collider and that they're accessible globally.
bullet = None
def input(key):
    global bullet
    if key == 'left mouse down':
        bullet = Entity(parent=weapon, model='cube', scale=.1, color=color.black, collider='box')
        bullet.world_parent = scene
        bullet.animate_position(bullet.position+(bullet.forward*500), curve=curve.linear, duration=2)
        destroy(bullet, delay=2)

def update():
    if bullet and bullet.intersects(wall).hit:
        hit_info = bullet.intersects(wall)
        print('hit wall')
        destroy(bullet)

I adapted this example from the demo code in the FirstPersonController class. I'm not sure if there's a way without specifying the other entity when calling bullet.intersects(). I think it should work because the hit_info object has various properties, among them entities but I couldn't get it to work myself.


text:
Q: why is this showing in the app ?Is it a problem with dropdownbutton? The problem was shown only after I added value to show the options in dropdown button.The image showed red screen instead of the app which said something about value should'nt be null
code was
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
  @override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  var _calculation = ["Sum ", "Subtraction", "Division", "Multiplication"];
  var _currentItemselected = "Add";
  @override
  Widget build(BuildContext context) {
return Scaffold(
child: ListView(
          children: <Widget>[
          DropdownButton<String>(
            items: _calculation.map((String dropdownStringItem) {
              return DropdownMenuItem<String>(
            value: dropdownStringItem,
                child: Text(dropdownStringItem),
);
            }).toList(),
            onChanged: (String newValueSelected) {
              setState(() {
                this._currentItemselected = newValueSelected;
});
value:_currentItemselected;
},
},

A: The initial value of Of DropDownButton should be one of the items of list.
For example, add the value of _currentSelectedIndex to the list.
_calculation = ["Add", "Sum ", "Subtraction", "Division", "Multiplication"];


text:
Q: Как импортировать бибилиотеку из GitHub? Как импортировать бибилиотеку не .JAR формата? например из GitHub нужно импортировать вот это , я скачал себе проект, а как импортировать дальше в свой проект?
A: Добавляете в WorkSpace этот проект.
Затем правой кнопкой на ваш проект -> Properties -> Вкладка Android -> Там внизу Library -> Жмёте Add и выбираете проект ActionBar, который до этого в WorkSpace добавили.


text:
Q: Deleting a specific In[ ] / Out[ ] pair I recently found that the CleanSlate package allows you to free memory without restarting the Wolfram kernel. The CleanSlate package includes the ClearInOut, which resets the $Line to 1. However, I wonder if there's a way to clear a specific In/Out pair without deleting every other cell preceding the current one. Is there such a way?

A: Maybe something like this?
a;
Unprotect /@ {In, Out};
In[1] =.; Out[1] =.;
Protect /@ {In, Out};
DownValues /@ {In, Out}

{
  {HoldPattern[In[2]] :> (Unprotect /@ {In, Out}; ),
   HoldPattern[In[3]] :> (In[1] =. ; Out[1] =. ; ),
   HoldPattern[In[4]] :> (Protect /@ {In, Out}; ),
   HoldPattern[In[5]] :> DownValues /@ {In, Out}
  },
  {HoldPattern[Out[2]] :> {{"In"}, {"Out"}},
   HoldPattern[Out[3]] :> Null,
   HoldPattern[Out[4]] :> {{"In"}, {"Out"}}
  }
}

The key part being Unset to only deal with specific Ins and Outs.


text:
Q: Check if input is of type "text/number/email/etc"? I need to check with Javascript (not jQuery) if the given input element is writable by the user using the keyboard.
I'd like to exclude checkboxes, radios, buttons, resets, submits, image and so on.
Is there a simple way to do it without list all the input types?
This is my current code now:
if (element.getAttribute === undefined) {
    return false;
}

var eTag  = element.tagName;
var eType = element.getAttribute('type');
var isTextInput = (eTag === 'INPUT' || eTag === 'TEXTAREA') && ( eType !== null || eType === 'text' || eType === 'password');
var isEnabledInput = element.disabled === false && element.readOnly === false;
var isContentEditable = ( element.contentEditable && element.contentEditable === true );

// stop for enabled text inputs, selects and contentEditable areas
return (isTextInput && isEnabledInput) || eType === 'SELECT' || isContentEditable;

Logically the && ( eType !== null || eType === 'text' || eType === 'password'); is not enough to check them all.

A: Posting this as an answer because fixes the problem, but it's not strictly what I'm asking for.
I'm still waiting for a cleaner solution.
var notTextual = [
    'button',
    'checkbox',
    'hidden',
    'image',
    'radio',
    'reset',
    'submit'
];

if (element.getAttribute === undefined) {
    return false;
}

var eTag  = element.tagName;
var eType = element.getAttribute('type');
var isTextInput = (eTag === 'INPUT' || eTag === 'TEXTAREA') && !notTextual.contains(eType);
var isEnabledInput = element.disabled === false && element.readOnly === false;
var isContentEditable = ( element.contentEditable && element.contentEditable === true );

// stop for enabled text inputs, selects and contentEditable areas
return (isTextInput && isEnabledInput) || eType === 'SELECT' || isContentEditable;

A: If you wanna call a function depending on the type of input, create an array with the wished types of input, another with the types function and do a loop.
function GetInputType(e){ // e = element
   var Types=[
      "text",
      "password"
   ],
   Attr=e.getAttribute("type"),
   Actions=[
      function(){alert("It's text.")},
      function(){alert("It's password.")}
   ],
   Call=function(){alert("Unknown type.")};
   for(var i=0,l=Types.length;i<l;i++){
      !function(i){
         if(Attr==Types[i])
            Call=Actions[i];
         else break
      }(i)
   }
   Call()
}

A: I think you're going to need to write something yourself. You're asking for more specific business logic than you think.

*

*text is text.

*number is text but the input must be 0-9, and decimal.

*password is text-input, black circles or similar shown on screen.

*Radio buttons are certainly keyboard-inputtable. Text won't display, but that's also true for password. Also the input is essentially "yes" or "no," but that's just a restriction on what keyboard inputs do, just like number is a restriction on what keyboard inputs do.

So you want something like...

*

*the keyboard can input at least some of the time...

*and text must display on screen unless it's a password...

*and more input should be accepted than just a "space" or "enter" as in radio button or checkbox

That's not a standard HTML modifier, or standard jQuery, or anything. That's your own business logic.
I know this is a non-answer but I think there's good reason to believe you won't find what you're looking for out-of-the-box somewhere. It depends on your own application's logic, exactly what you mean by "text."


text:
Q: How to insert multiple rows from a python nested dictionary to a sqlite db I read a yaml file and extract values into a python list. I want to dump the values into a sqlite db and the structure of the list is nested. I have attempted various methods of storing the data in my db, as seen below but they don't solve the problem.
When the lists of the format ('a','b','c') I am able to insert into the table without issues. But when I have a key-value pair, I run into issues.
Data structure:
 [   {   'CPU': 2,
    'jobname': 'Job1',
    'memory': '4 GB',
    'problem': 'Prob1',
    'team': '1'},
{   'CPU': 4,
    'jobname': 'Job2',
    'memory': '256 GB',
    'problem': 'Prob3',
    'team': '3'},
{   'CPU': 5,
    'jobname': 'Job3',
    'memory': '8 GB',
    'problem': 'Prob5',
    'team': '1'}]

This is what I tried but it looks their data structure is slightly different: Python : How to insert a dictionary to a sqlite database?
# read data from the config file
def read_yaml(file):
    with open(file, "r") as stream:
        try:
            config = yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            print(exc)
            print("\n")
    return config

    q = read_yaml("queue.yaml")

  # establish connection to sqlite database and save into db
 conn = sqlite3.connect('queues.db')
 c = conn.cursor()

 # create a sqlite3 database to store the dictionary values
 def create_table():
    c.execute("CREATE TABLE IF NOT EXISTS queues(job TEXT, team
       TEXT, problem TEXT, CPU INT, memory TEXT)")

 create_table()

 # insert data into the table
def dynamic_data_entry():
    for item in q:
        c.execute("INSERT INTO queues VALUES (?, ?, ?, ?, ?)", item)
    conn.commit()

dynamic_data_entry()

This is the output error : Traceback (most recent call last):
File "queue_info.py", line 50, in <module>
dynamic_data_entry()
File "queue_info.py", line 47, in dynamic_data_entry
c.execute("INSERT INTO queues VALUES (?, ?, ?, ?, ?)", item)
sqlite3.ProgrammingError: Binding 1 has no name, but you supplied a
 dictionary (which has only names).

A: sqlite3 supports dictionaries using the placeholder syntax :[key] in place of ?.
You can also use executemany instead of for item in q:
c.executemany("INSERT INTO queues (job, team, problem, CPU, memory) VALUES
    (:jobname, :team, :problem, :CPU, :memory);", data)


text:
Q: Adding a listener to hyperlink in ExtJS I simply want to add a hyper link in my application. I tried the following code and the link is appearing in the page. But the on click event is not working. Can anyone please tell me what might be the reason?
xtype:'box',
isFormField: true,
id: "prospectStageLink",
style: "padding: 3px",
autoEl:{
    //html: ' Link To Prospect'
    tag: 'a',
    href: '#',
    cn: 'Link To Prospect'
},
listeners: {
    render: function(c){
        c.on('click', function(e){
            alert('clicked', 'hiii');
        }, c, { stopEvent: true });
    }
}

A: try this :
listeners: {
    render: function(component) {
        component.getEl().on('click', function(e) {
            alert('test');
        });
    }
}

A: I assume you are not running on ExtJS 4, because BoxComponent was removed from it.
Anyways, the simple explanation is probably that BoxComponent does not have a click event. You might want to try using an Element instead, which does have support for the click event.

A: xtype:'box',
isFormField: true,
id: "prospectStageLink",
style: "padding: 3px",
autoEl:{
    //html: ' Link To Prospect'
    tag: 'a',
    href: '',
    onClick: 'nameYouFunction'
}


text:
Q: Setting up Mock repository with Moq I am unit testing controller logic with xUnit and Moq.  I am trying to use a Mock repository object which will enable the test case to pass.  However, in my setup it caused the test to fail because the Mock repository returns null instead of a TweetDay object.
I am testing the TweetsController:
public class TweetsController : ControllerBase
{
    private readonly ITweetDayRepository _tweetDayRepository;

    public TweetsController(ITweetDayRepository tweetDayRepository)
    {
        //Implementation here
    }

    public async Task<IActionResult> GetTweetDay()
    {
            var tweet = await _tweetDayRepository.GetTweetOfTheDayAsync(_systemClock.GetToday);

            if (tweet == null)
            {
                _logger.LogError(LoggingEvents.GetItemNotFound, "An error occurred getting tweet with date: {Date}", _systemClock.GetToday);
                return BadRequest();
            }

            return Ok(tweet);
        }
        catch (Exception ex)
        {
            _logger.LogError(LoggingEvents.GetItemNotFound, ex, "An error occurred getting tweet with date: {Date}", _systemClock.GetToday);
            return BadRequest();
        }
    }
}

Below is my test case:
public class TweetsControllerTests
{
    private Mock<IMemoryCache> _cache;
    private readonly Mock<IMapper> _mapper;
    private readonly Mock<ILogger<TweetsController>> _logger;
    private readonly Mock<ISystemClockService> _systemClock;
    //private readonly ITweetDayRepository _tweetDayRepository;

    public TweetsControllerTests()
    {
        _cache = new Mock<IMemoryCache>();
        _mapper = new Mock<IMapper>();
        _systemClock = new Mock<ISystemClockService>();
        _logger = new Mock<ILogger<TweetsController>>();
    }

    [Fact]
    public async Task GetTweetDay_ReturnsOkResult_WithATweetObject()
    {
        // Arrange
        var mockRepo = new Mock<ITweetDayRepository>();
        mockRepo.Setup(repo => repo.GetTweetOfTheDayAsync(DateTime.Today))
            .ReturnsAsync(GetTestTweet());

        var controller = new TweetsController(mockRepo.Object, _cache.Object, _logger.Object,
                                                 _systemClock.Object, _mapper.Object);

        // Act
        var result = await controller.GetTweetDay();

        // Assert
        var okResult = Assert.IsType<OkResult>(result);
    }

    private TweetDay GetTestTweet()
    {
        var tweet = new TweetDay()
        {
            Bird = new Bird(),
            BirdId = 0,
            CreationDate = new DateTime(2016, 7, 2),
            DisplayDay = new DateTime(2016, 7, 2),
            LastUpdateDate = new DateTime(2016, 7, 2),
            TweetDayId = 0
        };

        return tweet;
    }
}

Under my setup, I expect the Mock repository to return the TweetDay object intialised in
mockRepo.Setup(repo => repo.GetTweetOfTheDayAsync(DateTime.Today))
    .ReturnsAsync(GetTestTweet());

I cannot isolate the exact source of the problem.
Am I setting up the Mock repository properly?  Or is the problem elsewhere?

A: Based on shown setup one of you injected mocked dependencies (I suspect the system clock)
 var tweet = await _tweetDayRepository.GetTweetOfTheDayAsync(_systemClock.GetToday);

is not behaving as expected and causing the hard coded DateTime.Today expectation to not match and thus return null or a default value different to what was used in the matcher.
You can get around this by loosening the expected match in the target mock
mockRepo
.Setup(repo => repo.GetTweetOfTheDayAsync(It.IsAny<DateTime>()))
.ReturnsAsync(GetTestTweet());


text:
Q: Blocking YouTube website using WiFi and/or DSL Router Is it possible to block certain websites e.g. YouTube on all computers without having to configure something on each and every computer. I have access to WiFi router and the DSL router. Is there any setting on either hardware that allows me to do so?
P.S. I've checked the control panel of both devices but wasn't able to find out anything that might allow me to do that, or may be I was looking at wrong places.

A: You can possibly use OpenDNS for this - it allows you to block both categories of website and specific urls. http://www.opendns.com
You would need to do set DHCP on the router to hand out their DNS server addresses to clients, which should discourage "casual" attempts to surf sites you want to block.
If you want something more "hardcore" in terms of enforcement then you'd need to lock down clients so that users couldn't manually edit their own DNS settings. Or possibly block DNS traffic going through the router if its firewall is half decent, except to the OpenDNS servers.
This won't be foolproof, but it sounds like you're using home or SoHo equipment and that doesn't really do "foolproof" at the best of times.

A: 1. Edit the hosts file
You can achieve very basic control by modifying the Hosts file which is part of the Windows operating system. You can edit the hosts file in a text editor such as notepad, and add websites that you want blocked to the file. Open C:\Windows\System32\drivers\etc\hosts (Note: the "hosts" file has no file extension and will not automatically open in a text editor). Go to the end of the file and start a new line. Enter 127.0.0.1, a space, and then a domain name that you want to block (e.g. "facebook.com"). Create another line but this time add www. to the beginning of the domain. The new lines that you created in the hosts file should look like this:
127.0.0.1 facebook.com
127.0.0.1 www.facebook.com
Repeat the steps for any other domains that you want to block and save your hosts file. When your computer tries to find a website that is listed in the hosts file, it will try to get the website from 127.0.0.1 (your own computer) instead of the actual server IP where the website is hosted. This results in a "Server not found" error message when browsing to the blocked domain.
The hosts file acts as a filter on each client computer, so these steps must be performed on every computer that you want to control. This is OK in small networks, but will become more difficult to manage with more computers.
Notes:
Pros:
Very easy to set up
No additional software required
Cons:
It is very hard to maintain a long list of blocked websites.
You have to set up and maintain this list of sites on each computer you want to control.
Tech savvy users could circumvent these blocks and access the websites without too much difficulty.
2. Install a hardware router
While most low end routers don't offer very much control over what comes in and what goes out of the network, some more advanced hardware routers give you the ability to manage your networks internet access and set blocked sites centrally in the router. Sonic Firewall and Watchguard Firebox are two suppliers who offer such hardware routers for small businesses and home users.
Notes:
Pros:
Users cannot bypass the router
You don't need to have another computer up and running all the time
One single point to manage your list of blocked sites that effects all computers
Cons:
More expensive than software solutions
Initial setup may require some reconfiguration of your network
You might have to upgrade the hardware in the future if the amount of workstations on your network grows
3. Set up a proxy server
If you want even more power to monitor and control internet access, then you should consider using a solution designed specifically for the task. Programs such as WinGate Proxy Server (Windows 2000, XP, Vista, 7) or WinProxy(Windows 95, 98, NT, 2000, XP) are two such solutions. Proxy server software is usually installed on a dedicated computer in your home or office network, and the other computers on the network are configured to connect to the Internet through the proxy server. The proxy then handles all internet traffic for the network and is able to log, monitor and filter internet access. For small networks a lower spec computer will be up to the task of hosting a proxy service, but you could also use an existing workstation or server, for example an active directory server, print server or file server.
The typical setup for a proxy server is to have two network interfaces, one facing the local network and one facing the internet router. This makes the server the only gateway to the internet for the client computers which prevents tech savvy users from bypassing the proxy.
Notes:
Pros:
Easy to maintain.
Gives you lots of additional features, such as bandwidth limiting, website caching, real-time monitoring and logging of visited websites.
You can purchase additional licenses if your network grows and you want to connect more users to your network.
Cons:
You have to install additional software on your computer.
Your proxy server must be up and running for the network to have internet access.
4. Use monitoring and filtering software
You can simply use monitoring and filtering software to block the website you don't want, such as Websense or WFilter.
Pros:
All you need is one computer to monitor your network.
Cheaper than hardware solutions.
Cons:
Need port mirroring router or switch.


text:
Q: How does aircrack-ng suite view Clients on networks we are not connected to? I noticed with the tool airodump-ng which is apart of the aircrack-ng suite we can view all networks around us along with Client MAC address's which are connected to these networks.
How can I acheive similar without this tool, I assume some common packages could be used such as tcpdump, nmap, wireshark, etc...

A: try this :
iwlist wlan0 scanning | grep ESSID

the grep will filter out the rubbish and simply display the networks around you.


text:
Q: How can I transfer parameters from one gpflow model to another to gain similar results? Suppose I have a trained model
m = gpflow.models.SVGP(
     likelihood=likelihood, kernel=kernel, inducing_variable=Z, num_data = len(X_train)
)

is it possible to transfer its parameters to another model and achieve similar results? For example
model = gpflow.models.SVGP(kernel=m.kernel,
                           likelihood=m.likelihood,
                           inducing_variable=m.inducing_variable,
                           num_data=m.num_data)

But this example fails since model has poor results. Are there some other parameters, which should be added to the signature, or it is impossible in principle?

A: Yes, the SVGP (as well as VGP) model predictions crucially depend on the q(u) distribution parametrised by model.q_mu and model.q_sqrt. You can transfer all parameters (including those two) using
params = gpflow.utilities.parameter_dict(model)
gpflow.utilities.multiple_assign(model, params)

(see this notebook for more context)


text:
Q: Submit form using VueJs and AJAX in Laravel 5.1 I am trying to submit a form using AJAX and VueJs. But somehow I am failing to achieve that. I always end up getting an empty Illuminate\Http\Request object.
The blade file:

        <generate-admin></generate-admin>

The component:
<template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

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

    </form>
</template>

main.js
import Vue from 'vue';
import GenerateAdmin from './components/GenerateAdmin.vue';

var VueResource = require('vue-resource')
Vue.use(VueResource);

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
Vue.http.options.emulateJSON = true;

new Vue({
    el: 'body',

    components: { GenerateAdmin }
});

gulpfile.js
var elixir = require('laravel-elixir');

require('laravel-elixir-vueify');

elixir(function(mix) {
    mix.browserify('main.js');
});

routes.php
Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function(Request $request) {
    // returns an empty object.
    return response(['results' => $request]);
});

Route::get('/', function () {
    return view('welcome');
});

What I get in return is:
"{"results":{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}}"

When I check the Request Payload section of Network Tab in Chrome. I do see that the form is getting submitted successfully with whatever data I write in the text box above.
Why is this happening ? Kindly guide me where I have made the mistake ?

UPDATE 1:
I was playing trial and error with the code above. And I removed the namespace Illuminate\Http\Request and also removed the argument Request $request from the post Route. And changed the passing parameter to object from string.
Doing so, did the job for me that I was looking for. Why I don't know. I am still looking for someone who can explain this to me.
Why adding the namespace Iluminate\Http\Request in routes.php file didn't work as I was expecting and removing it did the task ?
Can anybody tell me why it didn't worked out earlier ? Any kind of help is highly appreciated.

P.S.: I have started learning VueJs Components recently.

A: As a general practice I follow, any form data which needs to be passed to the laravel controller is passed as json object from vue frontend. Then in laravel controller (route with a closure function in your case) the values from the received json object are retrieved by using $request->get('key').
So in your case the component code could be

    <template>
    <form id="createAdministrator" @submit.prevent="createAdministrator">

           <input type="text"
                  name="username"
                  id="txtUserName"
                  placeholder="Username"
                  autocomplete="off"
                  v-model="username"
           />

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

    </form>
</template>

Then in your routes.php file
<?php
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/admin/create', function () {
    return view('admin.create');
});

Route::post('/admin', function (Request $request) {
    return response(['results' => $request->get('username')]);
});

I guess the Illuminate\Http\Request instance returns a $request - Collection so we need to access the values using Methods available on Collections.
I have tested the above code along with your code for main.js and '/admin/create'.
One more thing - I think if you send serialized form data to the controller, then within the controller it needs to be de-serialized in order to get object or array containing $key=>$value pairs to facilitate fetching required data.

A: All variables ($attributes, $request, $query, etc) on Request and SymfonyRequest classes are protected, since neither class implements __toString, php does its best to give you what it can.
If you need to see each value, you need to call correct getter. Something like:
Route::post('/admin', function(Request $request) {
    return response(['server' => $request->server(), 'form'=>$request->all()]);
});


text:
Q: Vue.js builder produces incorrect paths in index.html The problem is that after building vue app in destination folder there is index.html with incorrect paths to static assets. Links look like
<link href="/static/js/chunk-29e00bf1.49e28fbb.js" rel="prefetch">

which is incorrect, but should be
<link href="static/js/chunk-29e00bf1.49e28fbb.js" rel="prefetch">

And browser look into ///D:/static/js/ instead of D://.../build/dist/static/js .
There is my vue.config.js
module.exports = {
  outputDir: './build/dist/',
  assetsDir: './static', //...

A: Use publicPath property, and set the path to ./ to use relative paths on build.
module.exports = {
    ...
    publicPath: "./"
    ...
}

Read more in the official documentation: publicPath


text:
Q: String replace in FTL with a specific word I need to replace a specific string in a URL in FTL.
Code 1:
<#assign pageUrlWithParams= "https://sample.com/category?filter=low&navParam=Appliances&skrLocale=en_US&t=1"/>
<#if pageUrlWithParams?? && pageUrlWithParams != '' && pageUrlWithParams?contains("skrLocale")>
    <#assign pageUrlWithParams = pageUrlWithParams?replace('skrLocale','')/>
</#if>
${pageUrlWithParams}

Code 2 :
 <#assign pageUrlWithParams= "https://sample.com/category?filter=low&navParam=Appliances&skrLocale=en_FR&t=2"/>
    <#if pageUrlWithParams?? && pageUrlWithParams != '' && pageUrlWithParams?contains("skrLocale")>
        <#assign pageUrlWithParams = pageUrlWithParams?replace('skrLocale','')/>
    </#if>
    ${pageUrlWithParams}

I need to remove "skrLocale=en_US" and "skrLocale=en_FR" from pageUrlWithParams.
Known text is "skrLocale", using this I need to remove "skrLocale=en_US" and "skrLocale=en_FR".
Because of en_US and en_FR, i dont know how to take that that part after equals.
Some suggest an answer please. Thanks in advance

A: Using regular expressions ('r' as 3rd parameter to ?replace) is the key. Note that due to the complexity of URL syntax, we need to handle two edge cases (skrLocale is the first parameter, and skrLocale is the only parameter), which the below function fulfills. However, it doesn't handle %xx escapes in the parameter name (which you might don't care about):
<#function removeSkrLocale url>
  <#return url?replace(r'([&\?])skrLocale=[^&]*&?', '$1', 'r')?remove_ending('?')>
</#function>

${removeSkrLocale(pageUrlWithParams)}

Of course you can do this without #function as well, directly inside the ${}, but it's reusable and more self documenting this way.

A: I would use a Freemarker function (this is a simple version, can be improved)
<#function remove_param_if_value_equals pageUrlWithParams paramName, paramValues >
    <#if pageUrlWithParams?has_content && pageUrlWithParams?contains(paramName)>
        <#list paramValues as paramValue>
            <#local paramNameAndValue = paramName + "=" + paramValue />
            <#local pageUrlWithParams = pageUrlWithParams?replace(paramNameAndValue,'')/>
        </#list>
    </#if>
    <#return pageUrlWithParams />
</#function>

<#assign pageUrlWithParams= "https://sample.com/category?filter=low&navParam=Appliances&skrLocale=en_US&t=1"/>
<#assign pageUrlWithParams = remove_param_if_value_equals(pageUrlWithParams, "skrLocale", ["en_US", "en_FR"]) />
${pageUrlWithParams}

The code that does the business remains isolated and can be altered/improved later on.
(For example there is that double "&" that could be cleaned)

A: I don't know about FTL. But if you need to replace parameter skrLocale in your URL, I think below is good pattern you can use:
(skrLocale(.*?)&)

With (.*?) is called lazy, it match from skrLocale to nearest &. Therefore, with your case, it will match skrLocale=en_US& and skrLocale=en_FR& .


text:
Q: ZooKeeper - command zkCli doesn't connect When I ran the command zkCli, I got the following output:
Connecting to localhost:2181
Welcome to ZooKeeper!
JLine support is enabled
[zk: localhost:2181(CONNECTING) 0] ls /
KeeperErrorCode = ConnectionLoss for /
[zk: localhost:2181(CONNECTING) 1]

I use homebrew install and services start zookeeper,and it successfullly started!
zkServer status shows below
ZooKeeper JMX enabled by default
Using config: /usr/local/etc/zookeeper/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: standalone

echo srvr | nc localhost 2181
echo srvr | nc 127.0.0.1 2181

print
Zookeeper version: 3.5.6-SNAPSHOT--1, built on 02/27/2020 03:01 GMT
Latency min/avg/max: 0/0/0
Received: 1
Sent: 0
Connections: 1
Outstanding: 0
Zxid: 0xe02
Mode: standalone
Node count: 83

zoo.cfg
this file need add something?
homebrew installation path is /usr/local/Cellar/zookeeper/3.5.7/bin
echo prints Zookeeper version: 3.5.6-SNAPSHOT--1 version have problem?

Now I tail zookeeper.log and find out exception
2020-06-08 18:36:36 ClientCnxn [WARN] Session 0x0 for server localhost/0:0:0:0:0:0:0:1:2181, unexpected error, closing socket connection and attempting reconnect
java.lang.NoSuchMethodError: java.nio.ByteBuffer.clear()Ljava/nio/ByteBuffer;
    at org.apache.zookeeper.ClientCnxnSocketNIO.connect(ClientCnxnSocketNIO.java:296)
    at org.apache.zookeeper.ClientCnxn$SendThread.startConnect(ClientCnxn.java:1104)
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1139)
2020-06-08 18:36:36 NIOServerCnxn [WARN] Unable to read additional data from client sessionid 0x0, likely client has closed socket

A: Please make sure, that your Zookeeper instance is up and running before you try to connect to it.
To check status of Zookeeper execute:
zkServer status

Output should be similar to:
Client port found: 2181. Client address: localhost.
Mode: standalone

If it doesn't work, please check:

*

*If there is anything in Zookeeper log file

*Your JAVA_HOME environment variable. You can also run export JAVA_HOME=$(/usr/libexec/java_home) (on macOS) to be sure it is correct.

*That ports are not used: lsof -i :2181, lsof -i :8080 (both ports can be configured in zoo.cfg by changing clientPort and admin.serverPort respectively)


text:
Q: Upgrading phpMyAdmin in XAMPP to latest produces an error I'm trying update phpMyAdmin in XAMPP to the latest version using this guide:
How to upgrade phpMyAdmin in XAMPP to latest?
however, as soon as I open the xampp-control and click on Admin in the MySQL section it produces an error:

Fatal error: Call to undefined function PMA\libraries\PMA_langSet() in C:\xampp\phpMyAdmin\libraries\Config.php on line 1021

I basically did what the guide except that I renamed my old phpMyAdmin folder (located in c:/xampp) to phpMyAdmin_old in order to have something to fall-back to in the event that something went wrong and then I copied the phpMyAdmin folder containing the new version into the same place where the old version - and it sure went wrong as you all can see and now I'm not able to revert back to my old setting even if I rename my old phpMyAdmin folder.
I did remember to save a copy of the config.inc.php as the guide specified and copy that one into the new folder.
I have tried to turn the server on and off several times to no avail.
I suspect, based on the \PMA_langSet(), that the error has something to do with the language settings - which I haven't tampered with.
How to proceed from here?

A: refresh the browser's cache for ie users (CTRL+F5)
If you don't know how to refresh your browser's cache:
How to refresh your browser's cache


text:
Q: Getting Issues with trying to pass params to knockout function from view on click So consider the following:

The important piece is the click: $root.navigateToPageNum.bind($index() + 1), ...
The issue is when I throw a console.log in said function, I get undefined.
    self.navigateToPageNum = function(pageNumber) {
      console.log(pageNumber);
    }

This gives me undefined which I click on the li link element.
The totalPages() is 7, so I do have 7 li links on the page. but clicking on one gives me undefined.
How can I pass the current index to the function?

A: The first parameter of bind is the thisArg so the current page number will be set as the this in your function:
self.navigateToPageNum = function() {
  console.log(this); // will print the page number
}

If you want to keep your signature you need to pass in $index() + 1 as the second parameter to bind:
click: $root.navigateToPageNum.bind($data, $index() + 1)

Note: if you don't care about the this in the navigateToPageNum you can also pass in null as the first argument to bind.


text:
Q: Importing a TXT file to a DataTable so it matches how Excel imports it - C# .NET I have a txt file, and I can import it into Excel with the following settings perfectly:
Type: Delimited
Delimiters: TAB
Text Qualifier: None
I tried loading it into a DataTable by reading the input file into a String[] array, and then splitting that String[] array.
However how do you represent a TAB when splitting a string? Is this even possible?
How can I import my TAB delimited txt file into a DataTable? If it were comma separated I think my code would work, but not a clue how to represent a TAB?...
Any ideas or code samples showing how to do this?
Any help greatly appreciated.
Dan

A: Just use '\t' for a tab.
So something like this would probably work (though I might be mixing up VB.Net and C# syntax right now):
string rows[]; // read in file here
foreach(string row in rows)
{
     string values[] = row.Split('\t');
     foreach(string value in values)
     {
          // do something
     }
 }

A: We are tool using apes. I'm just sayin'

A: I have found the answer to this here:
Efficient function for reading a delimited file into DataTable
Sorry for creating something similar. Should have searched more thoroughly.


text:
Q: seaborn - how to use `multiple` parameter in seaborn.histplot? seaborn.histplot takes a keyword argument called multiple with one of {'layer', 'dodge', 'stack', 'fill'} values. I presume it handles how multiple bars overlap, or when hue is used. but, the examples and documentation doesn't make it clear on when to use what type of multiple. Any information from the community will be helpful!!

A: A picture says more, etc.
from matplotlib import pyplot as plt
import seaborn as sns

penguins = sns.load_dataset("penguins")
fig, axes = plt.subplots(2, 2, figsize=(15, 15))

kws = ["layer", "dodge", "stack", "fill"]
for kw, ax in zip(kws, axes.flat):
    sns.histplot(data=penguins, x="flipper_length_mm", hue="species", multiple=kw, ax=ax)
    ax.set_title(kw)

plt.show()

The docs say "Approach to resolving multiple elements when semantic mapping creates subsets. Only relevant with univariate data." meaning this is only of relevance when categories are plotted within one graph:

*

*layer - overlayed categories (giving rise to ... interesting color combinations)

*dodge - categories side by side (not applicable to pure KDE plots for the obvious reasons)

*stack - stacked categories

*fill - categories add up to 100%.

A: I think the visible examples are pretty good (in comparison to other "documentation" I have seen).
The default for the parameter "multiple" is layer which just the different sub-histograms on top of each other. This is helpfull if you want to compare the form(skewness, variation, location of median/average on x-axis ect.) of each sub-histogram and to compare the forms to each other.
stack piles the bars on top of each other. This would be most usefull if you want to have an idea of the proportion (e.g. which subcategory is more dominantly distributed on which area of the x-axis and a quick look on where there are gaps for which subcategory).
dogde will split the columns next to each other. This is very similar to stack and in my opinion just a variation with the same intent.
If I remember right, fill will fill the whole plot.
This is not as useful in my opinion because the lack of the excact form of each distribution could lead to the user miss some important insights.


text:
Q: Como faço para calcular o perímetro de um triângulo no java? Como faço para calcular o perímetro de um triângulo no java?
Não sei como calcular o perímetro de um triangulo no java, alguém sabe? Já tentei mas não consegui, me ajudem!

A: public class Triangulo {

    private final double lado1;
    private final double lado2;
    private final double lado3;

    public Triangulo(double lado1, double lado2, double lado3) {
        this.lado1 = lado1;
        this.lado2 = lado2;
        this.lado3 = lado3;
    }

    public double getPerimetro() {
        return lado1 + lado2 + lado3;
    }

    @Override
    public String toString() {
        return "Triangulo [lado1=" + lado1 + ", lado2=" + lado2 + ", lado3=" + lado3 + "]";
    }

}


text:
Q: sqlite3_step(stmt) inside a transaction fails with error 5 without my busy-handler being called [sqlite version 3.28.0 (2019-04-16)]
I am using sqlite in a multi-threaded application.
Sqlite threading-mode is configured for multi-threading (compilation flag: SQLITE_THREADSAFE=2).
In accordance to that each thread is using its own database connection.
In addition, since the multiple connections can access the database simultaneously and in order to avoid the 'database is locked' (error 5) I implement a busy-handler callback and assign it to the connection using sqlite3_busy_handler() right after connection creation.
Generally speaking, all is working well, however I did find that in the following scenario my busy-handler is not being called:

*

*Code begins transaction (BEGIN TRANSACTION),

*Code working with sqlite-statement (sqlite3_prepare_v2(), sqlite3_bind_xxx()),

*Eventually when calling sqlite3_step() I receive the 'database is locked' (error 5)  without my busy-handler ever being called.

I know that in sqlite documentation it says:

The presence of a busy handler does not guarantee that it will be invoked when there is lock contention. If SQLite determines that invoking the busy handler could result in a deadlock, it will go ahead and return SQLITE_BUSY

However, my condition is a simple stand-alone application that does not share the database with any other applications. For this reason, I cannot see why would my busy-handler callback not get called.
My question:
Is there a way to configure sqlite to always call my busy-handler callback?

A: ...after consulting with SQLite Forum...
The solution:
Replace the command BEGIN TRANSACTION with BEGIN IMMEDIATE TRANSACTION.
More
In sqlite there are three types of transactions:

*

*Deferred   (the default)

*Immediate,

*Exclusive

If the transaction-type is not explicitly specified in the BEGIN TRANSACTION statement then the default DEFERRED transaction-type is selected.
In the DEFERRED transaction-type sqlite will not try to acquire any locks until it encounters the first command that requires this lock.
So if the transaction contained one READ command and one WRITE command, then sqlite will do:
BEGIN TRANSACTION  //  No locks acquired
    SELECT...      //  Try to acquire READ  lock
    INSERT...      //  Try to acquire WRITE lock

In multi-threading environment, if the above transaction will be executed simultaniously by two (or more) different threads then a deadlock could occur:

*

*Thread-A acquires READ lock,

*Thread-B acquires READ lock,

*Thread-A tries to acquire a WRITE lock, which can be acquired only once all READ and WRITE locks are released,

*Thread-B tries to acquire a WRITE lock...

This condition is a deadlock, and as sqlite documentation explains: if a potential deadlock is identified then the busy-handler will not get called as it cannot resolve this condition.
The above described how DEFERRED transaction work.
In both other cases - IMMEDIATE and EXCLUSIVE - the WRITE lock is acquired right in the beginning of the transaction, thus no risk of deadlocks:
BEGIN IMMEDIATE TRANSACTION  //  Try to acquire the WRITE lock
    SELECT...                //  ...no locks activity...
    INSERT...                //  ...no locks activity...

Since my code is using sqlite in Multi-Thread threading mode I had to replace my BEGIN TRANSACTION command with BEGIN IMMEDIATE TRANSACTION.
This solved the problem.


text:
Q: Azure DevOps Extension - how to run? I created a hello world Azure extension.  I followed Microsoft's directions from this link https://learn.microsoft.com/en-us/azure/devops/extend/get-started/node?view=azure-devops.  Instead of showing someone's name I just changed it to hello world in the Html.  Then, I loaded it to the marketplace and then installed it into my organization.  At this point, I need to get the hello world to pop up based on clicking the save button in Azure DevOps on a ticket.  But, the Microsoft directions don't really tell you have to run the extension.  It just tells you how to build it and get it installed in your organization.  Once its installed, how would I get it to run based on a button click?

A: In the vss-extension.json file, we can find the categories is Azure Repos, so you will find your extension in the azure repos page.
You can refer the doc Required attributes to help you know more about this.


text:
Q: Jenkins pipeline Parellel steps needs to run based on the previous step This is the Jenkisnfile script currently i am using to run my pipeline for the NodeJS applications. it's working well and suited to my previous pipeline process.
Now I Need to change a little bit in my script for the New Project Requirement.
In the "Step B" if the application failed to start with the NPM Start command, "Step C" (build) does not need to trigger the Job.
Now with this pipeline script approach, "Step C" (build) is always running whether the application failed to start or successfully run because of the parallel block.
pipeline {
agent any
stages {
    stage('need to run parallelly'){
        steps{
            script{
                parallel(
                    a:{
                        dir('file path'){
                            bat """
                            npm install
                            """
                        }
                    },
                    b:{
                        dir('file path'){
                            bat """
                            npm start
                            """
                        }
                    },
                    "build":{
                        build job: 'JenkinsTest'
                    },
                )
            }
        }
    }
}

A: There are 2 ways:
1/ Using global boolean parameter and sleep command. I mean, estimate the time ur Stage B run the "NPM Command" finished, sleep stage C until u get NPM Command result, for eg:
    boolean isFail = false
Stage B:

      if (NPM_Command.isFail()) isFail = true
    Stage C:
      Sleep(60) //eg 1 min is enough for run stage B
      if(isFail)
        // do your work

2/ As ur comment, ur problem is Stage C cant be reach if stage B failed, try this solution


text:
Q: Why does Ruby Builder::XmlMarkup add inspect tag to xml? I'm trying out Builder::XMLMarkup to build some xml and it keeps adding an empty  element to my xml.
Why does it do this and how do I stop it?
xml = Builder::XmlMarkup.new
=> <inspect/>

A: If you still want to see the output:
xml = Builder::XmlMarkup.new; xml.target!

A: Builder implements a version of method_missing that adds tags given by the name of the method call.
Assuming you are playing in irb (or rails' console), irb's default behaviour when you evaluate an expression (such as Builder::XmlMarkup.new) is to call inspect on it, in order to generate a string to show to you. In the case of builder, inspect isn't the usual ruby inspect method - it falls through to method_missing and adds the tag.
This will only happen when playing with ruby interactively. You can do stuff like
xml = Builder::XmlMarkup.new; false

Here the result of the expression is false so irb calls inspect on that and leaves your builder object alone.
It can be awkward to keep doing this continually. If you do
xml = Builder::XmlMarkup.new; false
def xml.inspect; target!; end

then xml will still be a builder object that display its content when inspected by irb. You won't be able to create tags called inspect (other than by using tag!) but that is usually a minor inconvenience.


text:
Q: List items partially overlapping each other most of the times On tap handler of a panel I am creating a list(which uses itemTpl), then populating its store with relevant items and then setting it to the container. When this list is shown first item is shown fully and rest all other items below it, overlap each other. This happens 90% of the time not always and if I resize browser or change orientation of device overlapping disappears and all items look proper.
Here is my store:
var listStore = Ext.create('Ext.data.Store', {
    fields: ['id','image','name','description']
});

Here is how I am populating the store:
var json = Ext.decode(response.responseText);
var arr = json.categories;
for(var x = 0; x < arr.length; x++) {
    if(arr[x].id == self.parent.cid){
        var itemsArr = arr[x].items;
        var myitems = [];
        for(var y = 0; y < itemsArr.length; y++) {
            myitems.push({"id":itemsArr[y].id, "image":itemsArr[y].image, "name":itemsArr[y].name, "description":itemsArr[y].description});
        }
        listStore.add(myitems);
    }
}

Here is how I am creating the list:
var itemsList = {
    xtype: 'list',
    itemTpl : self.parent.tp,
    store : listStore,
    flex : 1,
    id : 'ilid',
    layout : 'fit',
    templateId : 'detailsTemplate_'+self.parent.cid,
    detailsView : 'myshop.view.'+self.parent.ctype+'Details',
    direction: 'vertical',
    listeners: {
      itemtap: function (list, index, element, record)
      {
            var popup = Ext.create(list.detailsView, {
                    rec : record.getData(),
                    tid : list.templateId
            });
            Ext.Viewport.add(popup);
            popup.show('pop');
      }
    }
};

Here is template:
<tpl for=".">

{name}

</tpl>

Here is how it looks like:

Please help!
EDIT!!!
Here is Template:
<tpl for=".">

{name}

</tpl>

and here is related CSS:
.productBox
    {
        border:1px solid #9a9a9a;
    }
.productTitle
    {
        border-bottom:1px solid #9a9a9a;
        padding:5px 10px 0px 10px;
        background-color:#ccc;
        font-weight:bold;
        font-size: 80%;
        height:30px;
    }
.productBody
    {
        padding:10px;
        background-color: white;
    }
.productImage
    {
        margin-left: auto;
        margin-right: auto;
        display: block;
    }
.tp_5 .productBody, .st_5 {
        background-color : white;
    }

Edit
While testing various thing like using flex, providing margins, doing refresh etc I realized that this overlap happens only when the list is loaded for the first time. When I go back to main page and remove it from container
hccontainer.remove(Ext.getCmp('ilid'), true);

and then again create and put it in container onTap event, it renders fine.
Also overlapping happens only second item onwards, first item is always shown fully.

A: This seems to be an open issue with Sencha:
http://www.sencha.com/forum/showthread.php?249938-List-Items-with-height-gt-47px-not-rendered-correctly.
The workaround which worked in my case was to do deferred refresh of list like this:
var l = Ext.getCmp('ilid');
Ext.defer(function(){
  l.refresh();
  console.log("Refreshed");
}, 100, l);

Hoping to see TOUCH-3781 fixed very soon.

A: I found cleaner workaround for this issue by providing height to template div which holds image.
    .productBody
    {
        padding:10px;
        background-color: white;
        height : 240px;
    }

Looks like overlapping was happening because there was no default CSS height for template.

A: Using 'div' in your template in Sencha Touch 2.2.1 brings overlap for me. My workaround has been to convert the 'div' to an html table, so your template would become:

{name}


text:
Q: How to test for sequences that are not string-like using Python 3's standard library For some time, Python has had Abstract Base Classes (proposed orignally in PEP 3119) that, especially for container types, make it easier to write code that generalizes across custom types. For example,
from collections.abc import Sequence, Set

if isinstance(x, Sequence):
    # Handle lists, tuples, or custom objects that behave like lists
elif isinstance(x, Set):
    # Handle anything that behaves like a set

One of the 'gotchas' that's tripped me up a few times is that str, bytes, and bytearray are all considered Sequences, in addition to more obviously list-like objects:
from collections.abc import ByteString, Sequence

s = 'hello'
b = b'hello'
ba = bytearray(b'hello')
lst = [0, 1, 2]
t = (0, 1, 2)

islistlike = lambda x: isinstance(x, Sequence)

list(map(islistlike, [s, b, ba, lst, t])) # -> [True, True, True, True, True]

This certainly makes sense: usually these three types behave just like lists or tuples of characters (or bytes). However, it seems like a pretty common use case to ask, is this object x both list-like and not string-like? The fix is straightforward:
islistlike = lambda x: isinstance(x, Sequence) and not isinstance(x, (str, ByteString))

list(map(islistlike, [s, b, ba, lst, t])) # -> [False, False, False, True, True]

But this seems like it would be a common enough pattern that I wonder if I'm missing something in the standard library.

*

*Is there any abc in Python's standard library such that islistlike = lambda x: isinstance(x, abc) will behave like the last example above?

*Is there any design discussion around Sequence vs string-like containers somewhere? (I haven't found anything related to this in the standard library documentation or PEP 3119.)

A: No, there is nothing in the standard library to easily distinguish between str and bytes-like sequences vs other sequence types.  If this is common in your code-base then you may want to roll your own.


text:
Q: 2 sided winform Tree - exist? I'm looking for a 2 sided winform Tree control. something like what you see in the math books. meaning that the tree can go both right and left in the control.
Something like http://www.math.bas.bg/~nkirov/2010/NETB201/slides/ch06/pic3.jpg
Thanks
Avi

A: You can possibly create a control for yourself deriving from the treeview and doing all the styling in the derived control. But I am sure it will be tedious thing. If you need to just show some data, in that case you can think of using SVG (its an XML inside) so that you can change data as you wish. Otherwise, think of WPF.


text:
Q: Display Instagram captions in an iframe Is there a way to display Instagram captions in an iframe?
The reason I am not using Instagram embed option is because I need to change dynamically the link of the popup which carries the frame.
<iframe class="popupInst" src="http://instagram.com/p/qbq6fIJMVZ/embed" frameborder="0"></iframe>

A: Add /captioned/ to the end of your embed URL; like

https://www.instagram.com/p/{shortcode}/embed/captioned/

A: You can use this tool to generate iframe instagram embed: http://www.gramfeed.com/instagram/embed#https://www.instagram.com/p/8_kRtJBsBq/
You can select size and caption option, which will automatically adjust the height and generate embed code.


text:
Q: How to automatically assign a new number as a key in the dictionary whenever the user wants to add an item? For example, I have an empty dictionary called a shopping list. and it shall store keys such as #"1,2,3,4..." and the value should be a list that store the name and price of item. For some #reason I can only have 1 key in the shopping list only...
The code is below:
#Convenience store inventory of products with code number, item name, price and stock
 items = { 0:['black tea',500,20], 1:['red tea',500,1], 2:['milk
 tea',500,0]}
 shopping_list = {}

 query = input("Enter the code number of the item you want to get: ")
 query = int(query)
 for i in items:
     if query == i:
          item = i
          print(items[item][0], "will cost you", "{:.2f}".format(items[item][1]/100),"dollars")

 #Temporary shopping list shall store item code, name and price from original list of product
 n=0
 buy_more = input("Do you wish to choose some more items? (Y or N) ")
 while buy_more.isdigit() and buy_more not in "Yy" and buy_more not in "Nn":
       print("Please enter (Y or N) only. ")
       buy_more = input("Do you wish to choose some more items? (Y or N) ")

       #loopback and let users to buy an additional item
       while buy_more in "Yy":
            shopping_list[n] = [items[item][0],items[item][1]]
            print("Nice! Please choose one more item.")
            buy_more = input("Do you wish to choose some more items? (Y or N) ")

       #Continue to the transaction process
       if buy_more in "Nn":
            print("Continue to transaction process. ")
            break
shopping_list[n] = [items[item][0],items[item][1]]
print(shopping_list).   `

A: I optimised your code a bit, maybe it will help, here in the code since you asking for the item code as input I'm not incrementing it:
items = { 0:['black tea',500,20], 1:['red tea',500,1], 2:['milk tea',500,0]}
shopping_list = {}

#Temporary shopping list shall store item code, name and price from original list of product
buy_more='y'
while buy_more:
    if buy_more not in 'YyNn':
        print("Please enter (Y or N) only. ")
        buy_more = input("Do you wish to choose some more items? (Y or N) ")

   #loopback and let users to buy an additional item
    while buy_more in "Yy":
        query = int(input("Enter the code number of the item you want to get: "))
        print(items[query][0], "will cost you", "{:.2f}".format(items[query][1]/100),"dollars")
        shopping_list[query] = [items[query][0],items[query][1]]
        print("Nice! Please choose one more item.")
        buy_more = input("Do you wish to choose some more items? (Y or N) ")

        #Continue to the transaction process
    if buy_more in "Nn":
        print("Continue to transaction process. ")
        break

print(shopping_list)


text:
Q: Why can switch only compare to const values? I'm just curious: Take a switch-statement like:
switch(myVar)
{
case(label):
    ...
    break;
}

Why must label be const?

A: Andy Prowl has provided the relevant paragraph from the standard, here's a possible reason why you'd want it like that.
Consider switch (c) { case a: ...; break; case b: ...; break; }. What would you expect to happen if a==b and b==c?
If you write this in terms of if ...; if ... or if ...; else if ..., the semantics are clear. In the case of switch, not so much. Sure, you could define it to behave one way or the other, but imho it would result in code whose behaviour isn't immediately clear, and that's a bad thing in general.

A: If label is not constant it might lead to ambiguity perhaps,
int a = 1, b = 6;

switch(myVar)
{

case a+1;
//etc
break;

case 2;
//etc
break;

}

A: The whole idea behind a switch in C is that the compiler can "prepare" where what myVar value goes. Yes, it may still choose to use a if-else-if-else type chain of operations, but given a particular value of myVar, the outcome should be the same every time. Of course, if the expression in label is not a constant, then it can't determine where each value goes at compile-time.
If that's not what you want, then you need to do something else in your code - tables or a lot of if-statements would be the most obvious solutions.

A: Any constant expression can be used. Per Paragraph 6.4.2 of the C++11 Standard:

The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type. Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:
case constant-expression :
where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the
switch condition. No two of the case constants in the same switch shall have the same value after conversion
to the promoted type of the switch condition.


text:
Q: Why was Peter's "Peter Tingle" not working at the start of the events of "Far From Home"? At the start of Spider-Man: Far From Home May throws a banana at Peter which he fails to notice coming which hits him. She then states that his "Peter Tingle", Spidey sense, was not working.
This continues to be a theme through the film until the final battle in London. I don't remember much of an explanation given for why it wasn't working and why it all of a sudden started to work again. He does have a brief conversation with Happy but I believe that just amounts to him saying "yeah it works again".
So, why was his "Peter Tingle" not working and how did it start working again?

A: After thinking this through a bit I think this is a combination of two things, Peter not being able to move on from post Endgame and Tony's death and the fact that he had given up on super hero life to a point.
He needed to move on
This is probably the main reasoning behind why it wasn't working well. Throughout the film Peter clearly has some issues with how things went down in Infinity War/Endgame and is struggling to cope with them. The main thing is that he is in mourning for Tony and this impacts him quite a lot during the film's events. It is only after talking to Happy and getting those feelings out in the open with someone who had equal, if not greater, feelings for Tony is he able to move on.
At the end of this conversation with Happy Peter feels like his "Peter Tingle" is going to work again. He is coping with Tony's death better and he also appears to believe in himself again which is a massive factor.
He needed to believe again
For the most part of the film Peter is just trying to be a normal kid again, he's trying to distance himself from the super hero lifestyle. He's given up on himself and doesn't want to be a part of it anymore. He goes so far as to ghost and refuse "Fury" for quite a while until he is given no choice.
After the conversation with Happy and that he realises what a threat Mysterio is he decides he needs to do something about it. He jumps back into the super hero lifestyle and accepts who he is and awakens his "Peter Tingle" again. This is probably helped by jumping into his work for designing and building a new suit using Tony's tech on the plane.

A: Peter's "Peter Tingle" has been known to work inconsistently in the comics at times. Honestly, I think the best answer here is probably "plot", but for those looking for a more satisfying answer...
Peter's spider-sense sometimes doesn't go off when he doesn't think he's in danger:

Spider-Sense does not go off to those that Spider-Sense does not believe to be a threat.

Meaning that if Peter didn't think Mysterio was a threat, his spider sense might not go off. However, at the end of the movie, he does think Mysterio is a threat, meaning that his spider senses probably would work.
As to why it doesn't go off for May:

It will not go off for Aunt May or Mary Jane Watson

Yeah, there's a spider-sense clause for that.
Over all, besides plot reasons, I think Peter's problems with his spider-sense are purely psychological. His arc for this movie was pretty much about him trying to fill certain shoes and about him feeling inferior. The whole point the movie was him overcoming these obstacles, and it sort of makes sense that his spider-sense would be part of that.

A: Re: Chipster's answer above, I think I'm going to elaborate on this.
The Spider-Sense may not be a form of ESP at all, but simply a shortcut between Peter's concious and unconscious mind. It happens in the real world; most people experienced this sometimes: on the surface, you are convinced that everything is OK, but somewhere deep in your subconscious something goes off because of a tiny detail your conscious mind didn't notice. You feel uneasy, but you don't know why.
The Spider-Sense is just a bridge between the conscious and the unconscious that allows the latter to send a brief message (the "tingle") to the former saying, "Here is where the danger's at!" in a way non-mutated brains can't - fast enough to dodge a point-blank bullet to the head.
This means Beck was that good at fooling Peter. Hell, he fooled Skrulls!

A: I can think of a number of reasons. Firstly, being a man of science he would find it hard to trust something that is more like magic since it can warn him of things that he can't actually see.
Secondly, as other have said, he has been going through a lot recently and it could be messing him up inside.
Finally, even if it is working correctly, it could be giving him confusing information about the elementals since they aren't actually real. He might not be getting any danger warnings at all since the fights are all an act and he isn't in any actual danger.


text:
Q: Discord OAuth2 in vanilla js without Node.js is it possible to use Discord OAuth2 in vanilla Javascript without using a node.js server or something?
I haven't found any documentation about that so I hope to get an answer from here.


text:
Q: PHP Count number of occurrences in numeric array I have a PHP array and I have dumped it below using Zend_Debug:
    $ids = array(13) {
  [0] => string(1) "7"
  [1] => string(1) "8"
  [2] => string(1) "2"
  [3] => string(1) "7"
  [4] => string(1) "8"
  [5] => string(1) "4"
  [6] => string(1) "7"
  [7] => string(1) "3"
  [8] => string(1) "7"
  [9] => string(1) "8"
  [10] => string(1) "3"
  [11] => string(1) "7"
  [12] => string(1) "4"
}

I am trying to get how many times each number occurs in the array and output it into an array.
I have tried using array_count_values($ids) but it outputs in the order of most occurred but I cant get the Total times the numbers occur.  It gives me the below output:
    array(5) {
  [7] => int(5)
  [8] => int(3)
  [2] => int(1)
  [4] => int(2)
  [3] => int(2)
}

I can see from the above array 7 occurs 5 times but I can access it when I loop through the array!
Any thoughts?
Cheers
J.

A: You can access the data you want like this:
$ids = array( ...);

$array = array_count_values( $ids);
foreach( $array as $number => $times_number_occurred) {
    echo $number . ' occurred ' . $times_number_occurred . ' times!';
}

Output:
7 occurred 5 times!
8 occurred 3 times!
2 occurred 1 times!
4 occurred 2 times!
3 occurred 2 times!

Demo

A: Use a foreach construct to loop through the resulting array:
$res = array_count_values($ids);

foreach( $res as $value => $count ) {
  // your code here
  echo "The value ".$value." appeared ".$count." times in the array";
}


text:
Q: Date and time in console log Is their a way to mention the date and time in the console log of an asp.net core 2.0 project for production and development environment?
I have following in my startup:
services.AddLogging(builder =>
{
            builder.AddConfiguration(Configuration.GetSection("Logging"+Environment.EnvironmentName))
                    .AddConsole()
                    .AddDebug();
});

Appsettings.json:
"LoggingDevelopment": {
    "IncludeScopes": false,
    "Console": {
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
  },
  "LoggingProduction": {
    "IncludeScopes": false,
    "Console": {
      "LogLevel": {
        "Default": "Error",
        "System": "Error",
        "Microsoft": "Error"
      }
    }
  },

Current [development] log layout (without a date or time of the log line):
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action a.Controller (project) in 531.2457ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 532.5812ms 200 text/html; charset=utf-8

A date and time would be extremly handy in production mode for error lines.

A: Default Console logger is pretty limited. Of course there is always the possibility to use lambda formatter like said in Github issue provided by serpent5. But it's accessible only if using raw ILogger.Log() method.
It's not available for ILogger extensions like LogInformation or LogError. This option is also not available if you don't control logging call. It's actually your case when logging is done by ASP.NET Core internal classes.
So you need some more flexible implementation of logger for .Net Core. I suggest using of Serilog. It's pretty simple but very flexible and powerful at the same time.
To integrate Serilog into ASP.Net Core application do the following:

*

*Install following NuGet packages:
Serilog.AspNetCore
Serilog.Sinks.Console
Besides Console, Serilog supports many other targets like Rolling File, E-mail, SQL Server, etc. See this list of other Serilog targets.

*Configure Serilog on application startup:
Here is a sample:
public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}")
            .CreateLogger();

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog()
            .Build();
}

Provided output template adds date and time to logged message:

A: To expand on CodeFuller's response, here's how you can modify the Serilog Console output formatter purely from configuration:
{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "System": "Information",
        "Microsoft": "Information"
      }
    },
    "WriteTo:Sublogger": {
      "Name": "Logger",
      "Args": {
        "configureLogger": {
          "WriteTo": [
            {
              "Name": "Console",
              "Args": {
                "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{TraceId}] {Message:lj}{NewLine}{Exception}"
              }
            }
          ]
        }
      }
    }
  }
}

If you take this approach, remove the WriteTo.Console logger method from your startup configuration. This line:
 .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}")

I've also modified the output format template slightly. Either template will work fine.


text:
Q: Binary Search Tree using doubly Linked List, find adjacency Currently doing an assignment where we have to make a binary search tree (I'm using a linked list implementation) and I'm currently getting stuck trying to find the adjacency of nodes given two nodes. It is marked against input that is hidden, I'll provide my code and test cases that I can't fulfill. This is my first time writing a question on Stack Overflow let me know how to word my questions better and/or provide more detailed information. Also I'm not sure if I'm allowed to post my code from the assignment so I might have to take it down.
My implementation as far:
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <limits>
#include <utility>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <cmath>
#include <memory>

using namespace std;

template <typename T> // the template allows the weight of vertex to take any numeric data type (denoted by T).
class BST {

    private:

        struct TreeNode {
            T weight;
            string name;
            std::unique_ptr<TreeNode> left;
            std::unique_ptr<TreeNode> right;

            TreeNode(T weight, string name): weight(weight), name(name), left(nullptr), right(nullptr) {}
        };

    std::unique_ptr<TreeNode> root;

    public:
        /* define your data structure to represent a binary search tree (bst) */

        map<string, T> vertices;

        vector<string> leaves;
        vector<pair<string,string>> edges;

        bool adjacent_found = false;

        /* test1 */
        BST(); // the contructor function.
        ~BST(); // the destructor function.
        size_t num_vertices(); // returns the total number of vertices in the bst.

        void count(int& , const std::unique_ptr<TreeNode>&);

        size_t num_edges(); // returns the total number of edges in the bst.
        T sum_weight(); // return the total weight of all the vertices in the bst.

        void weight_total(int& , const std::unique_ptr<TreeNode>&);

        void print();
        std::string TreeToString(const std::unique_ptr<TreeNode>& );  // Helper method for Print()

        /* test2 */
        void add_vertex(const string&, const T&); // adds a vertex, which has a weight, to the tree -- every vertex uses a string as its unique identifier.
        void Insert(const T&, const string&, std::unique_ptr<TreeNode>&);

        bool contains(const string&); // checks if a vertex is in the bst -- returns true if the bst contains the given vertex; otherwise, returns false.

        bool Contains(const string&);

        /* test3 */
        vector<string> get_vertices(); // returns a vector of all the vertices in the bst.
        vector<string> get_leaves(); // returns a vector of all the leaves in the bst.
                                     //     Leaves are the vertices that do not have any children in the bst.
        void extract_leaf_nodes(std::unique_ptr<TreeNode>&);

        /* test4 */
        bool adjacent(const string&, const string&); // check if there is an edge between the two vertices in the bst -- returns true if the edge exists; otherwise, returns false.

        void Adjacent(const string &, const string&, std::unique_ptr<TreeNode>&);
        /* test5 */
        vector<pair<string,string>> get_edges(); // returns a vector of all the edges in the bst -- each edge is represented by a pair of vertices incident to the edge.

        void edge_retrieval(std::unique_ptr<TreeNode>&);

        /* test6 */
        vector<string> get_neighbours(const string&); // returns a vector of all the vertices, each of which is directly connected with the given vertex via an edge.
        size_t degree(const string&); // returns the degree of a vertex.

        /* test7 */
        vector<string> preorder_traversal(); // returns a vector of all the vertices in the visiting order of a preorder traversal over the bst.

        /* test8 */
        vector<string> inorder_traversal(); // returns a vector of all the vertices in the visiting order of an inorder traversal over the bst.

        /* test9 */
        vector<string> postorder_traversal(); // returns a vector of all the vertices in the visiting order of a postorder traversal over the bst.

        /* test10 */
        vector<string> breadth_first_traversal(); // returns a vector of all the vertices in the visiting order of a breadth first traversal over the bst.

        /* test11 */
        vector<string> path(const string&, const string&); // returns a vector of all the vertices in the path from the first vertex to the second vertex.
                                                            //     A path should include the source and destination vertices at the begining and the end, respectively.

        /* test12 */
        vector<string> path_with_largest_weight(); // returns a path that has the largest weight in the bst.
                                       //    The weight of a path is the sum of the weights of all the vertices (including the source and destination vertices) in the path.

        /* test13 */
        size_t height(); // returns the height of bst. Height of a tree is the number of edges that form the longest path from root to any leaf.

        /* test14 */
        void remove_vertex(const string&); // delete the given vertex from bst -- note that, all incident edges of the vertex should be deleted as well.

};

/* test1 */

template <typename T>
BST<T>::BST() {
    root = nullptr;
}

template <typename T>
BST<T>::~BST() {}

template <typename T>
size_t BST<T>::num_vertices() {
    int total_vertices = 0;
    this->count(total_vertices,this->root);
    return total_vertices;
}

template <typename T>
void BST<T>::count(int& total_vertices, const std::unique_ptr<TreeNode>& node) {
    if (node != nullptr) {
        total_vertices++;
        this->count(total_vertices, node->left);
        this->count(total_vertices, node->right);
    }
}

template <typename T>
void BST<T>::weight_total(int& total_weight, const std::unique_ptr<TreeNode>& node) {
    if (node != nullptr) {
        total_weight += node->weight;
        this->weight_total(total_weight,node->left);
        this->weight_total(total_weight,node->right);

    }
}

template <typename T>
size_t BST<T>::num_edges() {
    if (num_vertices() != 0) {
        return (this->num_vertices() - 1);
    } else {
        return 0;
    }
}

template <typename T>
T BST<T>::sum_weight() {
    int total_weight = 0;
    this->weight_total(total_weight,this->root);
    return total_weight;
}

template <typename T>
void BST<T>::print(){
    if(this->root == nullptr){
        std::cout << "{}" << std::endl;
    } else{
        std::cout << this->TreeToString(this->root) << std::endl;
    }
}

template <typename T>
std::string BST<T>::TreeToString(const std::unique_ptr<TreeNode>& node) {
    std::string leftStr = (node->left == nullptr) ? "{}" : TreeToString(node->left);
    std::string rightStr = (node->right == nullptr) ? "{}" : TreeToString(node->right);
    std::string result = "{" + (node->name) + ", " + leftStr + ", " + rightStr + "}";
    return result;
}

/* test2 */

template <typename T>
void BST<T>::add_vertex(const string& u, const T& w) {
    this->Insert(w, u, this->root);
}

template <typename T>
void BST<T>::Insert(const T& w, const string& vertice_name, std::unique_ptr<TreeNode>& node) {
    if(node == nullptr){
        // Make a new TreeNode for it to point to
        node = std::make_unique<TreeNode>(w, vertice_name);

        //cout << vertice_name << " : " << w << " | ";

        vertices.insert(make_pair(vertice_name, w));

        //cout << "Node: " <<  '"' << node->name << '"' << " | " << node->weight << endl;
    } else{
        if( w < node->weight) {
            //cout << "Going left because w is: " << w << " and weight of node is: " << node->weight << endl;
            // Case: w is < node's weight
            this->Insert(w, vertice_name, node->left);
        } else{
            this->Insert(w, vertice_name, node->right);
        }
    }

}

template <typename T>
bool BST<T>::contains(const string& u) {
    return Contains(u);
}

template <typename T>
bool BST<T>::Contains(const string& _name) {
    for (auto& [key, value]: vertices) {
        if (key == _name) {
            return true;
        }
    }
    return false;
}

/* test3 */

template <typename T>
vector<string> BST<T>::get_vertices() {
    vector<string> get_vertices_vector;
    for (auto& [key, value]: vertices) {
        get_vertices_vector.push_back(key);
    }
    return get_vertices_vector;
}

template <typename T>
vector<string> BST<T>::get_leaves() {

    extract_leaf_nodes(this->root);
    return leaves;
}

template <typename T>
void BST<T>::extract_leaf_nodes(std::unique_ptr<TreeNode>& node) {
    // if node is leaf node, copy name
    if (!node->left && !node->right)
    {
        leaves.push_back(node->name);
    }

    // if left child exists, check for leaf
    // recursively
    if (node->left) {
        extract_leaf_nodes(node->left);
    }

    // if right child exists, check for leaf
    // recursively
    if (node->right)
       extract_leaf_nodes(node->right);

}

/* test4 */

template <typename T>
bool BST<T>::adjacent(const string& u, const string& v) {
    adjacent_found = false;
    if (this->contains(u) && this->contains(v)) {
        Adjacent(u, v, this->root);
    }
    return adjacent_found;

}

template <typename T>
void BST<T>::Adjacent(const string & u, const string& v, std::unique_ptr<TreeNode>& node ) {
    if (node != nullptr) {
        if (node->name == v && node->left != nullptr && node->right != nullptr) {
            if (node->right->name == u) {
                adjacent_found = true;
            } else if (node->left->name == u) {
                adjacent_found = true;
            }
        } else if (node->name == u && node->left != nullptr && node->right != nullptr) {
            if (node->right->name == v) {
                //return true;
                adjacent_found = true;
            } else if (node->left->name == v) {
                adjacent_found = true;
            } else {
                // Not Adjacent
            }
        } else {
            // Can't find either
            if (node->left != nullptr) {
                Adjacent(u,v,node->left);
            } else if (node->right != nullptr) {
                 Adjacent(u,v,node->right);
            }
        }
    }
}

/* test5 */

template <typename T>
vector<pair<string,string>> BST<T>::get_edges() {
    edge_retrieval(this->root);
    return edges;
}

template <typename T>
void BST<T>::edge_retrieval(std::unique_ptr<TreeNode>& node) {
    for (auto x : edges) {
        if (x.first == node->name) {
            edge_retrieval(node->left);
            edge_retrieval(node->right);
        } else {
            if (node->left != nullptr) {
                edges.push_back(make_pair(node->name,node->left->name));
            }
            else if (node->right != nullptr) {
                edges.push_back(make_pair(node->name,node->right->name));
            }

        }
    }

}

/* test6 */

template <typename T>
vector<string> BST<T>::get_neighbours(const string& u) {
    return vector<string>();
}

template <typename T>
size_t BST<T>::degree(const string& u) {
    vector<string> neighbours = get_neighbours(u);

    return neighbours.size();
}

/* test7 */

template <typename T>
vector<string> BST<T>::preorder_traversal() {
    return vector<string>();
}

/* test8 */

template <typename T>
vector<string> BST<T>::inorder_traversal() {
    return vector<string>();
}

/* test9 */

template <typename T>
vector<string> BST<T>::postorder_traversal() {
    return vector<string>();
}

/* test10 */

template <typename T>
vector<string> BST<T>::breadth_first_traversal() {
    return vector<string>();
}

/* test11 */

template <typename T>
vector<string> BST<T>::path(const string& u, const string& v){
    return vector<string>();
}

/* test12 */

template <typename T>
vector<string> BST<T>::path_with_largest_weight(){
    return vector<string>();
}

/* test13 */

template <typename T>
size_t BST<T>::height() {
    return 0;
}

/* test14 */

template <typename T>
void BST<T>::remove_vertex(const string& u) {

}

Test Cases: (v2 is adjacent to v3, but is returning that its not. And v2 is adjacent to v10 but also returning its not)
#include "tree.hpp"

int main(){

    BST<int> bst;

    bst.add_vertex("v1", 15);
    bst.add_vertex("v4", 5);
    bst.add_vertex("v0", 10);
    bst.add_vertex("v3", 30);
    bst.add_vertex("v2", 17);
    bst.add_vertex("v5", 1);
    bst.add_vertex("v7", 3);
    bst.add_vertex("v6", 20);
    bst.add_vertex("v8", 12);
    bst.add_vertex("v9", 7);
    bst.add_vertex("v10", 30);
    bst.add_vertex("v11", 28);
    bst.add_vertex("v12", 16);
    bst.add_vertex("v13", 21);
    bst.add_vertex("v14", 24);
    bst.add_vertex("v15", 36);
    bst.add_vertex("v16", 14);
    bst.add_vertex("v17", 14);

    cout << "is v2 adjacent to v3?:" << bst.adjacent("v2","v3") << endl;
    cout << "is v2 adjacent to v10?:" << bst.adjacent("v2","v10");
}


text:
Q: make http post synch using Observable in Angular I'm trying to implement this but need some help (I'm new to this).
I currently have,
constructor(http: HttpClient, private cvservice: CvService) {
const req = http.post<any>('url', [{
            "name": "ids",
            "license": "GPL version 2"
}])
  .subscribe(
    res => {
    console.log(res);
    var resp = res.Results[0].results.map(x => {
            return {cvid: x.ID, severity: x.CVSS };
    } );
   this.data = [...resp];
    },
    err => {
      console.log("Error occured");
    }
  );
}

This works fine except I need to make the http.post synch (need Results[0] before continuing) and I'm using the suggestion from, How to synchronise Angular2 http get?.
I've modified the service as,
export class CvService {
constructor(private http: HttpClient) {
}
url = 'foo';
getIds():Observable<any[]> {
const url='xxx';
return this.http.post(url, [{
            "name": "ids",
            "license": "GNU General Public License GPL version 2"
        }])
        .map(
            res =>  {
                res.Results[0].results.map( x => {
                   return {cvd: x.ID, severity: x.CVSS };
}));
}
}
}

But I think this syntax is wrong. This gives compile error. Can someone please clarify the correct way to use the map function here?

A: import map from rxjs and use it inside the pipe like this
return this.http.post(URL, Object)
 .pipe(map(data) => {
    return data['result'].map(res => {
   // Here You can return the entire res, or just the properties you want
   // EX: --> return res OR --> return res.cvd
   });
});

also, make the object outside
let cv = [{
  name: "ids",
  license: "GNU General Public License GPL version 2"
}];

You can use it then like this
return this.http.post(URL, cv);

A: You can implement this way:
Service
saveUser(): Observable<any> {
    const data = [{"name": "ids", "license": "GNU General Public License GPL version 2"}];

    // For Angular v5 below
    this.http
      .post(url, data)
      .map(res => res.json());       // or .map(res => res), depends what your fetching with

    OR you can pipe it out (Angular 6+)

    this.http
      .post(url, data)
      .pipe(map(({ Results }: any) => Results[0].results.map(item => ({cvid: item.ID, severity: item.CVSS }))));

    // Based from you code when you accessed it this way: res.Results[0].results.map( x => {return {cvd: x.ID, severity: x.CVSS };
}

Component
this.userService
   .saveUser()
   .subscribe(data => console.log(data));

Had created a Stackblitz demo for your reference - This uses different data and mocked POST API for demo purposes only.