text:
Q: Query DHT for the total number of active peers Assume there is a P2P file sharing system which has no trackers but only a DHT.
How to know the number of all active peers uploading/downloading a specific file?
Is it just keep querying the DHT by get_peers to get new peers? Are there any better solution?

A: The distributed part in the DHT makes it hard to get the exact number of peers in a swarm from it. Technically it's also unneeded and not a very useful number, as its only necessary to get in contact with only one other peer in the swarm and then the PeerEXchange extension will give plenty more peers in a more efficient way than the DHT.
Some clients also support the BEP33 DHT scrape extension that can give a approximate number of peers registered in the DHT with a max capacity of ca 6000.
Unfortunately it's badly designed and has a vulnerability making it the currently most potent vector for UDP amplification attacks using the BitTorrent protocol. It has a BAF (Bandwidth Amplification Factor) of 13.4 The attack is called Distributed Reflective Denial of Service (DRDoS) and is decribed in this paper. If this vector starts to get used it may be necessary to speedly remove this extension from the protocol.


text:
Q: Lockdown: insmod: unsigned module loading is restricted; see man kernel_lockdown.7 While inserting simple hello kernel module facing below error messge
Ex: insmod: ERROR: could not insert module main.ko: Operation not permitted
Os used:
NAME="Ubuntu"
VERSION="20.04.2 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.2 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal

redpajama_set_name: RedPajamaStackExchange


text:
Q: Query result set randomly duplicated I've a very simple query that returns duplicated rows, randomly. Sometimes I have no duplicates, other times I have duplicate result set, and duplicated record are every time different. I'm running the query on frozen database (data don't change). My Oracle version is the 11g.
I have only one filter (in the WHERE clause) on a date:
to_char(date,'yyyy/mm') > = '2012/03'.
Any help would be appreciated.
Thank you for your attention.
Best regards.
Complete query:
select distinct
   B.ORD_V_COD_ROWID as c1,
   B.ORD_D_DAT_INSERITO_RIFIUTATO as c2,
   B.ORD_D_DAT_RIFIUTO_SIS as c3
  from
       NRFTF_ORD_ORDINE A,
       NRFTF_COR_ORDINI_RDS B
  where  (A.ORD_N_DWH_NUM_ORDINE = B.ORD_N_DWH_NUM_ORDINE
  and B.ORD_V_COD_CAUSALE = 'CLIENTE NON AFFIDABILE'
  and B.ORD_V_COD_STATO = 'RIFIUTATO'
  and B.RDS_C_DWH_FLG_CANCELLAZIONE = '0'
  and B.ORD_C_DWH_FLG_CANCELLAZIONE = '0'
  and B.ORD_V_COD_CAUSALE = 'CLIENTE NON AFFIDABILE'
  and B.PER_NAME_MONTH >= '2012/03'
  and (B.ORD_D_DAT_RIFIUTO_SIS >= TO_DATE('2012-03-22 00:00:00' , 'YYYY-MM-DD HH24:MI:SS')
  or B.ORD_D_DAT_INSERITO_RIFIUTATO >= TO_DATE('2012-03-22 00:00:00' , 'YYYY-MM-DD HH24:MI:SS'))
  and  TO_CHAR (A.ord_d_dat_creazione,'YYYY/MM') >= '2012/03' )
  order by c1, c2, c3

A: Interesting. I have seen somewhat similar behaviour with a broken index. Rebuilding the index fixed the problem for sometime, but then non deterministic behaviour came back. We ended up calling Oracle support. They fixed it in a really impressive 24hour-around-the-globe-updating-the-data-dictionary-session.
I'd try rebuilding all tables and indexes involved from scratch.
If this doesn't help and you triple checked that you don't have anything dynamic going on on your side contact Oracle support.


text:
Q: Design pattern for Processing unlimited Events I want suggestion any design pattern in which I want to process unlimited events.
I am not sure how many events I may get when the system is running.
I have some actions defined on those events.
I am looking for solutions which can give me processing actions in near real time.

A: Does Chain of Responsibility work for you?
You would give all the event producers an object to send the events to, and that object would pass the event down from rule to rule until it is fully handled.
Also when building GUI applications in Java I need to deal with many graphical components which generate various events based on user actions, and based on what event happens I need to implement rules for what happens.
I am not sure the name of the basic event listener pattern that is in use in Swing, but that might work for you too.
If you mean real time like GUI response time, then just calling out to an event handler should be plenty fast, that is what happens in Swing.
If I knew more about how or where these events are being generated then there may be a better pattern that I could suggest.


text:
Q: Not able to set the "PasswordNeverExpires" parameter to true in Powershell 2.0 Below is my Powershell script -
Import-Module ActiveDirectory
$objOU=[ADSI]"LDAP://OU=Service,OU=Accounts,DC=xyz,DC=com";
$dataSource=import-csv "add_user2.csv";

foreach($dataRecord in $datasource)
{
$cn=$dataRecord.FirstName + " " + $dataRecord.LastName
$sAMAccountName=$dataRecord.FirstName + "." + $dataRecord.LastName
$givenName=$dataRecord.FirstName
$sn=$dataRecord.LastName

$displayName=$sn + ", " + $givenName
$userPrincipalName=$sAMAccountName + "@test.com";

#Additional Attributes
$objUser=$objOU.Create("user","CN="+$cn)
$objUser.Put("sAMAccountName",$sAMAccountName)
$objUser.Put("userPrincipalName",$userPrincipalName)
$objUser.Put("displayName",$displayName)
$objUser.Put("givenName",$givenName)
$objUser.Put("sn",$sn)

#Place the additional attributes into the record

$objUser.Put("PasswordNeverExpires", $true)
$objUser.SetInfo()

}

I am trying to set the values of an ActiveDirectory user, using the above script. The problem I am facing is I am not able set the "PasswordNeverExpires" attribute under Account Options in Account tab to True.
My input file "add_user1.csv" looks like -
FirstName   LastName
Test              Account1

Will appreciate all help.
Regards.

A: There is no PasswordNeverExpires property. If you run Get-Member on $objUser you will see this. These properties are controlled by UserAccountControl. For more information look here.
This blog article details how to set the password never expires attribute to true:
Setting "Password never expire" attribute on user object
This property unlike many other properties of AD object are contained in bitmask
attribute UserAccountControl
(not related in any way with User Account Control feature of Windows).
To set it you need to retrieve current value of this attribute and use binary OR
operation (-bor) to calculate new value.

$User = [ADSI]"LDAP://cn=Gusev,ou=Users,ou=Lab,dc=contoso,dc=com"
$UAC = $User.UserAccountControl[0] -bor 65536
$User.Put("userAccountControl",$UAC)
$User.SetInfo()

Your script needs to be modified as such:
$objUser.SetInfo()

#Place the additional attributes into the record
$UAC = $objUser.UserAccountControl[0] -bor 65536
$objUser.Put("userAccountControl",$UAC)
$objUser.SetInfo()

Without running SetInfo() twice the script will throw an error.

A: Another thing you could use to get around having to fiddle with the UserAccountControl property is to use the PasswordNeverExpires parameter of Set-ADUser.
$objUser | Set-ADUser -PasswordNeverExpires

In fact, you could replace a lot of that code by using New-ADUser
Import-Module ActiveDirectory
$dataSource=import-csv "add_user2.csv";

foreach($dataRecord in $datasource)
{
    $cn=$dataRecord.FirstName + " " + $dataRecord.LastName
    $sAMAccountName=$dataRecord.FirstName + "." + $dataRecord.LastName
    $givenName=$dataRecord.FirstName
    $sn=$dataRecord.LastName
    $displayName=$sn + ", " + $givenName
    $userPrincipalName=$sAMAccountName + "@test.com";

    New-ADUser $cn -SamAccountName $sAMAccountName -GivenName $givenName `
        -Surname $sn -DisplayName $displayName -UserPrincipalName $userPrincipalName `
        -PasswordNeverExpires $true -Path "OU=Service,OU=Accounts,DC=rjfdev,DC=com"
}


text:
Q: Can someone look at my loop? guys I have no idea what is wrong with my loop but I keep on getting an error that my last line is not indented properly , i have tried indenting it multiple times but keep on getting the error.
while itemsneeded>=1:
    if (items[0]) == 86947367 :
        with open("read_it.txt") as text_file:
            try:
                price = int(text_file.readlines()[2])
            except ValueError:
                print("error")
            else:
                new_price = int(price * (items2[0]))
                print("£",new_price)

    elif (items[0]) == 78364721 :
        with open("read_it.txt") as text_file:
            try:
                price = int(text_file.readlines()[6])
            except ValueError:
                print("error")
            else:
                new_price = int(price * (items2[0]))
                print("£",new_price)

    elif (items[0]) == 35619833 :
        with open("read_it.txt") as text_file:
            try:
                price = int(text_file.readlines()[10])
            except ValueError:
                print("error")
            else:
                new_price = int(price * (items2[0]))
                print("£",new_price)

    elif (items[0]) == 84716491  :
        with open("read_it.txt") as text_file:
            try:
                price = int(text_file.readlines()[14])
            except ValueError:
                print("error")
            else:
                new_price = int(price * (items2[0]))
                print("£",new_price)

    elif (items[0]) == 46389121  :
        with open("read_it.txt") as text_file:
            try:
                price = int(text_file.readlines()[18])
            except ValueError:
                print("error")
            else:
                new_price = int(price * (items2[0]))
                print("£",new_price)
else:
    continue

I want my code to continue if itemsneeded is not equal to 1 or more.

A: The problem is continue within your last else clause. It's not needed as there's no iterator to continue with. As soon as your program leaves the while loop it moves on anyways.
Remove the last two lines.
else:
    continue


text:
Q: Multithreading Thread restart i'am writing a small app to remote control a (Behringer x32) Mixing console. And i got a problem with the communication.
I'am sending data from the pc (app) to the console (port 10023 UDP Protocol), then the console answers to the port from the pc has send data, (random port).
So i have 2 Threads one for sending data, and one for listening for data from the console..... so every time i send data to the console, i need to change the listening port... so i have to kill the listening thread and start it new.
But after some time a have and the app has about x1000 threads open.
How can i restart the Thread or update the listening port without create a new thread?
here's the code for this section, the whole files are @ gihub
the listening thread class:
public class Receiver implements Runnable {

    private List<IReceiverListener> listeners;
    private final static int PACKETSIZE = 48;
    private int port;

    public Receiver() {
        listeners = new ArrayList();
    }

    public void addReceiverListener(IReceiverListener listener) {
        listeners.add(listener);
    }

    private void update(String data, String adress) {
        for (IReceiverListener listener : listeners) {
            listener.receiveConsoleData(data, adress);
            if (data.indexOf("active") > -1) {
                listener.incrementWatchDog();
            }
        }
    }

    @Override
    public void run() {
        try {
            // Convert the argument to ensure that is it valid
            // Construct the socket
            while (true) {
                //System.out.println("Listen on Port:" + this.port);
                DatagramSocket socket = new DatagramSocket(this.port);
                // Create a packet
                DatagramPacket packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
                // Receive a packet (blocking)
                socket.receive(packet);
                // Print the packet
                update(new String(packet.getData()), packet.getAddress().toString());
                //logger.addLogData(new String(packet.getData())+"  "+packet.getAddress().toString());
                // Return the packet to the sender
                socket.close();
            }
        } catch (IOException e) {

        }
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getPort() {
        return port;
    }
}

and here my port updateFunction
 @Override
public void updatePort(int port) {
    receiverThread.interrupt();
    receiverThread = null;
    receiver.setPort(port);
    receiverThread = new Thread(receiver);
    receiverThread.start();
}

and the sending thread does this, when it sends data:
 listener.updatePort(dsocket.getLocalPort());

A: This is actually not a threading problem. The problem is, that the receiver thread is stuck in the receive method, so it cannot react to the changed port. However, calling the method DatagramSocket#close from another thread releases the blocking receiver thread with a SocketException.
Thus, you can solve this by closing the currently receiving socket when the receiving port was changed. The receiving thread can now catch the SocketException and create a new DatagramSocket that listens on the new port.
There is no need to kill and recreate threads.

First you put the socket into a field. This allows you to access it from another thread, so you can call the socket.close() method. Second, you put another try-catch block into the while(true) loop, which only catches SocketException.
Something like this might work fine:
public class Receiver implements Runnable {

    private static final int PACKETSIZE = 48;

    private final ConcurrentLinkedQueue<IReceiverListener> listeners = new ConcurrentLinkedQueue<>();

    private volatile DatagramSocket socket;
    private volatile int port;

    public Receiver(int port) {
        this.port = port;
    }

    public void addReceiverListener(IReceiverListener listener) {
        listeners.add(listener);
    }

    public void updatePort(int port) {
        this.port = port;
        DatagramSocket socket = this.socket;
        if (socket != null) {
            socket.close();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                receiveLoop(new DatagramSocket(port));
            }
        } catch (IOException e) {
            // handle error
        }
    }

    private void receiveLoop(DatagramSocket newSocket) throws IOException {
        try (DatagramSocket socket = newSocket) {
            this.socket = newSocket;
            while (true) {
                DatagramPacket packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
                socket.receive(packet);
                process(packet);
            }
        } catch (SocketException e) {
            // port was changed -> return and restart with a new socket
        } finally {
            this.socket = null;
        }
    }

    private void process(DatagramPacket packet) {
        update(new String(packet.getData()), packet.getAddress().toString());
    }

    private void update(String data, String adress) {
        for (IReceiverListener listener : listeners) {
            listener.receiveConsoleData(data, adress);
            if (data.indexOf("active") > -1) {
                listener.incrementWatchDog();
            }
        }
    }
}

Please note, that this might still contains some bugs. It is only supposed to give you a rough idea of how to solve this.

A: As you are using DatagramSocket, you can change the used port by Binding the socket to a new port rather than the used one:
socket.bind(new InetSocketAddress(new_port));

But remember that bind() method won't work unless the socket is already opened and a port assigned to it, so at the first time you have to create the socket regularly, then when you try to change the port, just bind it.
And the following is a complete visualization of the process:
public void video_udp_server(int port) throws Exception
{
    byte[] receiveData = new byte[Integer.MAX_VALUE/100];
    for(int i = 0; i < receiveData.length; i++){
        receiveData[i] = ' ';
    }

    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    DatagramSocket socket = null;
    try{
        socket = new DatagramSocket(port);
    }catch(Exception ex){
        socket.bind(new InetSocketAddress(port));
    }
    socket.setReuseAddress(true);
    socket.receive(receivePacket);

    System.out.println(new String(receivePacket.getData()));

}


text:
Q: "Dirty" polygons created when using "Merge selected features" in QGIS When I selecting features to merge in QGIS 2.14.3-Essen using "merge selected features", I sometimes get "dirty" results with redundant polygon vertices. Is there an ex-ante or an ex-post way to get rid of them? Using Mac OS 10.11.6 El Capitan

A: Those gaps are produced because during the digitizing process the "topological" option is not enabled. Hence borders must be redrawn instead of being used as a reference for the new polygon.
There is a simple and quick approach to solve the problem. Here is a demonstration with a polygon layer with the same issues:
1) First the original shapefile, with Chilean administrative regions.

2) After enabling editing mode and merge two regions gaps appear.

3) In editing mode again you could use the 'Node Tool' in order to select the vertices of those gaps.

4) Finally, press Supr to delete the vertices and consequently the gaps.


text:
Q: How can I adjust the width of a pickerColumn to the text inside the pickerColumns? So far I can only adjust the size of each PickerColumn manually through code, but I want each of them to adjust automatically according to the contents from the largest PickerRow inside of any of them.
This is because I'm working with dynamic PickerColumns whose PickerRows content change according to the previous PickerColumn's selected value. I found out how to scale the whole Picker using the next code:
var transformPicker=Ti.UI.create2DMatrix().scale(0.5);
var picker = Ti.UI.createPicker({
    width:500,
    height:10,
    top:0,
    transform:transformPicker
});

I tried to apply a transformation matrix to a PickerColumn but it didn't do anything. Does anybody know how to adjust the size of them? Or am I trying to resize the wrong thing?
Thanks in advance for any piece of advice you can give me, I'm new to developing for iOS in Titanium and even though is not hard to get used to its API, the real issue are the small tricks like the one I'm trying to figure out that makes the whole thing kinda confusing.

A: If you use a transform that could very well get you a rejection from Apple, since this is a Apple Specific UI element, so any egregious resizing of it will violate the Human Interface guidelines.  If you find that you have too many columns for the screen width, then you may need to abandon the Picker element :-( or face Apple's wrath.
But to answer your question about dynamic resizing of picker columns, just use the reloadColumn( Titanium.UI.PickerColumn column ) method of the picker. This will resize based on picker size and row contents. Also consider using updateLayout( Dictionary params ) of the PickerColumn.
Check the documentation here.


text:
Q: Как сделать загрузку в определенную папку с определенным названием? на Python Использовал библиотеку youtube-dl на python. Нужно загружать ролик по ссылке в определенную папку с определенным названием, как это сделать? (Моя попытка)
ydl_opts = {'outtmpl':'videos_youtube/botazure'} # тут должно задаться путь и название файла
            with youtube_dl.YoutubeDL() as ydl:
                ydl.download(link) # загрузка ```


text:
Q: 'player' : unknown override specifier Why isn't my code working??? What does this error mean? FYI: I wanted to create a top down shooter game. all my code was basically just copied from different sources(some I just solved on my own).
I intended to put the player class in the game loop or game class. here's the code:
game.cpp
#include "Player.h"

//Private Functions
void game::intVariables()
{
    this->window = nullptr;

    this->points = 0;
    this->enemySpawnTimerMax = 1000.f;
    this->enemySpawnTimer = this->enemySpawnTimerMax;
    this->maxEnemies = 8;
}

void game::intWindow()
{
    this->videoMode.height = 1080;
    this->videoMode.width = 1780;
    this->window = new sf::RenderWindow(this->videoMode, "Top Down Shooter", sf::Style::Close | sf::Style::Titlebar);

    this->window->setFramerateLimit(60);

    this->window->setKeyRepeatEnabled(true);

    Player player("player.png");

}

void game::intEnemies()
{
    this->enemy.setPosition(30.f, 30.f);
    this->enemy.setSize(sf::Vector2f(50.f, 50.f));
    this->enemy.setFillColor(sf::Color(0, 128, 128));
    this->enemy.setOutlineColor(sf::Color::Black);
    this->enemy.setOutlineThickness(-4.f);
}

//Constructors or Destructors
game::game()
{
    this->intVariables();
    this->intWindow();
    this->intEnemies();
}

//prevents memory leak
game::~game()
{
    delete this->window;
}

//Accessors
const bool game::running() const
{
    return this->window->isOpen();
}

//functions
void game::player1()
{
    player.drawPlayer(*this->window);
}

void game::spawnEnemy()
{
    /*
        @return void

        Spawns enemies and sets their color and positions.
        - select random position
        - select random color
        - add enemy to vector
    */

    this->enemy.setPosition(
        static_cast<float>(rand() % static_cast<int>(this->window->getSize().x - this->enemy.getSize().x)),
        static_cast<float>(rand() % static_cast<int>(this->window->getSize().y - this->enemy.getSize().y))
    );

    this->enemy.setFillColor(sf::Color(0, 128, 128));

    //spawns the enemy
    this->enemies.push_back(this->enemy);
}

void game::pollEvents()
{
    //event polling
    while (this->window->pollEvent(this->evnt))
    {
        switch (this->evnt.type)
        {
        case sf::Event::Closed:
            this->window->close();
            break;
        case sf::Event::KeyPressed:
            if (this->evnt.key.code == sf::Keyboard::Escape)
                this->window->close();
            break;
        }
    }
}

void game::updateEnemies()
{
    /*
        @return void

        updates the enemy spawn timer and spawns enemies
        when the total amount of enemies is smaller than the maximum.
        removes the enemies at the edge of the screen. //to do
    */

    //Updating the timer for enemy spawning
    if (this->enemies.size() < this->maxEnemies)
    {
        if (this->enemySpawnTimer >= this->enemySpawnTimerMax)
        {
            //spawn the enemy and reset the timer
            this->spawnEnemy();
            this->enemySpawnTimer = 0.f;
        }
        else
            this->enemySpawnTimer += 1.f;
    }
    // Move the enemies
        for (auto &e : this->enemies)
        {
            e.move(0.f, 1.f);
        }
}

void game::update()
{
    this->pollEvents();

    this->updateMousePositions();

    this->updateEnemies();
}

void game::renderEnemies()
{
    for (auto &e : this->enemies)
    {
        this->window->draw(e);
    }
}

void game::render()
{
    /*
     - clears old frame
     - renders objects
     - display frames on window

      renders game objects.
    */

    this->window->clear(sf::Color(128, 128, 128));

    //draw game objects
    this->renderEnemies();

    this->player1();

    this->window->display();
}

void game::updateMousePositions()
{
    /*
    @return void

    updates the mouse position
    *mouse postion relative to window (vector2i)*
    */
    this->mousePosWindow = sf::Mouse::getPosition(*this->window);
}

game.h

#include <iostream>
#include <vector>
#include <ctime>

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>

/* class acts as the game engine
    wrapper class.
*/

class game
{
protected:
    //variables
    //window
    sf::RenderWindow* window;
    sf::VideoMode videoMode;
    sf::Event evnt;

    //mouse positions
    sf::Vector2i mousePosWindow;

    //game logic
    int points;
    float enemySpawnTimer;
    float enemySpawnTimerMax;
    int  maxEnemies;

    //game objects
    std::vector<sf::RectangleShape> enemies;
    sf::RectangleShape enemy;
    Player player;

    // Private Functions
    void intVariables();
    void intWindow();
    void intEnemies();
public:
    // Constructors or Destructors
    game();
    virtual ~game();

    // Accessors
    const bool running() const;

    // Functions
    void player1();
    void spawnEnemy();
    void pollEvents();
    void updateEnemies();
    void update();

    void renderEnemies();
    void render();
    void updateMousePositions();

};

Player.h

#include <iostream>
#include <SFML/Graphics.hpp>
#include "game.h"

class Player
{
public:
    Player() {
        //default
    }
    Player(std::string imgDirectory) {
        if (!playerTexture.loadFromFile(imgDirectory)) {
            std::cerr << "Error\n";
        }
        playerSprite.setTexture(playerTexture);
    }
    void drawPlayer(sf::RenderWindow& window) {
        window.draw(playerSprite);
    }
    void movePlayer(char direction, float moveSpeed) {
        if (direction == 'u')
        {
            playerSprite.move(0, -moveSpeed);
        }
        else if (direction == 'd')
        {
            playerSprite.move(0, -moveSpeed);
        }
        else if (direction == 'l')
        {
            playerSprite.move(-moveSpeed, 0);
        }
        else if (direction == 'r')
        {
            playerSprite.move(moveSpeed, 0);
        }
    }
private:
    sf::Texture playerTexture;
    sf::Sprite playerSprite;
};


text:
Q: CSS background-image I All,
I am using Ionic2. I am trying to display a message box with an image to the bottom right of it. As you can see from the screen capture below, the image (light green) is being hidden (cut-off) as soon as it is outside the message box.

Question
How do I get the full image to be displayed?
It is as if the ion-list is allowing the message box to be displayed, but not anything beyond the message box.
More info:
The image is: /assets/message-me.png

.messages-page-content {
  > scroll-content {
    padding: 0;
  }
  .messages {
    height: 100%;
    background-color: #E0DAD6;
    background-repeat: no-repeat;
    background-size: cover;
  }
  .message-wrapper {
    margin-bottom: 9px;
    &: : after {
      content: "";
      display: table;
      clear: both;
    }
  }
  .message {
    display: inline-block;
    position: relative;
    max-width: 236px;
    border-radius: 7px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
    &.message-me {
      float: right;
      background-color: white;
      &: : before {
        right: -11px;
        background-image: url(/assets/message-me.png);
      }
    }
    &.message-you {
      float: left;
      background-color: blue;
      &: : before {
        left: -11px;
        background-image: url(/assets/message-you.png);
      }
    }
    &.message-you::before,
    &.message-me::before {
      content: "";
      position: absolute;
      bottom: 3px;
      width: 12px;
      height: 19px;
      background-position: 50% 50%;
      background-repeat: no-repeat;
      background-size: contain;
    }
    .message-content {
      padding: 5px 7px;
      word-wrap: break-word;
      &: : after {
        content: " \00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0";
        display: inline;
      }
    }
    .message-timestamp {
      position: absolute;
      bottom: 2px;
      right: 17px;
      font-size: 11px;
      color: gray;
    }
  }
}
<ion-content padding class="messages-page-content">
  <ion-scroll scrollY="true" class="messages">
    <ion-list>
      <ion-item class="message-item" *ngFor="let item of firelist | async">

{{item.message_text}}

             {{item.timestamp | amDateFormat: 'DD MMM YYYY  h:mm a'}}

      </ion-item>
    </ion-list>
  </ion-scroll>
</ion-content>

UPDATE
I did find if I changed overflow: hidden; below to overflow: visible; it fixes my problem. However, that's just in the browser, I am not sure how to change the css on ion-label in the code yet.
ion-label {
    display: block;
    overflow: hidden;
    -webkit-flex: 1;
    -ms-flex: 1;
    flex: 1;
    margin: 0;
    font-size: inherit;
    text-overflow: ellipsis;
    white-space: nowrap;
}

A: Just change the CSS of the ion-label in your CSS, just as you said in your question:
In your CSS file, do a search for ion-label, and when you find the block you show, change the line of code overflow: hidden; to overflow: visible;, so it looks like below:
ion-label {
    display: block;
    overflow: visible;
    -webkit-flex: 1;
    -ms-flex: 1;
    flex: 1;
    margin: 0;
    font-size: inherit;
    text-overflow: ellipsis;
    white-space: nowrap;
}

Or if you can't edit the CSS file, add this CSS either directly, or as a separate file:
ion-label {
    overflow: visible;
}


text:
Q: How to make a sequence in google sheets which has increments in regular intervals I want to create a sequence in google sheets where i have to make a sequence of this sort like if the sequence starts at 5000, it should be 5000 for the next 12 rows and then it should increment to 5500 and then it should go on for another 12 rows to be 5500. So basically it should increment by 10% after 12 rows and continue to do this.

A: =ArrayFormula(vlookup(quotient(sequence(Blocklength*Blocks,1,0),Blocklength),
{sequence(Blocks,1,0),Start*(1+Increment)^(sequence(Blocks,1,0))},2))

Comment
You don't actually need the vlookup, could go straight to the calculation, but with a power calculation in every row this might be slower:
=ArrayFormula(Start*(1+Increment)^quotient(sequence(Blocklength*Blocks,1,0),Blocklength))

A: I found this a bit tricky, maybe others have smoother answers. But one way is to use FV() function for a compound interest. With a combination of SEQUENCE() you can get the cumulative increase:

Formula in A1:
=INDEX(FLATTEN(SPLIT(REPT(FV(D3,SEQUENCE(D4),0,-(D1/(D3+1)))&"|",D2),"|",1)))

Or, without the FV() function, but with math and same concept:
=INDEX(FLATTEN(SPLIT(REPT(D1*(1+D3)^SEQUENCE(D4,1,0)&"|",D2),"|",1)))

Note: For reading purposes I set blocksize to 2 rows only.

A: Try, with B1=5000, B2=10%, B3=24 periods (288 values=24*12)
=arrayformula(sort(flatten(sequence(12,1,B1,0)*(1+B2)^(sequence(1,B3,0,1)))))


text:
Q: Find $a$ and $b$ that make the following function differentiable for all values of $x$ $$
f(x)=\left\{
\begin{array}{ll}
 b+a x & x>-1 \\
 b x^2-3 a x+4 & x\leq -1 \\
\end{array}
\right.
$$
How do I solve this question? I'm stuck and not sure how to start it up. I did the derivative using definition of the derivative but not sure what to do afterwards.

A: First of all the function must be continuous at $x=-1$
$$\lim_{x\to -1^-} \, f(x)=\lim_{x\to -1^+} \, f (x)$$
that is
$$b-a=b+3a+4\to a=-1$$
Now the derivative
$$
f'(x)=
\left\{
\begin{array}{ll}
 a & x>-1 \\
 2 b x-3 a & x\leq -1 \\
\end{array}
\right.
$$
To be differentiable the derivative must have the same value at $x=-1$ in both directions
for $x<-1$ we have $f'_{-}(-1)=-2b-3a$
and $f'_+(-1)=a$
the two values must be equal so we have
$-2b-3a=a\to b=-2a\to b=2$
The function is differentiable for $a=-1;\;b=2$


text:
Q: ul li css not working properly Got a strange issue:
In my .cshtml I have a second thing:

Test

Test2

Test3

Test4

Test5

Test6

Which supposed to work like this:
Test
Test2
     Test3
Test4
     Test5
     Test6

BUT instead of it, it works this way:
Test
Test2
Test3
Test4
Test5
Test6

The only thing I have in css for this is list-style: none;
Also main
 is placed inside of
 which have text-align: left; (without it, all items are centered).
I am a newbie speaking of css so, I can't get, what I am missing.
EDIT:
Forgot one thing. This works fine in jsfiddle.

A: Just reset all your styles and give
. You are using
 only for opening and closing it:

Test

Test2

Test3

Test4

Test5

Test6

Your Mistake

Test

Test2

Test3

Test4

Test5

Test6

Preview:

A: Just check this out...
OR
Provide the CSS you have used..

div {
  text-align: left;
}
ul {
  list-style: none;
}

Test

Test2

Test3

Test4

Test5

Test6

A: The solution that I came up with is that you should wrap your un-ordered list with div tag that has a class name. Ex.

HTML:

Test

Test2

Test3

Test4

Test5

Test6

CSS
.test ul li {
    list-style: none;
    text-align: left;
}

A: I guess this might be your issue.

*

*padding:0px;

*margin:0px;

ul li ul
{
    padding:0px;
}

Test

Test2

Test3

Test4

Test5

Test6

ANSWER

Note : So remove padding property from your ul CSS.

ul li ul
{
   /* padding:0px; REMOVE IT If It's 0PX' */
}

Test

Test2

Test3

Test4

Test5

Test6


text:
Q: How to pass custom param for creating access token and fetch it while validating token in Azure AD I am creating Bearer token from Azure AD using the following
URL - https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token
Request Method - POST
Payload -
{
"client_id": "",
"client_secret": "",
"scope: "",
"grant_type": "client_credentials"
}

This is generating access token as expected.
My requirement is I want to pass an extra param when generating token like "testId" (dynamic value) along with client id, secret, scope & grant_type while creating token and fetch the testId value when validating or verifying the token.
I tried adding a custom claim in azure portal and fetched it when validating but the limitation here is that we need to hard-code the value in azure portal.
Do we have any other way to complete my requirement?
Any help is much appreciated.


text:
Q: How to get new data from database (php) using ajax I am trying to get new content from database with php, here is the code:
<?php
if($row['permalink'] == $_GET['contents']){
?>

<?php echo $row['title']; ?>

<img style="" src="portfolio/<?php echo $row['first_img']; ?>.jpg">

<?php
}
}
?>

So that works fine. So if I click on  then that would change the above content. However, I am try to figure hour how to get the result with jquery so that I do not have to reload the page.
I have managed to come this far:
$("#thums").click(function(){
$.ajax({ url: 'index.php',
data: {permalink: 'listaker'},
type: 'get',
success: function(output) {
$('#workproject').html(output);
}
});
});

But this loads the entire page from the start. is there a way that I can only reload the workproject id only. Or any other way to get this to work
Thanks

A: Try this
$('#workproject').load('index.php?permalink=listaker #workproject');

instead of your $.ajax() code


text:
Q: How to run Python script in background in android? I want to run a specific Python file(for example, main.py) in android device even if my app is not running in the foreground using my android application made using Python, Kivy and Buildozer .

A: Did you try this?:
import subprocess
subprocess.call(['python main.py'])


text:
Q: I have Type Errors like only size-1 arrays can be converted to Python scalars When I tried to import complex number in my code I have the following error: only size-1 arrays can be converted to Python scalars.
import matplotlib.pyplot as plt
import numpy as np
import math
import os

# Create target Directory if don't exist

if not os.path.exists('Sparameters images'):
    os.mkdir('Sparameters images')

## UPLOAD DATA ##############################
#############################################

HB1 = np.loadtxt('S11_Magnitude\S11_Magnitude.txt',skiprows=7)
HB2 = np.loadtxt('S11_Phase\S11_Phase.txt',skiprows=7)
HB3 = np.loadtxt('S21_Magnitude\S12_Magnitude.txt',skiprows=7)
HB4 = np.loadtxt('S21_Phase\S12_Phase_Width.txt',skiprows=7)

## CONVERT DATA TO LINEAR MAGNITUDE AND RADS #####################
##################################################################

W1=HB1[:,0]
A_mag=np.power(10,HB1[:,1]/10)*100
W2=HB2[:,0]
A_Phase=HB2[:,1]
W3=HB3[:,0]
B_mag=np.power(10,HB3[:,1]/10)*100
W4=HB4[:,0]
B_Phase=HB4[:,1]

## CONVERTING INTO COMPLEX NUMBERS ##############################
#################################################################

S11 = [A_mag * math.cos(A_Phase)] + 1j * [A_mag * math.sin(A_Phase)]
S21 = [B_mag * math.cos(B_Phase)] + 1j * [B_mag * math.sin(B_Phase)]

I have tried many also this but it doesn't work
S11 = np.vectorize(complex)(A_mag * math.cos(A_Phase), A_mag * math.sin(A_Phase))
S21 = np.vectorize(complex)(B_mag * math.cos(B_Phase), B_mag * math.sin(B_Phase))

How can I overcome this issue?


text:
Q: display user profile image of chat sender in django-template All is working good except of the fact that, i am trying to display user profile images of user who sent a chat message in a chat room .
this is what my image patth prints "profilepics/images_g9LwcHF.jpg".
Note i am using django framework
<script>

  chatSocket.onmessage=function(e){
    var  tag_img=document.createElement('img');
    var get_user=document.querySelector('#user').value
    var tagname=document.createElement('li');
    var data =JSON.parse(e.data);

    document.querySelector('.img_tag').src=data.message.sender_img

</script>

Dom
<img class ="img_tag">

This is my consumer.py
        messaage_json={
          'user':me.username,
          'message':message_object.message,
          'sender':message_object.sender.username,
          'sender_img':str(message_object.sender.profilepicture),
          'created':str(message_object.created)
        }

        #coverting data to string
        myResponse={
          "message":messaage_json,

        }
        #broad cast the message event to be send
        # in the layaer
        await self.channel_layer.group_send(
            self.room_group_name,{
                # call the chat_message method
                "type":"chat_message",
                #covert string data to json objects
                "text":json.dumps(myResponse),

            }
        )

It prints out the user profile image path in the media file, but cannot display the image using javascript.
Note i am using django .

A: I do not see you actually injecting the newly created image DOM-node into the DOM, e.g. somewhere you would need to do that for the image to be displayed:
chatSocket.onmessage=function(e){

var data =JSON.parse(e.data);

var tag_img=document.createElement('img');
tag_img.src = data.message.sender_img;

document.querySelector('.img_tag').appendChild(tag_img);

A: yes i solved the problem . To display the image path, since all uploaded images are stored in django media file , i am to use the following bellow
tag_img.src = '/'+'media'+'/'+ data.message.sender_img;


text:
Q: Difflib SequenceMatcher - how to determine 'equal' for similarity of more than one char? I wrote a Python module that diffs between two HTML source codes.
I have a little problem to compare the text - the difflib.SequenceMatcher function determines text as 'equal' even if only one character if similar.
So genereted values like "123456" and "abc1de" will categorized as inserted "abc", equals on 1=1 and replaced 23456 in de.
In conclusion, how can I determine that the 'equal' classification will be set only if the equal length will be more than 3 chars?


text:
Q: correct kernel call in case of using dynamic shared memory allocation developers,
may someone give me a hint please?
I didn't find any information about how to allocate constant and dynamic shared memory in the same kernel, or lets ask more preciously:
How to call a kernel where the amount of shared memory that needs to allocated is just partly known at compilation time?
Referring to allocating shared memory for example, it becomes pretty obvious how to do for dynamic allocation.
But lets assume I have the following kernel:
__global__ void MyKernel(int Float4ArrSize, int FloatArrSize)
{
  __shared__ float Arr1[256];
  __shared__ char  Arr2[256];
  extern __shared_ float DynamArr[];
  float4* DynamArr1 = (float4*) DynamArr;
  float* DynamArr = (float*) &DynamArr1[Float4ArrSize];

  // do something
}

Kernel Call:
int SharedMemorySize = Float4ArrSize + FloatArrSize;

SubstractKernel<<< numBlocks, threadsPerBlock, SharedMemorySize, stream>>>(Float4ArrSize, FloatArrSize)

I'm actually wasn't able to figure out how the compiler is linking the size a shared memory only to the part I want to allocate dynamically.
Or does the parameter "SharedMemeorySize" represents the total amount of shared memory per block, so I need to calculate in the size of constant memory (int SharedMemorySize = Float4ArrSize + FloatArrSize + 256*sizeof(float)+ 256*sizeof(char)) ?
Please enlighten me or just simply point to some code snippets.
Thanks a lot in advance.
cheers greg

A: Citing programing guide, SharedMemorySize specifies the number of bytes in shared memory that is dynamically allocated per block for this call in addition to the statically allocated memory; this dynamically allocated memory is used by any of the
variables declared as an external array. SharedMemorySize is an optional argument which defaults to 0.
So if I understand what you want to do, it should probably look like
extern __shared_ float DynamArr[];
float*  DynamArr1 = DynamArr;
float4* DynamArr2 = (float4*) &DynamArr[DynamArr1_size];

Be aware, I didn't test it.
Here is very useful post.

A: From the CUDA programming guide:

The [kernel's] execution configuration is specified by inserting an expression of
  the form <<< Dg, Db, Ns, S >>> between the function name and the
  parenthesized argument list, where:

*

*Ns is of type size_t and specifies    the number of bytes in shared memory that is dynamically allocated    per block for this call in
  addition to the statically allocated    memory; this dynamically
  allocated memory is used by any of the    variables declared as an
  external array as mentioned in __shared__;    Ns is an optional
  argument which defaults to 0;

So basically, the shared memory size that you specify during the kernel call is related to the dinamically allocated shared memory. You don't have to manually add the size of your statically allocated arrays in shared memory.


text:
Q: What is the difference between using jQuery and it's alias ($)? When using Jquery a syntax error occured. What is the difference between the two
   $.ajax({
   //working
   });
   Jquery.ajax({
   //not work
   });

A: $ is just an alias/shortcut for the formal name jQuery. This was done by jQuery to reduce the weight of scripts that would depend on the library.
you have misspelled the library identifier in your example:
 //Your Example
 JQuery.ajax({
 });

 //What it should look like
 jQuery.ajax({
 });

The 2nd code above should work fine like
 $.ajax({
 });

if in case the dollar sign ($) is also used by other libraries. You can use the jQuery.noConflict(); to give way to other libaries.

A: The correct name is jQuery, not Jquery. jQuery and $ are the same thing. $ is just a shortcut. Please read the documentation to get more information about how to properly use jQuery - https://api.jquery.com/

A: As the others already point out the problem:-
jQuery, not Jquery .
The below code from jQuery Source Code will show you how jQuery sets $ as alias or shortcut. And what happens when jQuery.noConflict is called.
http://code.jquery.com/jquery-2.1.4.js
var
    // Map over jQuery in case of overwrite
    _jQuery = window.jQuery,

    // Map over the $ in case of overwrite
    _$ = window.$;

jQuery.noConflict = function( deep ) {
    if ( window.$ === jQuery ) {
        window.$ = _$;
    }

    if ( deep && window.jQuery === jQuery ) {
        window.jQuery = _jQuery;
    }

    return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
    window.jQuery = window.$ = jQuery;
}

For learning jQuery refer to :-

*

*https://api.jquery.com/

*http://learn.jquery.com/


text:
Q: RStudio: keeping special characters in a script I wrote a script with German special characters e.g. ü.
 However, whenever I close R and reopen the script the characters are substituted:
Before "für"; "hinzufügen"; "Ø" - After "für"; "hinzufügen"; "Ã".
I tried to remedy it using save with encoding and choosing UTF-8 as it is stated here but it did not work.
What am I missing?

A: You don't say what OS you're using, but this kind of thing really only happens on Windows nowadays, so I'll assume that.
The problem is that Windows has a local encoding that is not UTF-8.  It is commonly something like Latin1 in English-speaking countries.  I'm not sure what encoding people use in German-speaking countries, if that's where you are.  From the junk you saw, it looks as though you saved the file in UTF-8, then read it using your local encoding.  The encodings for writing and reading have to match if you want things to work.
In RStudio you can try "Reopen with encoding..." and specify UTF-8, and you'll probably get your original back, as long as you haven't saved it after the bad read.  If you did that, you've got a much harder cleanup to do.


text:
Q: How to change sub controls style in a Tab of TabPane using css I wanna create a TabPane with some Tabs. If a tab is selected, it shows an image (in the header, not the content), but others will not show the image.
I use the setGraphic method to add an Image, here is my code:
       TabPane tabpane = new TabPane();

        Tab tab = new Tab();
        tab.getStyleClass().add("ctab");

        Label value = new Label();
        value.getStyleClass().add("va");
        tab.setGraphic(value);

        tabpane.getTabs().add(tab);

Then I write the css to set its style:
.va {
    -fx-pref-width: 120;
    -fx-pref-height: 42;
    -fx-font-size: 10pt;
    -fx-text-fill: black;
}

.ctab:selected>.va {
    -fx-pref-width: 120;
    -fx-pref-height: 42;
    -fx-background-image: url("background.jpg");
    -fx-font-size: 10pt;
    -fx-text-fill: black;
}

The tab is selected, but the image is not shown.
I'm so confused about it. Because when the image is in a button, the css works.
    Button button= new Button("a");

    button.getStyleClass().add("abtn");

    Label value = new Label("b");
    value.getStyleClass().add("value");

    Label nest = new Label("s");
    nest.getStyleClass().add("nest");

    value.setGraphic(nest);
    button.setGraphic(value);

    root.getChildren().add(button);

and the css is:
.abtn {
    -fx-pref-width: 120;
    -fx-pref-height: 42;

    -fx-font-size: 11pt;
    -fx-text-fill: black;
}

.value {
    -fx-pref-width: 120;
    -fx-pref-height: 42;
    -fx-background-color: #ffffff;
    -fx-font-size: 10pt;
    -fx-text-fill: black;
}

.abtn:hover > .value > .nest {
    -fx-pref-width: 120;
    -fx-pref-height: 42;

    -fx-font-size: 20pt;
    -fx-text-fill: black;

    -fx-background-color: transparent;
}

When the mouse hover the button, the String "s" size is really changes.
What's the difference between two example? How can I make the tab's image change(use css)?

A: Your Label is not owned by the Tab directly. Try it out:
.ctab:selected > .tab-container > .tab-label > .va

As you can see, setGraphic is not always intended to set a child node.
JavaFX CSS Reference Guide helps you to figure out the structure of controls, but it doesn't have complete list of nodes (for example, TabPane's tab-container is not in the list).
To analyze the scene graph structure, CSS Analyzer in Scene Builder and ScenicView are useful.

Or simply the selector below also works.
.ctab:selected .va


text:
Q: Attachments QGIS I was wondering if there in QGIS is a good tool for adding attachments to different layers. I have previously worked a lot with ArcMap and it has great attachment facilities. I haven't so far been able to find the same functionality in QGIS.
I have looked a bit on photo2kmz, but it only works with photos (I would also like to attach pdf files and/or word documents) and as I understand it it creates a new feature each time (I wish to attach photos and documents to existing features).
I have also looked at the possibility of making fields in attribute tables as "External resource" format, but here I only get the possibility of storing a path, that is not "click-able" so that I have to afterwards copy paste it into Windows Explorer.
Perhaps someone has a better solution for attaching photos, pdfs etc. to already existing layers preferably in a MSSQL environment.

A: You document path is clickable if you use the action tool.

If you press the Add default action button, you get a sample of action. Try the Open file action where PATH is the column name of the field containing the path.


text:
Q: Intent without context I have an intent thats designed to be a POSSIBLE follow up intent. I don't want to assign it as a follow up because I want it to be used as an entry point. So for my parameters I assign the default value to the value passed in by the context.
And that works! As a follow up it works great and the context is passed through. However when I try any of the phrases without the context it goes to the "Default Fallback Intent."
Am I missing anything here?

A: I figured it out, I can leave the input context in Dialogflow blank and assign the value context as a default value of a parameter. As long as the context has been created from a previous intent it's all good. Now if you have a context it will use the context as a parameter, and if not it will you can prompt the user for a parameter. (Which you should export)


text:
Q: MySQL Case Statement based off of a count of records I am trying to make a MySQL statement that uses a CASE statement that takes a COUNT of records and then displays a column with information based on that. I am using the Sakila Database. This is what I have so far
SELECT *,
CASE(
SELECT count(*) FROM  sakila.film_actor fa
WHERE fa.actor_id = a.actor_id)
WHEN 20 THEN 'Newcomer'
WHEN 30 THEN 'Prolific Actor'
ELSE 'Hollywood Star'
END actor_level

FROM sakila.film_actor fa
JOIN actor a ON fa.actor_id = a.actor_id

This works but I need it to be on a scale so
0-20 is Newcomer
21-30 is Prolific Actor
30+ is Hollywood Star

A: Since you are using mysql,then we can use IF() function to do it
SELECT
   IF(a.cnt <= 20,'Newcomer',a.cnt > 20 and a.cnt <= 30,'Prolific Actor','Hollywood Star')
     AS actor_level
  FROM
  (
    SELECT count(*) as cnt
     FROM  sakila.film_actor fa
    WHERE fa.actor_id = a.actor_id
  ) a


text:
Q: Django-haystack form validation I have a search view on my application build on django-haystack. It works fine.
from haystack.forms import SearchForm
from haystack.query import SearchQuerySet
from haystack.views import SearchView

class SearchView(SearchView):
    sqs = SearchQuerySet().filter(lang=get_language())
    template = "search/search.html"
    searchqueryset = sqs
    results_per_page=10
    form_class=SearchForm

I want to add a custom validation to this view to set minimum input value. What is the most appropriate way to do that?
Thanks.

A: Validation is a part of form behavior, so you need to create successor of SearchForm and add custom validation there. There is example in docs.


text:
Q: Android Handler - not working properly I want to create a dialogBuilder with a text field and a button on it. The idea is to make the program wait for any further actions until the text in the field is entered and the OK button is clicked. Below is the code:
private static final Object wait = new int[0];
private static String result = null;

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

    Handler h = new Handler();
    final Context context = MainActivity.this;
    h.post(new Runnable() {

        public void run() {
            final Builder dialogBuilder = new AlertDialog.Builder(context);
            dialogBuilder.setTitle(R.string.app_name);
            final LinearLayout panel = new LinearLayout(context);
            panel.setOrientation(LinearLayout.VERTICAL);
            final TextView label = new TextView(context);
            label.setId(1);
            label.setText(R.string.app_name);
            panel.addView(label);

            final EditText input = new EditText(context);
            input.setId(2);
            input.setSingleLine();
            input.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_URI
                    | InputType.TYPE_TEXT_VARIATION_PHONETIC);
            final ScrollView view = new ScrollView(context);
            panel.addView(input);
            view.addView(panel);

            dialogBuilder
                    .setCancelable(true)
                    .setPositiveButton(R.string.app_name,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    result = input.getText().toString();

                                    synchronized (wait) {
                                        wait.notifyAll();
                                    }

                                    dialog.dismiss();
                                }
                            }).setView(view);

            dialogBuilder.setOnCancelListener(new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    result = null;
                    synchronized (wait) {
                        wait.notifyAll();
                    }
                }
            });
            dialogBuilder.create().show();
        }

    });

    String localResult = null;
    try {
        synchronized (wait) {
            Log.d("Waiting", "Waiting " + localResult);
            wait.wait();
        }
        localResult = result;
        result = null;
        if (localResult == null) {
            // user is requesting cancel
            throw new RuntimeException("Cancelled by user");
        }
        Log.d("RESULT ", "RESULT " + localResult);
    } catch (InterruptedException e) {
        localResult = result;
        result = null;

        if (localResult == null) {
            // user is requesting cancel
            Log.d("CANCELED ", "CANCELED " + localResult);
            throw new RuntimeException("Cancelled by user");
        }
    }
    Log.d("RESULT AFTER THE DIALOG", "RESULT AFTER THE DIALOG " + result);
}

The program is going to Log.d("Waiting", "Waiting " + localResult); and after that just waiting. NO DIALOG BUILDER IS SHOWN on the activity window. I used the debug mode and saw that the program flow is not entering the run() method, but the value of the Handler.post() is true. And for this reason the dialog is not shown, and the program is waiting.
I have tried to remove the moment with waiting (remove the Handler.post()), just to see if the dialog will show, and it showed and all moved well, but the result was not I am needing - I want the program to wait the input from the dialog ... I am really out of ideas.
Would you please give me some suggestions as I am really out of ideas.
Thanks a lot!

A: Handlers don't run in a separate thread. So when you call wait() :
    synchronized (wait) {
        Log.d("Waiting", "Waiting " + localResult);
        wait.wait();
    }

It waits indefinitely since the handler runs on the same thread as the current thread. Your Runnable can only be executed after the onCreate() method finishes but this will never happen because you just called wait().
You should reconsider your idea and find a workaround (for example, show the dialog the usual way and disable the "OK" button as long as the user does not enter a valid text). But calling wait() on the UI thread cannot go well.

A: You should be running the display of the Dialog in the UI Thread, not a seperate thread.
An example would be something like this:
In the onCreate()
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // Display progress dialog when loading contacts
                            dialog = new ProgressDialog(this);
                            // continue with config of Dialog
                        }
                    });

                        // Execute the Asynchronus Task
                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                // code to execute in background
                                return null;
                            }
                            @Override
                            protected void onPostExecute(Void result) {
                                // Dismiss the dialog after inBackground is done
                                if (dialog != null)
                                    dialog.dismiss();

                                super.onPostExecute(result);
                            }

                        }.execute((Void[]) null);

Specifically what is happening here is the Dialog is being displayed on the UI thread and then the AsyncTask is executing in the background while the Dialog is running. Then at the end of the execution we dismiss the dialog.


text:
Q: Why do I get a duplicated entry in my Windows manifest? The following manifest is added to my .exe.:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <ms_asmv2:trustInfo xmlns:ms_asmv2="urn:schemas-microsoft-com:asm.v2">
        <ms_asmv2:security>
            <ms_asmv2:requestedPrivileges>
                <ms_asmv2:requestedExecutionLevel level="asInvoker" />
            </ms_asmv2:requestedPrivileges>
        </ms_asmv2:security>
    </ms_asmv2:trustInfo>
  <asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
    <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
      <dpiAware>true</dpiAware>
    </asmv3:windowsSettings>
  </asmv3:application>
</assembly>

but when I view the manifest (for example using Kenny Kerr's Manifest View) the application, windowsSettings and dpiAware tags are seemingly duplicated:
 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
... general properties ...
     <asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
        <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
          <dpiAware>true</dpiAware>
        </asmv3:windowsSettings>
     </asmv3:application>
     <asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
         <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
          <dpiAware>true</dpiAware>
         </asmv3:windowsSettings>
     </asmv3:application>
  </assembly>

Any idea why this happens, and would it cause any problems?

A: After doing an awful lot of experiments and trying various versions of mt.exe to embed the manifest as suggested on some sites, I noticed a pattern; in all the samples I saw, the manifest filename seemed to always match the project or executable name, but with a '.manifest' appended.
My manifest filename did not totally match, so I rename it to match the Visual Studio project name for my application. I also changed the 'Additional Manifest Files' option in the Manifest Tool properties to, '$(ProjectDir)$(ProjectName).manifest', rather than my previous hardcoded filename.
Together, these changes worked and provided me with an executable with a correctly embedded manifest.


text:
Q: php WITH ROLLUP for two tables For a local non-profit org, I'm attempting to summarize donation totals using two MySQL tables: donations and donors. So far, I have this working correctly:
SELECT SUM(amount) AS total, donor_id FROM donations
GROUP BY donor_id WITH ROLLUP

What I can't figure out is how to present the donor's name (donors.last_name) in the query.
In other queries, I have used WHERE donations.donor_id = donors.donor_id, but that doesn't seem to work in this case. Also, I'd like the results to show the 'total' column in descending order if possible.
Your suggestions are much appreciated. Thanks!


text:
Q: Network communication between Windows + WSL2 + Docker I have a web app hosted in a Docker container and exposes port 5050 that is mapped to port 80 of the container.
The web app listens on 0.0.0.0:5050.
The Docker engine runs on WSL2.
Now when I open a browser on Windows and go to http://localhost:5050, everything works and I can see the web app.
But I don't understand how the request can reach the Docker container when I navigate to localhost on Windows.
Any ideas ?

A: The reason is that Docker for Windows uses a WSL2 backend, and is integrated with WSL distros.


text:
Q: SmbFileOutputStream write creating corrupted jpg files I'm using JCIFS SmbFileOutputStream write to upload jpg (and mp4) files to a share on a local Windows network. While this works well most of the time, I sometimes find that the resulting files are corrupt - e.g. if it's a jpg perhaps only the top part of the photo will be legible/visible.
I have the upload in a try/catch block, but it is not throwing an exception. Is there any way that I can verify that a file has been uploaded correctly?
try {
    if (debugging_on) {
        logger.info("UploadService.011 UploadFiles: uploading file:" + destFileName);
    }
    SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
    FileInputStream fileInputStream = new FileInputStream(new File(
            sSourceFilePath));
    byte[] buf = new byte[16 * 1024 * 1024];
    int len;
    while ((len = fileInputStream.read(buf)) > 0) {
        sfos.write(buf, 0, len);
    }
    fileInputStream.close();
    sfos.close();
    // Update the database to include the date/time of this upload
    millisStart = Calendar.getInstance().getTimeInMillis();
    sql = "UPDATE upload_history SET file_uploaded_date = "
            + millisStart + " WHERE filename = '" + filename + "'";
    db.execSQL(sql);

} catch (Exception e) {
    mNotifyBuilder.setContentText("Upload error - check folder permissions");
    mNotificationManager.notify(1, mNotifyBuilder.build());
    return "WriteFailure";

A: sfos.close();

needs to go before
fileInputStream.close();

Close the output before you close the input,
Adding 'sfos.flush()' couldn't hurt.


text:
Q: Configuration.GetSection returns a ConfigurationSection that doesn't exists in the file I'm working with a .NET Framework application that contains lines like these:
var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
Console.WriteLine(configuration.FilePath);
var mySettings = (MySettings) configuration.GetSection("MySettings");

It prints the following path:
C:\Users\Daniel Jonsson\AppData\Local\MyCompany\MyApp.exe_Url_ib5gv4f20ng5kujpcanm3fusbnakfvor\1.0.0.0\user.config

However, that file doesn't contain a section MySettings. Instead, the MySettings section that is being read is found in program's .config file in C:\code\MyCompany\MyApp\bin\Debug\MyApp.exe.config.
Is there some sort inheritance between the configuration files that control this behavior? Or why does it behave like this? I would like it to read whatever is in the user.config file.

A: Apparently the Configuration class represents a merged view of the configuration settings from all of the configuration files, according to this source:

Configuration settings are stored in a hierarchy of configuration files. The Configuration class instance represents the merged view of the configuration settings from all of the configuration files that apply to a specific physical entity, such as a computer, or to a logical entity, such as an application or a Web site. The logical entity can exist on the local computer or on a remote server. For information about configuration files, see Configuring Apps and ASP.NET Configuration Files.

The hierarchy is as follows, according to this source:

Machine.config > [AppName.exe.config] > Roaming.config > User.config

When using ConfigurationUserLevel.PerUserRoamingAndLocal, it will merge all of those levels, according to this section of the previous source:

Remember that configuration is hierarchical and merged. When requesting roaming or local user configuration, that level up through machine.config are merged, resulting in the complete configuration accessible by your application for the given user level. An interesting consequence of this merging allows you to request roaming or local user configuration even when the User.config file does not exist. The Configuration object returned will contain a FilePath that does not exist and the HasFile property will be false. Any sections defined in higher configuration levels will still be accessible though and with the proper allowances, changes to those sections can be saved. Saving changes at a level that previously did not exist will create the appropriate User.config file.


text:
Q: Javascript - emulating chrome-debugger's element highlighting I wonder if anyone has ever done something like that -
I would like to be able to emulate the ability of chrome debugger (or any other browser debugger) to highlight a rendered element by hovering/selecting its code equivalent element.
for example, I have the following layout:

the top part is an iframe element which renders a sample HTML page, and the bottom part is an embedded in-browser code editor (ace), which displays the HTML code of the iframe's contents. I would like to be able to highlight an HTML element inside the iframe by hovering its corresponding HTML code element in the code editor.
Does anyone have any idea how to achieve something like that? I would like to hear some interesting directions.
Thanks!

A: I thought

Inspect element

in Google Chrome could do the job
How to use Inspect Element
Right click on any website and click the last one Inspect element (and wait for a while).
Then the developer tools is going to popup with html. You can hover the mouse on those code in developer tools and it would highlight the website element as you hover and those color which highlight is different for indicate padding, margin and element itself.
More than those function you also do a lot with chrome developer tools such as editing styles and DOM, check your CSS class, check your size
For further information
This is official site.
If you want to reverse Chrome
Chrome DevTools App


text:
Q: Typescript issue with dynamic keys in object referencing react components Typescript complains that expression of type 'string' can't be used to index '{ bg: OverridableComponent<SvgIconTypeMap<{}, "svg">>; de: OverridableComponent<SvgIconTypeMap<{}, "svg">>; ... 7 more ...; tr: OverridableComponent<...>; }'
How should we proceed in such a case?
import {
  BulgariaFlag,
  FranceFlag,
  GermanyFlag,
  GreatBritainFlag,
  GreeceFlag,
  ItalyFlag,
  RomaniaFlag,
  RussiaFlag,
  SpainFlag,
  TurkeyFlag,
} from "../Icon";

const flagIcons = {
  bg: BulgariaFlag,
  de: GermanyFlag,
  en: GreatBritainFlag,
  es: SpainFlag,
  fr: FranceFlag,
  gr: GreeceFlag,
  it: ItalyFlag,
  ro: RomaniaFlag,
  ru: RussiaFlag,
  tr: TurkeyFlag,
};

const EmployeeItem: React.FC<{ company: Company; employee: User }> = ({
  company,
  employee,
}) => {
 return
   <span>
              {employee.spokenLanguages.map((spokenLanguage) => {
                const FlagIcon = flagIcons[spokenLanguage];

                  <FlagIcon
                    key={spokenLanguage}
                    viewBox="0 0 48 48"
                    titleAccess={t(`fields.spokenLanguages.${spokenLanguage}`)}
                  />
              })}
            </span>
};

export default EmployeeItem;

A: This means that User.spokenLanguages is array of string whereas it should really be array of "bg" | "de" | ... | "ru" | "tr". You have three solutions

*

*Change User.spokenLanguages to be of type ("bg" | "de" | ... | "ru" | "tr")[] instead of string[]

*When rendering, check if language is a valid key of flagIcons using a type guard

const isValidLanguage = (str: string): str is keyof typeof flagIcons => str in flagIcons

{employee.spokenLanguages.map(language => {
  if(!isValidLanguage(language)) return null

  const FlagIcon = flagIcons[language]
  return ...
})}
}

*Use const flagIcon: Record<string, ComponentType<TypeOfPropsOfYourIcons> = {...}. Please consider not doing this, as it can cause runtime errors if language is some string that is not in flagIcon.


text:
Q: CORS header 'Access-Control-Allow-Origin' missing for json POST using API Installed fruitcake/laravel-cors on Laravel 5.8
My testserver uses php artisan serve on 127.0.0.1:8000 using routes/api.php
client (nuxt) is running on 127.0.0.1:3000
I'm able to send data to the server using the POSTMAN tool
I've configured fruitcake/laravel-cors
protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

and config/cors.php
<?php

return [

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => [],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];

Still getting:

Access to XMLHttpRequest at
  'http://127.0.0.1:8000/api/customerFeedbackStore' from origin
  'http://127.0.0.1:3000' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

in browser.

A: It seems Cors was configured correctly but var_dump() and dd() before the return triggered the message anyway. Also not returning anything causes the cors message..
        var_dump($request);
        dd($request);

return with a json response (as I'm using Json) worked fine.  (any other return suggestions?)
        return response()->json([
            'data-received' => true
        ]);

A: 'paths' must not be empty. You should at least se it to [ '*' ], so it covers every request.


text:
Q: How to generate an object that has all the Properties of another, only Nullable (when applicable)? I am creating a project that will manage app configurations. It will be very generic, reusable across different apps (with different config models on each) and very flexible - including the ability to create/save/store/read/merge partial configurations from multiple sources.
Without getting too much into details, here's an example of what I need to do.
I have a class like below:
public class TestConfigModel
{
    public int SomeIntValue { get; set; }
    public string SomeStringValue { get; set; }
    public TestConfigSubsection Subsection { get; set; }
}

public class TestConfigSubsection
{
    public System.DayOfWeek SomeSubsectionEnumValue { get; set; }
    public Guid SomeSubsectionGuidValue { get; set; }
}

I need to dynamically generate a version of this model that has all properties nullable (unless they already take a null):
public class TestConfigModelNullable
{
    public int? SomeIntValue { get; set; }
    public string SomeStringValue { get; set; } // already takes a null
    public TestConfigSubsection Subsection { get; set; } // already takes a null
}

public class TestConfigSubsectionNullable
{
    public System.DayOfWeek? SomeSubsectionEnumValue { get; set; }
    public Guid? SomeSubsectionGuidValue { get; set; }
}

Example use:
I have a default (complete) config like so:
var aConfigInstance = new TestConfigModel()
{
    SomeIntValue = 3,
    SomeStringValue = "hey",
    Subsection = new TestConfigSubsection()
    {
        SomeSubsectionEnumValue = DayOfWeek.Thursday,
        SomeSubsectionGuidValue = Guid.Parse("{2C475019-5AAC-43C6-AC87-21947A40E3B7}")
    }
};

Now, I need to be able to create, serialize, store and later deserialize and operate on a partial configuration model, like below:
var aPartialConfigInstance = new TestConfigModelNullable()
{
    SomeIntValue = 4,
    Subsection = new TestConfigSubsection()
    {
        SomeSubsectionEnumValue = DayOfWeek.Monday
    }
};

... with all missing properties null. If I try to do the same with the original class, all the other non-nullable fields will receive default values and that would be bad (how do I tell if int value of 0 is intended or not? Maybe it makes sense for the consumer app).
However, I'm new to reflection in general and not sure how to approach this. Your help would be much appreciated :)
Recall that we don't know the model ahead of time.

A: I happened to implement several similar mechanisms in several different flavors. Implementing an "automagical" mechanism implies quite a bit of heavy lifting.
Here I wouldn't suggest generating separate nullable versions of the models. Instead, I would opt for making all model properties Optional<T>, which is like Nullable<T> but works for reference types as well. In this way, partial models will be represented with the same types as "base" models.
Such an approach will save the complexity of code generation (T4, Roslyn, CodeDom, or Reflection.Emit -- all these imply a lot of effort, including plugging them into the build process).
In addition, in either approach, a "merging" logic must be implemented which applies a partial model over a "base" one. In code generation approach, the merge logic can be generated as part of the nullable models. In Optional<T> approach, it can be either hard-coded or implemented in generic way with runtime Reflection (not Reflection.Emit). The hard-coded way appears to be the easiest, but for large number of models and properties, runtime Reflection may be a better fit.
How it will look
The models would look like this:
public class TestConfigModel
{
    public Optional<int> SomeIntValue { get; set; }
    public Optional<string> SomeStringValue { get; set; }
    public Optional<TestConfigSubsection> Subsection { get; set; }
}

With the implicit conversion operators of Optional<T>, you'll be able to initialize section values as normally:
var config = new TestConfigModel {
    SomeIntValue = 123,
    SomeStringValue = "ABC",
    Subsection = new TestConfigSubsection {
        SomeSubsectionEnumValue = DayOfWeek.Thursday
    }
};

Generic merging logic can be implemented by introducing an Apply method to Optional<T>:
Optional<T> Apply(Optional<T> partial, Func<T, T, Optional<T>> merge = null)

Every model will have to implement its own ApplyXxxx() method that will be passed in the merge parameter, like this:
public class TestConfigModel
{
    // ...properties

    public Optional<TestConfigModel> ApplyModel(TestConfigModel partial)
    {
        SomeIntValue = SomeIntValue.Apply(partial.SomeIntValue);
        SomeStringValue = SomeStringValue.Apply(partial.SomeStringValue);
        Subsection = Subsection.Apply(
            partial.Subsection,
            merge: (left, right) => left.ApplySubsection(right));
        return this;
    }
}

public class TestConfigSubsection
{
    // ...properties

    public Optional<TestConfigSubsection> ApplySubsection(TestConfigSubsection partial)
    {
        SomeSubsectionEnumValue = SomeSubsectionEnumValue.Apply(partial.SomeSubsectionEnumValue);
        SomeSubsectionGuidValue = SomeSubsectionGuidValue.Apply(partial.SomeSubsectionGuidValue);
        return this;
    }
}

Optional<T>
Built-in implementation of Optional<T> is planned for C# 8, but it can be  implemented easily (mostly similar to Nullable<T>).
public interface IOptional
{
    bool HasValue { get; }
    object Value { get; }
}
public struct Optional<T> : IOptional
{
    private readonly bool _hasValue;
    private readonly T _value;

    public Optional(T value)
    {
        _value = value;
        _hasValue = true;
    }

    public bool HasValue => _hasValue;
    object IOptional.Value => Value;

    public T Value
    {
        get
        {
            if (!_hasValue)
            {
                throw new InvalidOperationException("has no value");
            }
            return _value;
        }
    }

    public T GetValueOrDefault() => _value;

    public T GetValueOrDefault(T defaultValue)
    {
        if (!_hasValue)
        {
            return defaultValue;
        }

        return _value;
    }

    public bool IsNullValue => _hasValue && ReferenceEquals(_value, null);

    public override bool Equals(object other)
    {
        if (other is Optional<T> otherOptional)
        {
            if (_hasValue != otherOptional.HasValue)
            {
                return false;
            }

            if (_hasValue)
            {
                return CompareValue(otherOptional.Value);
            }

            return true;
        }

        return false;
    }

    bool CompareValue(object otherValue)
    {
        if (_value == null)
        {
            return (otherValue == null);
        }

        return _value.Equals(otherValue);
    }

    public override int GetHashCode()
    {
        if (_hasValue || ReferenceEquals(_value, null))
        {
            return 0;
        }

        return _value.GetHashCode();
    }

    public override string ToString()
    {
        if (!_hasValue || ReferenceEquals(_value, null))
        {
            return "";
        }

        return _value.ToString();
    }

    public Optional<T> Apply(Optional<T> partial, Func<T, T, Optional<T>> merge = null)
    {
        if (!_hasValue && partial.HasValue)
        {
            return partial;
        }

        if (_hasValue && partial.HasValue)
        {
            if (ReferenceEquals(_value, null))
            {
                return partial.Value;
            }

            if (!ReferenceEquals(partial.Value, null))
            {
                if (merge != null)
                {
                    return merge(_value, partial.Value);
                }

                throw new InvalidOperationException("both values exist and merge not provided");
            }
        }

        return this;
    }

    public static implicit operator Optional<T>(T value)
    {
        return new Optional<T>(value);
    }

    public static explicit operator T(Optional<T> value)
    {
        return value.Value;
    }
}

Serialization
The last thing left is to teach the serializers to handle Optional<T>. For instance, Newtonsoft.Json would require a custom JsonConverter. Below isn't a complete implementation, but it demonstrates the approach:
public class OptionalConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Optional<>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // TODO: implement properly
        // roughly the approach is like this:

        var hasValue = reader.ReadAsBoolean().GetValueOrDefault();
        var innerValue = hasValue
            ? serializer.Deserialize(reader, objectType.GetGenericArguments([0])
            : null;

        return Activator.CreateInstance(
            objectType,
            innerValue != null ? new[] {innerValue} : new object[0]);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is IOptional optional)
        {
            // TODO: implement writing
        }
    }
}

A: // Just for convenience
public Type CreateNullableTypeFrom<T>()
{
  return CreateNullableTypeFrom(typeof(T));
}

public Type CreateNullableTypeFrom(Type typeToConvert)
{
  // Get the AssemblyName where the type is defined
  AssemblyName assembly = typeToConvert.Assembly.GetName();
  AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.Run);
  ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule(assembly.Name);
  TypeBuilder typeBuilder = dynamicModule.DefineType(typeToConvert.Name + "Nullable");

  // Loop through the properties
  foreach(PropertyInfo property in typeToConvert.GetProperties())
  {
    // If property is value type, it can't be null
    if(property.PropertyType.IsValueType)
    {
      // Create a nullable type for the property
      typeBuilder.DefineProperty(property.Name, property.Attributes, typeof(Nullable<>).MakeGenericType(property.PropertyType), Type.EmptyTypes);
    }
    // The property can be null
    else
    {
      // Create a similar property
      typeBuilder.DefineProperty(property.Name, property.Attributes, property.PropertyType, Type.EmptyTypes);
    }
  }

  // Finally, create the type
  Type convertedType = typeBuilder.CreateType();
  Console.WriteLine(convertedType.Name);
  // Note: to access the properties of the converted type through reflection,
  //       use GetRuntimeProperties method, not GetProperties, since GetProperties
  //       will return an empty array because the type was created an runtime

  return convertedType;
}


text:
Q: Why searching for relatedVideos not returning nextPageToken for pagination?Any help is appreciated When using https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&relatedToVideoId=HZsRjrYW-lk&maxResults=10&key=${key} the response doesnt contain nextPageToken even though the number of results are more than the no of items returns
I tried increasing the maxResults to check if there are more results and using maxResults for pagination but i dont think its the best way to get 40 results and return last 10 result for example :-
1st page :- currentPage = 0 ;maxResult=currentPage+10;return items[maxResult-10]---items[maxResult]
so for 1st page currenPage = 0 ,maxResult = 10,return : items[0]--items[10]
2nd page :- currentPage = 10 ;maxResutl = currentPage+10 ;return items[maxResult-10]--items[maxResult]
so for 2nd page currenPage = 10 ;maxResult = 20 ;retrn items[10]--items[20]
..and so on
but the problem is that i need to get all the vidoes and then cut the part i dont need


text:
Q: Selenium webDriver/Maven java tests on Jenkins not able to communicate with firefox I'm trying to use jenkins to create automated regression tests for a web app. Jenkins basically fetches my maven project from git and reads the pom.xml. Then the test suite is started. The problem is that my tests are using selenium web driver in combination with gekodriver in order to launch firefox and navigate on the website. But everytime I launch the tests I get those errors:
Console logs

I'm running Jenkins as a service (it's how it was launched after installation) and my tests work fine when ran through eclipse or java. So I think the problem comes from how the jenkins handles selenium webdriver.
As you can probably see, I'm on a Windows 7 professional license. Firefox and gekowebdriver are updated to the last versions.

A: Fixed:
Jenkins being ran as a service was the problem. In order for selenium to properly display firefox, it needed to access the desktop. Fixed the issue by simply allowing Jenkins service to use the desktop. It makes for a poor fix but it works fine.


text:
Q: Best way to differentiate between class types for different handling I wanted to know what are the advantages / disadvantages of using each of the following ways to differentiate between sub-classes of the main parent class and handle them differently. I know this is pretty basic, but i couldnt find a full comparison between these ways anywhere.
For example:
- I have a Payment super abstract class and two extending classes OneTimePayment and Subscription
- I have a method switchPaymentState that should handle each one of these types differently

*

*Option 1: Using instanceof
public void switchPaymentState(Payment payment) {
  if(payment instanceof OneTimePayment) {
    //do something
  } else if(payment instanceof Subscription) {
    //do something else
  }
}

*Option 2: Using enum type argument (or other...)
public enum PaymentType {
  ONE_TIME_PAYMENT,
  SUBSCRIPTION;
}
public abstract Payment(PaymentType type) {
  this.type = type;
}
public OneTimePayment() {
   super(ONE_TIME_PAYMENT);
}
public Subscription() {
   super(SUBSCRIPTION);
}

and then:
public void switchPaymentState(Payment payment) {
  switch(payment.type) {
    case ONE_TIME_PAYMENT:
      //do something
      break;
    case SUBSCRIPTION:
      //do something
      break;
  }
}

*Option 3: Using overload methods
public void switchPaymentState(OneTimePayment payment){
    //do something
}
public void switchPaymentState(Subscription payment){
   //do something
}

So, which is the best way to go (or a complete other way?) and why?
EDIT:
The operations i need to do based on the class type are NOT operations on the class itself, i need to take some data form the payment and send it via other services, so solutions like implementing this functionality inside the classes and calling it regardless of the type, will unfortunately not help in this case. Thanks!

A: The most modular way would be to use overriding.
You'll have a single switchPaymentState method which accepts the base type - Payment - and calls a method in the Payment class to do the handling. That method can be overridden in each sub-class of Payment.
public void switchPaymentState(Payment payment)
{
    payment.handlePayment();
}

Your switchPaymentState method doesn't have to know which sub-classes of Payment exist, and it doesn't have to change if you add new sub-classes tomorrow.

A: Your option 3 will in many cases not work, because overloading is resolved atcompile-time rather than at run-time. If the type of your references is Payment, it is not possible to use overloading.
In terms of object-oriented design, using overridden methods is the "cleanest" method. However, it has the disadvantage that similar functionality is spead over multiple classes, whereas in the switch and instanceof solutions everything is together.
An alternative that offers the best of both worlds is the so-called Visitor Pattern. You create an interface PaymentVisitor with for each class you want a handle a method, as follows:
interface PaymentVisitor {
    void visitOneTimePayment(OneTimePayment payment);
    void visitSubscription(Subscription payment);
}

Then in you abstract superclass you add a method visit:
abstract class Payment {
    ...
    abstract void callVisitor(PaymentVisitor visitor);
}

Which you implement in all you subclasses as follows:
class OneTimePayment {
    ...
    @Override void callVisitor(PaymentVisitor visitor) {
        visitor.handleOneTimePayment(this);
    }
}

class Subscription {
    ...
    @Override void callVisitor(PaymentVisitor visitor) {
        visitor.handleSubscription(this);
    }
}

Now, in all cases where you would otherwise write something like (in pseudo-Java):
switch (type of x) {
    case OneTimePayment:
         // Code
         break;
     case Subscription:
         // Code
         break;
}

You can now write, cleanly and type-safe:
x.callVisitor(new PaymentVisitor() {
    @Override void handleOneTimePayment(OneTimePayment payment) {
        // Code
    }
    @Override void handleSubscription(Subscription payment) {
        // Code
    }
});

Note also that the visitor is implemented in an inner class, so you still have access to all (effectively) final variables defined in the method body.

A: I think the switch is a bit of an anti-pattern regardless of how you do it. The more standard OO way would be to implement the same method or methods in both of the subclasses, and let each class manage things as appropriate. In other words
abstract class Payment {
    abstract void processPayment(BigDecimal amount);
    abstract void processRefund...
}

class OneTimePayment extends Payment {
    void processPayment(BigDecimal amount){... }

    void processRefund...
}

etc.
Also, unless you're reusing a considerable amount of code in the super class, consider an interface-based implementation instead of subclassing.


text:
Q: Using ORDER BY to order 'Age Groups' (using postgresql in chartio) I'm displaying the Amount of Users in certain Age Groups. I work with Chartio so I have a graphic output. My problem: The output is orientated by the way the columns are orders. I want my Age Groups (and their count) to be lined up as you would logical expect it: From young to old and in the end "No information given". But I cannot order those alphabetically, that will mess up the table. My work around is to add another column just for Ordering (Numerical von 1 to n, use ORDER BY on that column, and then make this column invisible) - See code below. However I'm looking for a better way to do this; either (1) have a better way to get the columns in order or (2) find a way to make the counting better so I dont have to worry about ordering.
 SELECT "tmp"."type" AS "Type",
        count("tmp"."type") AS "Amount",
        "tmp"."order" AS "Order"
FROM
(SELECT "ci0"."id" AS "Id",
        "us0"."date_of_birth" AS "Date_of_Birth",
        "us0"."last_seen_at" AS "Last_seen_at",
        "us0"."username" AS "username",
        "us0"."email" AS "email",
        CASE
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 75
    THEN '75 years or older'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 65
    THEN '65-74 years old'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 55
    THEN '55-64 years old'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 45
    THEN '45-54 years old'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 35
    THEN '35-44 years old'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 25
    THEN '25-34 years old'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 18
    THEN '18-24 years old'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 12
    THEN '12-17 years old'
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") < 12
    THEN 'under 12 years old'
  ELSE 'No Birthdate given'
    END AS "type",
        CASE
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 75
    THEN 9
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 65
    THEN 8
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 55
    THEN 7
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 45
    THEN 6
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 35
    THEN 5
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 25
    THEN 4
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 18
    THEN 3
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") >= 12
    THEN 2
  WHEN DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth") < 12
    THEN 1
  ELSE 10
    END AS "order"

FROM "public"."users" AS "us0"
INNER JOIN "public"."chat_infos" AS "ci0"
ON "ci0"."user_id" = "us0"."id"
  WHERE ("us0"."last_seen_at" BETWEEN NOW() - INTERVAL '28 DAY' AND NOW())
  ) AS "tmp"

GROUP BY "type", "Order"
ORDER BY "Order"
LIMIT 1000;

A: You could enter the age-as-text information in a small lookup table, join to that using your date_part logic, and order on the text field.
e.g.
your lookup table would have
id
age_text_description
age_from
age_to

and your join would be of the form:
...on DATE_PART('year', now()) - DATE_PART('year', "us0"."date_of_birth")
between age_from and age_to

A: SQL Fiddle
with age_groups(ag, description) as (
    values
    (int4range(0, 11, '[]'), 'under 12 years old'),
    (int4range(12, 17, '[]'), '12-17 years old'),
    (int4range(18, 24, '[]'), '18-24 years old'),
    (int4range(25, 34, '[]'), '25-34 years old'),
    (int4range(35, 44, '[]'), '35-44 years old'),
    (int4range(45, 54, '[]'), '45-54 years old'),
    (int4range(55, 64, '[]'), '55-64 years old'),
    (int4range(65, 74, '[]'), '65-74 years old'),
    (int4range(75, 999, '[]'), '75 years or older')
)
select age_group, "Amount"
from (
    select
        ag,
        coalesce(description, 'No Birthdate given') as age_group,
        count(*) as "Amount"
    from
        (
            select (
                date_part('year', now()) - date_part('year', us0.date_of_birth)
            )::int as age
            from
                users as us0
                inner join
                chat_infos as ci0 on ci0.user_id = us0.id
            where (us0.last_seen_at between now() - interval '28 day' and now())
        ) s
        left join
        age_groups on age <@ ag
    group by 1, 2
    order by ag
) s


text:
Q: How to get rid of this problem ( On adding a nuget packages from VSCode it says terminated with exit code: 1.)? When I trying to add Nuget Packages by Nuget gallery extension from VS Code. It doesn't install the NuGet package.
Executing task: dotnet add /home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj package Microsoft.AspNetCore.Identity.EntityFrameworkCore -v 5.0.6 -s https://api.nuget.org/v3/index.json <
Determining projects to restore...
Writing /tmp/tmpIIHQRz.tmp
info : Adding PackageReference for package 'Microsoft.AspNetCore.Identity.EntityFrameworkCore' into project '/home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj'.
info : Restoring packages for /home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj...
error: Unable to load the service index for source https://api.nuget.org/v3/index.json.
error:   The SSL connection could not be established, see inner exception.
error:   The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
Usage: NuGet.CommandLine.XPlat.dll package add [options]
Options:
-h|--help               Show help information
--force-english-output  Forces the application to run using an invariant, English-based culture.
--package               Id of the package to be added.
--version               Version of the package to be added.
-d|--dg-file            Path to the dependency graph file to be used to restore preview and compatibility check.
-p|--project            Path to the project file.
-f|--framework          Frameworks for which the package reference should be added.
-n|--no-restore         Do not perform restore preview and compatibility check. The added package reference will be unconditional.
-s|--source             Specifies NuGet package sources to use during the restore.
--package-directory     Directory to restore packages in.
--interactive           Allow the command to block and require manual action for operations like authentication.
--prerelease            Allows prerelease packages to be installed.
The terminal process "/bin/bash '-c', 'dotnet add /home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj package Microsoft.AspNetCore.Identity.EntityFrameworkCore -v 5.0.6 -s https://api.nuget.org/v3/index.json'" terminated with exit code: 1.
Terminal will be reused by tasks, press any key to close it.
How can I get rid of this problem?
https://api.nuget.org/v3/index.json shows:#

Note: I'm using Ubuntu.

A: We may solve this issue by one of following process.

*

*copy project to another folder or create new project to another destination.

It may cause, our file or folder is corrupted.

*

*Reinstalling our software(s) like IDE or dotnet or both.

It may cause not to be installed correctly.

*

*The final is so funny. Re-install your OS and then other softwares.


text:
Q: How to mock UploadedFile object in request I want to fake  uploadedFile object in request object for testing purposes this way:
$image = new UploadedFile('public/testImage.jpg', 'testImage.jpg', filesize('public/testImage.jpg'), 'image/jpg', null, true);
    $request = new Illuminate\Http\Request();
    $request->replace([
        'image' => $image,
    ]);
    dd($request->hasFile('image'));

If I dump $request->toArray(), I see that it contains uploadedFile object:
array:1 [
  "image" => Illuminate\Http\UploadedFile {#651
    -test: false
    -originalName: "testImage.jpg"
    -mimeType: 9965
    -size: "image/jpg"
    -error: 0
    path: "public"
    filename: "testImage.jpg"
    basename: "testImage.jpg"
    pathname: "public/testImage.jpg"
    extension: "jpg"
    realPath: "/app/public/testImage.jpg"
    aTime: 2017-02-01 15:45:03
    mTime: 2017-01-31 15:35:05
    cTime: 2017-01-31 15:35:05
    inode: 15213368
    size: 9965
    perms: 0100775
    owner: 1000
    group: 1000
    type: "file"
    writable: true
    readable: true
    executable: true
    file: true
    dir: false
    link: false
  }
]

Unfortunately,  $request->hasFile('image') returns false.Tell me please, what am I doing wrong?


text:
Q: Is it possible to request app rating in an WKWebView? I have an app running WKWebView on a local html file, and I would like to add the function request app rating, but I don't know if it is possible and how to call that. The project runs in a XCode 13 on swift.

A: Yes, you need to register a WKUserContentController on your WKWebView like this
let webView = WKWebView()
let storeKitHandler = StoreKitHandler()
webView.configuration.userContentController.add(storeKitHandler, name: "storeKitHandler")

Where the StoreKitHandler is a class conforming to WKScriptMessageHandler
class MyHandler: NSObject, WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "callback" {
            if let body = message.body as? String, body == "requestReview" {
                SKStoreReviewController.requestReview()
            }
        }
    }
}

And then call the method like this from JavaScript
window.webkit.messageHandlers.storeKitHandler.postMessage('requestReview');

This will then call userContentController(_:WKUserContentController, didReceive: WKScriptMessage) with the message name storeKitHandler and body requestReview.