text:
Q: Drawing graphics doesn't work I have this code where it makes the form always on top, transparent and click through.
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    namespace HyperBox
    {

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();

        this.TopMost = true; // make the form always on top
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; // hidden border
        this.WindowState = FormWindowState.Maximized; // maximized
        this.MinimizeBox = this.MaximizeBox = false; // not allowed to be minimized
        this.MinimumSize = this.MaximumSize = this.Size; // not allowed to be resized
        this.TransparencyKey = this.BackColor = Color.Red; // the color key to transparent, choose a color that you don't use

        // Set the form click-through
        int initialStyle = GetWindowLong(this.Handle, -20);
        SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20);
    }

    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern int SetParent(int hWndChild, int hWndNewParent);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr FindWindow(
     [MarshalAs(UnmanagedType.LPTStr)] string lpClassName,
     [MarshalAs(UnmanagedType.LPTStr)] string lpWindowName);
    [DllImport("user32.dll")]
    public static extern IntPtr SetParent(
     IntPtr hWndChild,      // handle to window
     IntPtr hWndNewParent   // new parent window
     );

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        // draw what you want
        e.Graphics.FillRectangle(Brushes.Red, new Rectangle((SystemInformation.WorkingArea.Width / 2) - 4, (SystemInformation.WorkingArea.Height / 2) - 20, 8, 40));
        e.Graphics.FillRectangle(Brushes.Red, new Rectangle((SystemInformation.WorkingArea.Width / 2) - 20, (SystemInformation.WorkingArea.Height / 2) - 4, 40, 8));

    }
    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {

    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {

        IntPtr hwndf = this.Handle;
        IntPtr hwndParent = FindWindow("chrome.exe", null);
        SetParent(hwndf, hwndParent);

    }

}
    }

The problem is when I draw the graphics, it draws nothing. When the coordinates are around 100~ it works. But when it does the method above nothing happens. At all, not even a pixel. Could someone please explain why this is happening and or repost a fixed snippet, thank you. Layne

A: OnPaint is giving you a graphics object for your form, not the screen. You are filling rectangles based on the working area of the system, not the form. You will need to adjust your rectangle coordinates and position the form where you want your graphics to appear. A rectangle with a location of (0, 0) is the top-left corner of the form's client area. You should also be able to access that rectangle by calling ClientRectangle that is exposed on the base Form class.
Take a look at this question for drawing outside your form: Draw / Paint Outside Form
That should get you started in the right direction if you don't want to paint on your form, but it would probably be easier to reposition and resize your form as needed.
EDIT It would probably be wise to at least add a some sort of border while you debug your issue. This will help you see where the form is positioned and what monitor it is on. You can then check your numbers as you break point in OnPaint to make sure you are creating your rectangles correctly, however, making sure you are painting within the form's client area should fix your issue.


text:
Q: How to Install compiler g++-4.8.5 in ubuntu 22.04 I am trying to install g++ compiler version 4.8.5 on ubuntu 22.04 and found a similar question here
i have applied all the changes suggested in the chain but unable to compile the gcc4.8.5 , here are the steps
sudo dpkg --add-architecture i386
sudo apt update
sudo apt upgrade
sudo apt-get install gcc-multilib libstdc++6:i386
wget https://ftp.gnu.org/gnu/gcc/gcc-4.8.5/gcc-4.8.5.tar.bz2 --no-check-certificate
tar xf gcc-4.8.5.tar.bz2
# cd gcc-4.8.5
# ./contrib/download_prerequisites
# cd ..
sed -i -e 's/__attribute__/\/\/__attribute__/g' gcc-4.8.5/gcc/cp/cfns.h
sed -i 's/struct ucontext/ucontext_t/g' gcc-4.8.5/libgcc/config/i386/linux-unwind.h
sed -i '/#include <pthread.h>/a #include <signal.h>' path_to_gcc4.8.5src/libsanitizer/asan/asan_linux.cc
sed -i 's/__res_state \\*statp = (__res_state\\*)state\\;/struct __res_state \\*statp = (struct __res_state\\*)state\\;/g' path_to_gcc4.8.5src/libsanitizer/tsan/tsan_platform_linux.cc
mkdir xgcc-4.8.5
pushd xgcc-4.8.5
$PWD/../gcc-4.8.5/configure --enable-languages=c,c++ --prefix=/usr --enable-shared --enable-plugin --program-suffix=-4.8.5
make MAKEINFO="makeinfo --force" -j
sudo make install -j

Compilation Error
/home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/config/i386/i386.c: In function 'tree_node* ix86_handle_abi_attribute(tree_node**, tree, tree, int, bool*)':
/home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/config/i386/i386.c:34858:18: warning: unquoted identifier or keyword 'ms_abi' in format [-Wformat-diag]
34858 |           **error** ("ms_abi and sysv_abi attributes are not compatible");
      |                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/config/i386/i386.c:34858:18: warning: unquoted identifier or keyword 'sysv_abi' in format [-Wformat-diag]
/home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/config/i386/i386.c:34867:18: warning: unquoted identifier or keyword 'ms_abi' in format [-Wformat-diag]
34867 |           **error** ("ms_abi and sysv_abi attributes are not compatible");
      |                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/config/i386/i386.c:34867:18: warning: unquoted identifier or keyword 'sysv_abi' in format [-Wformat-diag]
/home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/config/i386/i386.c: In function 'long unsigned int ix86_memmodel_check(long unsigned int)':
/home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/config/i386/i386.c:42398:15: warning: unquoted identifier or keyword 'HLE_ACQUIRE' in format [-Wformat-diag]

/bin/bash /home/umtts/xgcc-4.8.5/../gcc-4.8.5/gcc/../move-if-change tmp-automata.c insn-automata.c
echo timestamp > s-automata
rm gcc.pod
make[3]: Leaving directory '/home/umtts/xgcc-4.8.5/gcc'
make[2]: *** [Makefile:4163: all-stage1-gcc] Error 2
make[2]: Leaving directory '/home/umtts/xgcc-4.8.5'
make[1]: *** [Makefile:21493: stage1-bubble] Error 2
make[1]: Leaving directory '/home/umtts/xgcc-4.8.5'
make: *** [Makefile:892: all] Error 2
umtts@wifi6:~/xgcc-4.8.5$ ls

redpajama_set_name: RedPajamaStackExchange


text:
Q: SMTP Client implementation I'm implementing SMTP client.
What should the client do once it already sent the "." at the end of the mail, but didn't receive "250 Ok"?
This is how the conversation between the client and server look like:
Server Response: 220 www.sample.com ESMTP Postfix
Client Sending : HELO domain.com
Server Response: 250 Hello domain.com
Client Sending : MAIL FROM: <me@domain.com>
Server Response: 250 Ok
Client Sending : RCPT TO: <friend@sample.com>
Server Response: 250 Ok
Client Sending : DATA
Server Response: 354 End data with <CR><LF>.<CR><LF>
Client Sending : Subject: Example Message
Client Sending : From: me@domain.com
Client Sending : To: you@sample.com
Client Sending :
Client Sending : TEST MAIL
Client Sending :
Client Sending : .
Server Response: 250 Ok: queued as 23411
Client Sending : QUIT

I'm not sure what should I do if the client sends "." and doesn't receive the 250 Ok - because of possible network error.
Was the "." sent or not? Should the client resend the mail - and - maybe - duplicate the item, or not - and risk in losing an important mail item?
Thank you.


text:
Q: Finding img src of parent of parent Recently I've been attempting to web scrape an image from a website with cheerio but I'm having issues actually finding it. Currently I'm looping through each link within the page and then attempting to find the image from the parents of the link.
Here is my current code:
$('a').each(function (Index, Element) {
    if (Index <= 8) {
        let Link = $(Element).attr('href');
        let Main = $(Element).parent().parent().find("img").attr("src")
        console.log(Main)
        PlayersEmbed.addField(ConvertNumber(Index), "Test", true);
    }
})

Here is website HTML:
https://smashdata.gg/error/smash/ultimate/player/Bravo?id=0

A: I was able to figure it out myself by searching for "tr" instead like how @Ouroborus suggested.


text:
Q: How can i get process original file name for a process? say, i've a binary called vlc.exe, if i rename it to abc.exe, it still runs fine. But if you see properties of abc.exe, you can see an attribute "Original FileName" and its value is vlc.exe. So, is there an api to get this "Original FileName"?
Thanks in advance.

A: See Version Information Functions on MSDN.
You'll need to GetFileVersionInfo to get the version info data, then VerQueryValue for the OriginalFilename entry.


text:
Q: animated closing flash message on bootstrap rails I'm using bootstrap with rails to generate flash message, i also have the following JS code:
$(function() {
    setTimeout(function(){
        $('.alert').slideUp(400);
    }, 1800);
});

Render fash in partial
<% flash.each do |message_type, message| %>
    <div class="alert alert-<%= flash_class_name(message_type) %> alert-dismissable">
    <%= message %>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
</button>

the code seems to work just fine, except the animation for flash message generated from Application Controller like:
rescue_from CanCan::AccessDenied do |exception|
    redirect_to main_app.root_path, :alert => exception.message
end

animation generated elsewhere from Application Controller works just fine,i don't know why it doesn't work in this case most of the time and how to fix that


text:
Q: How to use jruby/activerecord-jdbcmssql-adapter to a brand new rails app (preferrably rails 5+) I am trying to create a new Rails app using JRuby, and my Gemfile looks like:
source 'https://rubygems.org'

gem 'rails', '~> 5.0.7'
gem 'activerecord-jdbcmssql-adapter'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'therubyrhino'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

group :development do
  gem 'listen'
end

I run bundle install and it installs successfully.
Problem is when I run either rails s or rails c:

Bundler::GemRequireError: There was an error while trying to load the gem 'activerecord-jdbcmssql-adapter'.
Gem Load Error is: uninitialized constant ActiveRecord::ConnectionAdapters::Column::Format
Backtrace for gem load error is:
/app/jruby-9.2.0.0/lib/ruby/gems/shared/gems/activerecord-jdbc-adapter-1.3.22/lib/arjdbc/jdbc/type_cast.rb:13:in `module:TypeCast'
/app/jruby-9.2.0.0/lib/ruby/gems/shared/gems/activerecord-jdbc-adapter-1.3.22/lib/arjdbc/jdbc/type_cast.rb:7:in `module:Jdbc'
/app/jruby-9.2.0.0/lib/ruby/gems/shared/gems/activerecord-jdbc-adapter-1.3.22/lib/arjdbc/jdbc/type_cast.rb:4:in `module:ConnectionAdapters'
/app/jruby-9.2.0.0/lib/ruby/gems/shared/gems/activerecord-jdbc-adapter-1.3.22/lib/arjdbc/jdbc/type_cast.rb:3:in `'

The question is: Is activerecord-jdbcmssql-adapter compatible with Rails5?
Because my requirement is to use JRuby and MS SQL. It seems like this is the only gem available.
If it cannot support Rails 5, can it support Rails 4? What rails 4 version?

A: I have tried it in 4.2.10 and it works, with setting the version for the gem.
See my answer in this question, which has my settings:
Gem Load Error is: undefined method `type_cast_from_database' for class `ArJdbc::MSSQL::UUIDType'
About rails 5 though, I dont know for sure.


text:
Q: How to order a child of has_one relationship by attributes inside a controller using Rails 5? I have 2 models as a child from has_one relationship like this:
class HotelThai < ApplicationRecord

  belongs_to :hotel

  #validates :hotel_id, presence: true
  validates :hotel_name, presence: true
  validates :description, presence: true

end

class HotelEng < ApplicationRecord

  belongs_to :hotel

  validates :hotel_name, presence: true
  validates :description, presence: true

end

And this is my Parent Model:
class Hotel < ApplicationRecord

  mount_uploader :logo, PromotionImageUploader
  mount_uploader :image_url, PromotionImageUploader
  mount_uploader :banner, PromotionImageUploader

  validates :logo, presence: true
  validates :image_url, presence: true
  validates :banner, presence: true

  validates :hotel_link, presence: true

  has_one :hotel_thai ,dependent: :destroy
  has_one :hotel_eng ,dependent: :destroy

  validates_associated :hotel_thai
  validates_associated :hotel_eng

end

Then on the controller i need to get a hotel data order by child hotel_thai or hotel_eng (depending on current language) with hotel_name attribute.
I tried it with this:
def index
    @normal_hotel = nil
    if I18n.locale == :en
      @normal_hotel = Hotel.where(is_highlight: false).order('hotel_eng.hotel_name ASC').paginate(:page => params[:page], :per_page => 10)
    elsif I18n.locale == :th
      @normal_hotel = Hotel.where(is_highlight: false).order('hotel_thai.hotel_name ASC').paginate(:page => params[:page], :per_page => 10)
    else
      @normal_hotel = Hotel.where(is_highlight: false).order('hotel_eng.hotel_name ASC').paginate(:page => params[:page], :per_page => 10)
    end

    normal_hotel_group = @normal_hotel.in_groups(2)
    @left_normal_hotel = normal_hotel_group[0]
    @right_normal_hotel = normal_hotel_group[1]

    @highlight_hotel = Hotel.where(is_highlight: true)
    highlight_hotel_group = @highlight_hotel.in_groups(2)
    @left_highlight_hotel = highlight_hotel_group[0]
    @right_highlight_hotel = highlight_hotel_group[1]
  end

But this is what I got:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "hotel_eng" LINE 1: ...tels" WHERE "hotels"."is_highlight" = $1 ORDER BY hotel_eng.... ^ : SELECT "hotels".* FROM "hotels" WHERE "hotels"."is_highlight" = $1 ORDER BY hotel_eng.hotel_name ASC LIMIT $2 OFFSET $3

So does anyone know how to fix this, or another way to make this work?

A: You need to join related tables if you want to use order by theirs columns. Use joins or includes methods for this
def index
  hotel = I18n.locale == :th ? :hotel_thai : :hotel_eng
  @normal_hotel = Hotel.where(is_highlight: false).
    joins(hotel).order("#{hotel.to_s.pluralize}.hotel_name ASC").
    paginate(page: params[:page], per_page: 10)
  normal_hotel_group = @normal_hotel.in_groups(2)
  ...
end


text:
Q: Json.net can not install in visual studio 2012 when i am installing Newtonsoft.json using Nugget package manager then i am getting error like this

i am having .net framework version 4.5.50709

A: Update your nuget manager to 2.6 and restart visual studio.


text:
Q: Cannot bind docker chrome node in seleniumgrid to proxy container Problem
I am launching seleniumgrid with mobbrowserproxy in a docker bridged network. The remote driver proxy settings are configured correctly but i cannot connect to the proxy server from the chrome driver. I have looked at all the issues and i cannot find a solution.
Below is the error which shows the driver desired capabilities/options.
Stacktrace
selenium-hub    | 15:40:24.222 INFO [TestSlot.getNewSession] - Trying to create a new session on test slot {server:CONFIG_UUID=ef95a1c8-8c30-472b-9e5e-323b8a8c9045, seleniumProtocol=WebDriver, browserName=chrome, maxInstances=1, platformName=LINUX, version=74.0.3729.169, applicationName=, platform=LINUX}
chrome_1        | 15:40:24.243 INFO [ActiveSessionFactory.apply] - Capabilities are: {
chrome_1        |   "browserName": "chrome",
chrome_1        |   "goog:chromeOptions": {
chrome_1        |     "args": [
chrome_1        |       "--disable-gpu",
chrome_1        |       "--headless",
chrome_1        |       "--no-sandbox",
chrome_1        |       "--whitelisted-ips",
chrome_1        |       "--disable-dev-shm-usage",
chrome_1        |       "--allow-insecure-localhost",
chrome_1        |       "--disable-web-security",
chrome_1        |       "--ignore-certificate-errors",
chrome_1        |       "--allow-running-insecure-content"
chrome_1        |     ],
chrome_1        |     "extensions": [
chrome_1        |     ]
chrome_1        |   },
chrome_1        |   "proxy": {
chrome_1        |     "httpProxy": "0.0.0.0:9099",
chrome_1        |     "proxyType": "manual",
chrome_1        |     "sslProxy": "0.0.0.0:9099"
chrome_1        |   },
chrome_1        |   "version": ""
chrome_1        | }
chrome_1        | 15:40:24.243 INFO [ActiveSessionFactory.lambda$apply$11] - Matched factory org.openqa.selenium.grid.session.remote.ServicedSession$Factory (provider: org.openqa.selenium.chrome.ChromeDriverService)
chrome_1        | Starting ChromeDriver 74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}) on port 28080
chrome_1        | Only local connections are allowed.
chrome_1        | Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
chrome_1        | [1589038824.252][SEVERE]: bind() failed: Cannot assign requested address (99)
chrome_1        | 15:40:24.418 INFO [ProtocolHandshake.createSession] - Detected dialect: OSS
chrome_1        | 15:40:24.444 INFO [RemoteSession$Factory.lambda$performHandshake$0] - Started new session 4c42082804845cf9571e6a843a63feca (org.openqa.selenium.chrome.ChromeDriverService)
chrome_1        | 15:40:34.798 INFO [ActiveSessions$1.onStop] - Removing session 4c42082804845cf9571e6a843a63feca (org.openqa.selenium.chrome.ChromeDriverService)

I believe the key point of this stacktrace is right here
chrome_1        | Only local connections are allowed.
chrome_1        | Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
chrome_1        | [1589038824.252][SEVERE]: bind() failed: Cannot assign requested address (99)

To Reproduce
To reproduce this error. If you simple launch the containers and login to chromenode and use the chromedriver cli, you should see the same error in the terminal. Again the target of this issue is connecting the proxy container via chromedriver proxy settings.
version: "3"

services:
  selenium-hub:
    image: selenium/hub:3.141.59-20200409
    container_name: selenium-hub
    ports:
      - "4444:4444"
    networks:
      - caowebtests

  chrome:
    image: selenium/node-chrome:3.141.59-oxygen
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444
    networks:
      - caowebtests
    expose:
      - 9515

  firefox:
    image: selenium/node-firefox:3.141.59-20200409
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444
    networks:
      - caowebtests

  opera:
    image: selenium/node-opera:3.141.59-20200409
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444
    networks:
      - caowebtests

  proxy:
    image: spothero/browsermob-proxy:1.0.0
    depends_on:
      - selenium-hub
    networks:
      - caowebtests
    ports:
      - "9090:9090"
    links:
      - selenium-hub
      - firefox
      - chrome
      - opera

  robottests:
    container_name: robottests
    command: /bin/sleep infinity
    depends_on:
      - selenium-hub
    build: .
    volumes:
      - ./reports:/cao_ui_tests/reports
    networks:
      - caowebtests

networks:
  caowebtests:
    driver: bridge

As you can  see in the trace above. the desired capabilities and options are all there. What I am trying to find out is why the chrome driver is getting this error with the proxy settings above.
My test is failing when looking for the first element on the login page. I am not sure if you need the test scripts and the ability to execute the test scripts to try to reproduce this or if this is something that can be pointed out. I can add this repo to github if needed.
Test Script Below
*** Settings ***
Library    BrowserMobProxy
Library    SeleniumLibrary
Library    RequestsLibrary
Library    Collections

Resource   resources${/}base.robot
Resource   resources${/}common.robot
Resource   resources${/}auth.robot

Suite Setup  Setup Test Suite
Test Teardown  Close All Browsers
Suite Teardown  Test Suite Teardown

*** Variables ***
${BMP_HOST}  0.0.0.0
${BMP_PORT}  9090
${SELENIUM}  http://0.0.0.0:4444/wd/hub
${SHOT_NUM}  0
@{TIMINGS}

*** Test Cases ***
Login User
  Wait Until Page Loads
  Wait Until Page Contains Element  ${UI['login']}  timeout=10
  Submit Credentials  %{TEST_USER}  %{TEST_PASS}

*** Keywords ***
Setup Test Suite
  Load UI Repository  ${REPO_PATH}
  Connect To Remote Server  ${BMP_HOST}  ${BMP_PORT}
  Set Selenium Implicit Wait  0.2 seconds
  Set Selenium Timeout  30 seconds
  ${prefs}=  Evaluate  sys.modules['selenium.webdriver'].ChromeOptions()  sys, selenium.webdriver
  &{caps}=  Set Capabilities
  Call Method  ${prefs}  add_argument  --disable-gpu
  Call Method  ${prefs}  add_argument  --headless
  Call Method  ${prefs}  add_argument  --no-sandbox
  Call Method  ${prefs}  add_argument  --whitelisted-ips
  Call Method  ${prefs}  add_argument  --disable-dev-shm-usage
  Call Method  ${prefs}  add_argument  --allow-insecure-localhost
  Call Method  ${prefs}  add_argument  --disable-web-security
  Call Method  ${prefs}  add_argument  --ignore-certificate-errors
  Call Method  ${prefs}  add_argument  --allow-running-insecure-content
  Create Webdriver  Remote  command_executor=${SELENIUM}  desired_capabilities=${caps}
 options=${prefs}
  New Har  LoginPage
  Go To  https://cardatonce.eftsource.com

Test Suite Teardown
  Get Har  file.har
  Close Proxy

Set Capabilities
  [Documentation]  Set the options for the selenium Driver
  ${port}=  Create Proxy

  &{proxy}=  Create Dictionary
  ...  proxyType  MANUAL
  ...  sslProxy  ${BMP_HOST}:${port}
  ...  httpProxy  ${BMP_HOST}:${port}

  &{caps}=  Create Dictionary  browserName=chrome  platform=ANY  proxy=&{proxy}
  Log  Selenium capabilities: ${caps}
  [return]  ${caps}

Create Proxy
  [Documentation]  Get a BMP port for our test
  Create Session  bmp  http://${BMP_HOST}:${BMP_PORT}
  ${resp}=  Get Request  bmp  /proxy
  Should Be Equal As Strings  ${resp.status_code}  200
  Log  BMP Sessions: ${resp.text} [${resp.status_code}]
  &{headers}=  Create Dictionary  Content-Type=application/x-www-form-urlencoded
  &{data}=  Create Dictionary  trustAllServers=True
  ${resp}=  Post Request  bmp  /proxy  data=${data}  headers=${headers}
  Should Be Equal As Strings  ${resp.status_code}  200
  Log  ${resp.text} [${resp.status_code}]
  ${port}=  Get From Dictionary  ${resp.json()}  port
  Log  New BMP port: ${port} [${resp.status_code}]
  Set Global Variable  ${port}
  [return]  ${port}

Close Proxy
  ${resp}=  Delete Request  bmp  /proxy/${port}
  Should Be Equal As Strings  ${resp.status_code}  200
  Log  Closed proxy at ${port} [${resp.status_code}]

New Har
  [Documentation]  Name and initialize a Har
  [arguments]  ${pagename}
  &{data}=  Create Dictionary  initialPageRef=${pagename}
  ${resp}=  Put Request  bmp  /proxy/${port}/har  params=${data}
  #Should Be Equal As Strings  ${resp.status_code}  204
  Log  New Har (${pagename}) [${resp.status_code}]

Environment
This is on a MacOs Mojave.
Suggestions
I think the most important part of this script is the variables connecting to the hub and the mob browser proxy containers
${BMP_HOST}  0.0.0.0
${BMP_PORT}  9090
${SELENIUM}  http://0.0.0.0:4444/wd/hub

This script just shows you how I am setting the preferences that you already see here in the stacktrace on the chrome node.
chrome_1        | Only local connections are allowed.
chrome_1        | Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
chrome_1        | [1589038824.252][SEVERE]: bind() failed: Cannot assign requested address (99)

References
These are the issues i have already found online
One
Two - at the bottom of this issue it was resolved with adding, and as you can see above. I have already tried this.
--disable-dev-shm-usage'

Three this guy solved this problem by adding ipv6 to his docker config. But i am using a bridged network in docker compose so i dont see why this option would matter....
Previous attempts
I am not sure if this is an issue with chromedriver or docker.  To go through a couple of things i have already tried...
1. I tried logging in to the chrome container and using the chromedriver cli...I also get the same error
comment on issue 2
I did try to use the image that included chromedriver 74 as the next comment suggested
next comment on issue 2

A: To eliminate
chrome_1        | Only local connections are allowed.
chrome_1        | [1589038824.252][SEVERE]: bind() failed: Cannot assign requested address (99)

You need to by set env JAVA_OPTS for docker chrome-node image:

  chrome:
    image: selenium/node-chrome:3.141.59-oxygen
    depends_on:
      - selenium-hub
    environment:
      - HUB_HOST=selenium-hub
      - HUB_PORT=4444
      - JAVA_OPTS=-Dwebdriver.chrome.whitelistedIps=
    networks:
      - caowebtests
    expose:
      - 9515


text:
Q: How to acquire lock on a file located at a NAS mount path across multiple JVMs running on different servers in Java/ Spring Boot How to acquire lock on a file located at a NAS mount path across multiple JVMs running on different servers in Java/ Spring Boot.
Tried FileSystemPersistentAcceptOnceFileListFilter. It picked up the file. However other file in same directory was not picked up by other jvm


text:
Q: How to access Chrome active tab URL using Script Editor and JavaScript I'm trying to write my first OS X script using JavaScript instead of AppleScript, and am running into some issues. The first part of this is to get the URL from a tab in Chrome, so that I can do some more work on it (e.g., create a new reading list item in safari). I've tried the following code:
var safari = Application('Safari');
var chrome = Application('Google Chrome');
chrome.activate();
var url = chrome.windows[0].tabs[0].get('url'); // This returns an ObjectSpecifier
safari.addReadingListItem(url, {andPreviewText: 'Added from Chrome'});

This fails, with error: "Error -1700: Can't convert types." I need a string, but this is still an Object specifier. So I guess I don't get a string back from .get('url')
I haven't had any luck finding examples of pulling values FROM the scripting environment, but I've seen a few about putting new tabs into a browser. Any help with this is appreciated!

A: To get the URL of the active tab, do:
Application('Chrome').windows[0].activeTab.url()

A: After more digging, I tracked down what you're supposed to do. Documented here: Apple Documentation
Properties are returned as object specifiers, to get a value from an object specifier, you call it like a function:
chrome.windows[0].tabs[0].url(); // the string value of the URL

Settable properties can be set using the =. This does not apply to read-only values (which are marked as such in the Library Panel in script editor:
chrome.windows[0].tabs[0].url = "http://example.com";


text:
Q: slow build librealsense libusb When I start my program it takes very long to build, like 3.5 minutes.
I get:
1>------ Build started: Project: libusb (ExternalProjectTargets\libusb\libusb), Configuration: Debug x64 ------
    1>Performing update step for 'libusb'
    2>Performing configuration step for 'libusb'
    3>Performing building step for 'libusb'

Does anyone have an idea what is going on and how I can speed up the building? This problem is only with the wrapper from librealsense

A: I also encountered a similar problem. When compiling librealsense and executing cmake, it will detect the network connection. If there is a network connection, it will download some files such as libusb. When you disconnect the network, there may not be the problem you asked.


text:
Q: ng-repeat animation complete callback So I have a simple ng-repeat with enter animation defined in javascript.
Sandbox: http://codepen.io/anri82/pen/KwgGeY
Code:

  {{state}}

{{item}}

  <button ng-click="add()">add</button>

angular.module('myApp', ['ngAnimate'])
.controller("MyController", function($scope) {
   $scope.state ="idle";
   $scope.id=3;
   $scope.list = [1,2];
   $scope.add = function () {
     $scope.state="pushing";
     $scope.list.push($scope.id++);
     $scope.state="done pushing";
   };
}).animation('.repeat-animate', function () {
  return {
    enter: function (element, done) {
      element.hide().show(2000, done);
    }
  };
});

How do I switch $scope.state to done pushing only after animation is complete? Answer should be in angular way, don't suggest setTimeout.

A: With the javascript animation approach you are doing, you would need to get hold of the scope of the current element within the animation's done callback. Since it is outside of angular context after updating the variable you need to manually invoke the digest cycle by doing $scope.$apply() (or use $timeout, scope.$evalAsync and so on). And also since ng-repeat creates a child scope, element's scope would actually have the inherited property state from the parent controller scope, so in-order for the update to get reflected on the parent scope, use an object to wrap state property, so that both child scope and parent has the same object reference.
angular.module('myApp', ['ngAnimate'])
.controller("MyController", function($scope) {
  $scope.push = {state: "idle" };
  $scope.id=3;
  $scope.list = [1,2];
  $scope.add = function () {
    $scope.push.state="pushing";
    $scope.list.push($scope.id++);

  };
}).animation('.repeat-animate', function () {
  return {
    enter: function (element, done) {
     element.hide().show(2000, function(){
          var scope = element.scope(); //Get the scope
          scope.$evalAsync(function(){ //Push it to async queue
             scope.push.state="done pushing"
          });
      });
    }
  };
});

Demo


text:
Q: SwiftUI: How to connect currentPage of PageView with firing view's passing index I follow Apple's example interfacing-with-uikit to use PageView in SwiftUI. And I want to implement it in my app. The scenario is that in MovieView, when the user taps an image of image list then it triggers call to PageView with views and selected index as parameters.
But when I click on any item of image list, it always show the page view with the 1st element. I try to change it in init() of PageView, however it is not working.
In console, I try to print something, and I see the currentPage is not changed.
ReceivedIdx: 0
Current page: 1
ReceivedIdx: 3
Current page: 1
ReceivedIdx: 5
Current page: 1

Currently, currentPage is connected between PageView & PageViewCollection, but how to connect selectedIdx with them? Because it is the trigger point for which image is selected.
MovieView
...
private struct ImageList: View {
    var images: [ImageViewModel]
    @State private var showSheet = false
    @State private var selectedIdx = 0

    var body: some View {

        VStack(alignment: .leading) {
            Text("Images")
                .font(.headline)
            ScrollView(.horizontal) {
                HStack(alignment: .top, spacing: 6) {
                    ForEach(0..<images.count, id: \.self) { i in
                        KFImage(source: .network(self.images[i].fileURL))
                            .resizable()
                            .frame(width: 200)
                            .aspectRatio(1.77, contentMode: .fit)
                            .onTapGesture {
                                self.selectedIdx = i
                                self.showSheet.toggle()
                        }
                    }
                }.sheet(isPresented: $showSheet) {
                    PageView(self.images.map { PresentedImageView(image: $0) }, selectedIdx: self.selectedIdx)
                }
            }.frame(height: 120)
        }
        .padding(.horizontal).padding(.bottom)
    }
}

private struct PresentedImageView: View {
    var image: ImageViewModel

    var body: some View {
        KFImage(source: .network(image.fileURL))
        .resizable()
        //.frame(width: gr.size.width - 6, alignment: .center)
        .aspectRatio(1.77, contentMode: .fit)
    }
}
...

PageView
import SwiftUI

struct PageView<Page: View>: View {

    var viewControllers: [UIHostingController<Page>]
    var selectedIdx = 0
    @State var currentPage = 1

    init(_ views: [Page], selectedIdx: Int) {
        self.viewControllers = views.map { UIHostingController(rootView: $0) }
        self.currentPage = selectedIdx
        print("ReceivedIdx: \(selectedIdx)")
        print("Current page: \(currentPage)")
    }

    var body: some View {
        PageViewController(controllers: viewControllers, currentPage: $currentPage)
    }
}

//struct PageView_Previews: PreviewProvider {
//    static var previews: some View {
//        PageView(features.map { FeatureCard(landmark: $0) })
//            .aspectRatio(3/2, contentMode: .fit)
//    }
//}

PageViewController
import SwiftUI
import UIKit

struct PageViewController: UIViewControllerRepresentable {

    var controllers: [UIViewController]
    @Binding var currentPage: Int

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIPageViewController {
        let pageViewController = UIPageViewController(transitionStyle: .scroll,
                                                      navigationOrientation: .horizontal)

        pageViewController.dataSource = context.coordinator
        pageViewController.delegate = context.coordinator
        return pageViewController
    }

    func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
        pageViewController.setViewControllers([controllers[currentPage]], direction: .forward, animated: true)
    }

    class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
        var parent: PageViewController

        init(_ pageViewController: PageViewController) {
            self.parent = pageViewController
        }

        func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
            guard let index = parent.controllers.firstIndex(of: viewController) else {
                return nil
            }

            if index == 0 {
                return parent.controllers.last
            }

            return parent.controllers[index - 1]
        }

        func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
            guard let index = parent.controllers.firstIndex(of: viewController) else {
                return nil
            }

            if index + 1 == parent.controllers.count {
                return parent.controllers.first
            }

            return parent.controllers[index + 1]
        }

        func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
            if completed,
                let visibleViewController = pageViewController.viewControllers?.first,
            let index = parent.controllers.firstIndex(of: visibleViewController)
            {
                parent.currentPage = index
            }
        }
    }
}

A: Finally, I found the answer From this post in stackoverflow. this morning!
In one word:

SwiftUI doesn't allow you to change @State in the initializer but you can initialize it.

So in my case, remove the initial value on @State currentPage and set it directly using State(initialValue:) in your init().
Remember to use _ before currentPage.
import SwiftUI

struct PageView<Page: View>: View {

    var viewControllers: [UIHostingController<Page>]
    @State var currentPage: Int

    init(_ views: [Page], selectedIdx: Int) {
        self.viewControllers = views.map { UIHostingController(rootView: $0) }
        _currentPage = State(initialValue: selectedIdx)
    }

    var body: some View {
        PageViewController(controllers: viewControllers, currentPage: $currentPage)
    }
}


text:
Q: Making an image public in private repository We have a self hosted docker repository and want the ability to let our users on the network pull images in the repo without logging in. To push an image we still need them to login. Pull should be open though.
Like how docker hub works. You need to login to publish an image but anyone can pull it if it's marked public. Is there a way to make the image "public"?
Any pointers?

A: It seems like this is not supported yet. From docs:

Note: You need to be signed in and have access to work with a private
  repository.

What you can do is have them sign in and manage each user permission (to only pull or to be able to push and pull)


text:
Q: SQL Server JOIN/APPLY Query What join should I use to get my desired output base on dummy table below
DETAIL TABLE
x------------------------------x
| empID | empName | date       |
x------------------------------x
| 1     | emp1    | 10/01/2016 |
| 1     | emp1    | 10/03/2016 |
| 1     | emp1    | 10/04/2016 |
| 1     | emp1    | 10/05/2016 |
| 1     | emp1    | 10/06/2016 |
x------------------------------x

LIST DATES FROM 10/01/2016 to 10/15/2016 OF TABLE
x------------x
| date       |
x------------x
| 10/01/2016 |
| 10/02/2016 |
| .......... |
| .......... |
| 10/15/2016 |
x------------x

Desired output for my query
x------------------------------x
| empID | empName | date       |
x------------------------------x
| 1     | emp1    | 10/01/2016 |
| null  | null    | 10/02/2016 |
| 1     | emp1    | 10/03/2016 |
| 1     | emp1    | 10/04/2016 |
| 1     | emp1    | 10/05/2016 |
| 1     | emp1    | 10/06/2016 |
| null  | null    | 10/07/2016 |
| null  | null    | 10/08/2016 |
| null  | null    | 10/09/2016 |
| null  | null    | 10/10/2016 |
| null  | null    | 10/11/2016 |
| null  | null    | 10/12/2016 |
| null  | null    | 10/13/2016 |
| null  | null    | 10/14/2016 |
| null  | null    | 10/15/2016 |
x------------------------------x

A: Answer is OUTER JOIN it can be either LEFT or RIGHT depending on where you are using the detail table.
SELECT D.empid,
       D.empname,
       LD.[date]
FROM   detail D
       RIGHT OUTER JOIN list_dates LD
                     ON D.[date] = LD.[date]

Also you can use OUTER APPLY
SELECT D.empid,
       D.empname,
       LD.[date]
FROM   list_dates LD
       OUTER apply (SELECT *
                    FROM   detail D
                    WHERE  D.[date] = LD.[date]) D

A: Looks like you just need an outer join:
select e.empid, e.empname, d.date
from dates d
   left join detail e on d.date = e.date

*

*A Visual Explanation of SQL Joins


text:
Q: What is the workaround for WMI remote connection failure with Access Denied error when client runs with Local System account? What is the workaround for WMI remote connection failure with Access Denied error when client runs with Local System account?
I tried to run script under local system account on the client which connects to remote WMI (namespace: root\cimv2) using local administrator credentials of remote machine. But WMI connection failed with the following error. The remote server has firewall enabled and client has firewall disabled. Both client and remote server has windows 2012 R2 OS.
Access is denied.
Win32::OLE(0.1709) error 0x80070005: "Access is denied"
What could be the reason for this error? The same script worked when ran from another client machine.

A: http://msdn.microsoft.com/en-us/library/aa826699(v=vs.85).aspx
refer to above link.
solution:
To solve the problem, UAC filtering for local accounts must be disabled by creating the following DWORD registry entry and setting its value to 1:
[HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System] LocalAccountTokenFilterPolicy
reason:
"In a workgroup, the account connecting to the remote computer is a local user on that computer. Even if the account is in the Administrators group, UAC filtering means that a script runs as a standard user"

A: When you get an Access is denied. [0x00000005] error, apply the following patch to the registry:

*

*HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

*create or modify 32-bit DWORD: LocalAccountTokenFilterPolicy

*set the value to: 1

Windows Server 2012 (64bit)
To connect to Windows Server 2012, Change Permission for following registry key to Full Control:

*

*HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Wow6432Node\CLSID{72C24DD5-D70A-438B-8A42-98424B88AFB8}

*HKEY_CLASSES_ROOT\CLSID{76A64158-CB41-11D1-8B02-00600806D9B6}

*

*Launch regedit (as Administrator)

*Find (Ctrl+F) the following registry key: {72C24DD5-D70A-438B-8A42-98424B88AFB8} in HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Wow6432Node\CLSID\

*Right click and select 'Permissions'

*Change owner to administrators group (Advanced...).

*Change permissions for administrators group. Grant Full Control.

*Change owner back to TrustedInstaller (user is NT Service\TrustedInstaller on local machine)

*Repeat the steps 1-6 for HKEY_CLASSES_ROOT\CLSID{76A64158-CB41-11D1-8B02-00600806D9B6}

*Restart Remote Registry Service (Administrative Tools / Services)
If the service is not starting (both from Jenkins or manually), check that you have the .NET Framework 3.5 SP1 installed.

Follow these steps if you encounter errors during the installation of the Framework: https://stackoverflow.com/questions/14192244/offline-installer-for-net-3-5-sp1-not-working

A: what happened to me was I checked the: computer management\local users and groups\users
check the user name that you are using with "local admin" need to dbl click and check if "account is disabled" box is checked, uncheck and should be good to go.


text:
Q: Array is not visible I made a post earlier today asking how I could display an array on a page, and got some good pointers that helped in debugging, and brought me a step closer. However I need more pointers. Right now I am not even getting any errors, but still wont show the content of the array even though I can view it in the console. Here is my code:

import React, { Component } from 'react'
import { Container, Row, Col } from 'bootstrap-4-react';
import News from '../Articles/News';
import Post from '../Posts/Post/Post';
import axios from 'axios';
const REACT_APP_NEWS_ARTICLE_API = process.env.REACT_APP_NEWS_ARTICLE_API

export default class Body extends Component {
  constructor(props){
    super(props)

    this.state = {
      posts: [{}],
      newsPost: []

    }
  }

  componentDidMount = (props) => {
    axios.all([axios.get(`${process.env.REACT_APP_SERVER_URL}/posts`),
    axios.get(`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${REACT_APP_NEWS_ARTICLE_API}`)])
      .then(axios.spread((...responses) => {
        const responseOne = responses[0]
        const responseTwo = responses[1]

        this.setState({
          posts: responseOne.data,
          newsPost: responseTwo.data.articles
        })
      }

      ))
  };

  render() {
    // console.log(this.state.posts)
    const newsArticles = this.state.newsPost;
    console.log(newsArticles) //an array

    return (
      <Container id="bodycontainer" className="container">
        <Row className="tech">
         heool
          {newsArticles.map((item, idx) => {

            {item.urlToImage}
               {console.log("Title: ",item.title)} //can view these logs in the console.
               {console.log("Description: ",item.description)}
               {console.log(item.urlToImage)}

          })}
        </Row>
        <Row  className="rowstyles">
          <Col className="newscolumn" col="12 sm-6 md-8">
              <Post currentPost={this.state.posts} />
          </Col>
          <Col className="contentcolumn" col="6 md-3">

Sources

          </Col>
        </Row>
      </Container>
    )
  }
}

Any pointer would be greatly appreciated

A: The problem here is not about syntax or state, but rather not returning anything from the map function. Try:
{newsArticles.map((item, idx) => (

         {item.urlToImage}

  ))}

Here, the parantheses does the same thing as:
{newsArticles.map((item, idx) => {
     return (

         {item.urlToImage}

)
  })}


text:
Q: PHP multiple tables data pagination In a database there are 2 tables - 10 records in each of them;
I want to retrieve all the data, so there will be 20 records in a response;
On each page should be only 5 records listed, so there will be 4 pages at the bottom to switch between;
When I retrieve data from database I must query each table in a separate query.
And there is a problem, because when I set limits and offset afted choosing a page number 4 there won't be records to retrieve from each tables, and each query will give me no data, because limit is 5 and offset is 15 then, but in each tables there is only 10 records;
Is it possible to solve such a problem? I'm not searching for implementation, only for text explanation;
I don't use any framework, just simple mysqli_query during db connection (it's a very old project)
Thanks for advices!

A: Its possible with UNION but that problem represent very bad database architecture and you should change it (merge into one table) before bigger problems comes

A: Have you tried using UNION and split each table query into it's own query?
Example:
([query_from_first_table]) UNION ([query_from_second_table]) LIMIT 5;


text:
Q: Bootstrap overlapping upper and lower divs with scrolling offcanvas and navbar I have an upper div controlAll and a lower div main-tree-footer. I display an svg between that I want sized between the upper and lower bounds. That is all working, the issue is the Bootstrap offcanvas and the navabar.
I want the offcanvas to appear just below the controlAll, which it does. The problem is that either I can get it to scroll with the svg or be pushed down with the navbar is expanded downwards...but not both. I'd like the navbar to push the svg (it does) and the offcanvas down and also allow the offcanvas to scroll with svg.

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">

    <title>Type Guide</title>

    <link
      rel="shortcut icon"
      href="public/playground_assets/favicon.png"
      type="icon/png"
      sizes="32x32"
    />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
      data-tag="font"
    />
    <link rel="stylesheet" href="./style.css" />

      <link href="./main-tree.css" rel="stylesheet" />

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.8/css/all.css">

    Type Guide
    <button class="navbar-toggler collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

          Home

          Communications

          Types

            All Types
            Type 1
            Type 2

Divder Text

<button class="btn btn-primary menu" type="button" data-bs-toggle="offcanvas" onClick="hideMenuButton()" data-bs-target="#offcanvasScrolling" aria-controls="offcanvasScrolling">Menu</button>

Menu

    <button type="button" class="btn-close text-reset" onClick=showMenuButton() data-bs-dismiss="offcanvas" aria-label="Close"></button>

    <button class="btn btn-primary" type="button" onclick="collapseLayer()">Collapse Single Layer</button>
    <button class="btn btn-primary" type="button" onclick="collapseAll()">Collapse All Layers</button>
    <button class="btn btn-primary" type="button" onclick="expandAll()">Expand All Layers</button>

  Filtering

  <input class="form-check-input tt" type="checkbox" role="switch" id="flexSwitchCheckChecked" checked />
  Switch Text

Type Guide

                  <svg
                    viewBox="0 0 602.2582857142856 1024"
                    class="main-tree-icon13"
                  >
                    <path
                      d="M548 6.857v150.857h-89.714c-70.286 0-83.429 33.714-83.429 82.286v108h167.429l-22.286 169.143h-145.143v433.714h-174.857v-433.714h-145.714v-169.143h145.714v-124.571c0-144.571 88.571-223.429 217.714-223.429 61.714 0 114.857 4.571 130.286 6.857z"
                    ></path>
                  </svg>


text:
Q: cannot change my login screen background I cannot change my login screen background to the desktop background in my elementary os which is based on ubuntu. I have decrypted my home folder according to this link:
http://www.howtogeek.com/116179/how-to-disable-home-folder-encryption-after-installing-ubuntu/
and when I ran the command to check for encryption I got the following result-
~$ ls -A /home
lost+found     ramiz

[note: no .ecryptfs folder there!!]
~$ sudo blkid | grep swap
/dev/sda5: UUID="00ec9e13-4cfe-4f73-905a-fef05d73caa2" TYPE="swap"

I have come to understand that it means neither my home nor swap partition is encrypted. Still I cannot change my login screen wallpaper. I have tried the simple version given in the official website - i.e.,
1) Open "Files"
2) In plank, right click on "Files" and click "Open new window as admin"
3) Insert your password
4) On the new ADMIN window, go to: /usr/share/backgrounds
5) Paste your new image file there [/usr/share/backgrounds] (make sure it's a JPEG file with, at least, 1920x1080 resolution)
6) Go to "System Settings", "Desktop" and your new image file should be there
7) Click on it
8) Log out
This wasn't helpful so I went for the decryption as I read that it was due to the fact that my home folder is encrypted that I cannot change my login screen background to the wallpaper I downloaded. (I read that here:- http://elementaryos.org/answers/login-screen-isnt-the-wallpaper-i-want-i-also-want-to-delete-all-the-default-wallpapers-1 )
Please help me. I have installed elementaryos for a friend of mine recently and she doesn't have this problem. I could change my login screen before(have tried only once!) but cannot anymore. I always thought that the lock icon beside my partition in the gparted app is saying that its encrypted. The lock icon is there.

Please help me!!

A: Got it!
1) Copy all the pics to /usr/share/backgrounds
2) Then take terminal and change directory to that folder.
   cd /usr/share/backgrounds

3) Then for every image_name.jpg that you just added, type the command:
   sudo chmod a+rw image_name.jpg

4) Now exit terminal and check your System settings -> Desktop . Your custom wallpapers will be available there. Selecting from it also changed the login screen background in my lightdm.

A: I developed a function in shell script.
ChangeBackgroundLogin () {
   basename_file=${1##*/}
   p='/usr/share/backgrounds/elementaryos-default'
   sudo cp $1 $p
   sudo chmod 644 $p
}

Only need put this function in your .bashrc
And execute
ChangeBackgroundLogin 'myImage.jpg'

A: *

*sudo cp your_wallpaper.jpg /usr/share/backgrounds/

*sudo chmod 644 /usr/share/backgrounds/your_wallpaper.jpg

*sudo nano /usr/share/gnome-background-properties/trusty-wallpapers.xml

*Go to the bottom of the file and above the last </wallpapers> tag, copy the text:

<wallpaper>
    <name>Name_of_your_wallpaper</name>
    <filename>/usr/share/backgrounds/your_wallpaper.jpg</filename>
    <options>zoom</options>
    <pcolor>#000000</pcolor>
    <scolor>#000000</scolor>
    <shade_type>solid</shade_type>
</wallpaper>
</wallpapers> <-- This should be the last line - copy the above text

*Save file and exit.

*Open System Settings->Appearance->Look tag->Wallpapers from the expanding window. And finally choose your wallpaper which will appear now with the name Name_of_your_wallpaper.


text:
Q: Flutter Notification while in Video Call using Agora SDK I'm new to flutter. I'm developing an application with Video SDK. What I want to know is that, when you are in a video call and you press home button, the app runs in background, at that time I want show a notification as "you are in a video call" and when clicked need to open the app. Can anyone help me

A: To get the state of an app and to whether the app is running in background or is inactive or has been completely destroyed we use WidgetsBindingObserverand we couple that with AppLifecycleState.
So your code will look something like this:
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver{
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }
  @override
  void dispose() {
    WidgetsBinding.instance.addObserver(this);
    super.dispose();
  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state){
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.paused:
        //App is running in the background
        break;
      case AppLifecycleState.resumed:
        //App is being used again
        break;
      case AppLifecycleState.inactive:
        //App is in foreground but inactive
        break;
      case AppLifecycleState.detached:
        //App view has been destroyed
        break;
    }
  }


text:
Q: LINQ inner WHERE - inner collection not contains string Suppose I have the following collection:
ONE
- Banana
- Mango

TWO
- Apple
- Mango

THREE
- Orange
- Pear

I want to get only the collection which do not have Mango in it, such as:
THREE
- Orange
- Pear

The following example returns wrong result:
List<Order> list = new List<Order> {
                new Order { Id = 1, Name = "ONE", Items = new List<Items> { new Item { Id = 1, Nama = "Banana" }, new Items { Id = 2, Nama = "Mango" } }},
                new Order { Id = 1, Name = "TWO", Items = new List<Items> { new Item { Id = 1, Nama = "Orange" }, new Items { Id = 2, Nama = "Mango" } }},
                new Order { Id = 1, Name = "THREE", Items = new List<Items> { new Item { Id = 1, Nama = "Pear" }, new Items { Id = 2, Nama = "Chery" } }},
            };

var result = list.Where(x => x.Item.Any(y => y.Nama != "Mango")).ToList();

A: Any will bail out as soon as a "Nama" different from 'Mango' is found which is not what you want.
x.Items.All(y => y.Nama != "Mango")

Should do it.


text:
Q: how to GROUP BY data in multi relational table (laravel eloquent) I'm stuck in a problem that how to GROUP BY data in multi relational table. Here is my code:
$invoices = Invoice::select('id', 'date', 'type')
            ->with('invoice_items:invoice_id,item_id,amount', 'invoice_items.item_title:id,name')
            ->latest('id')
            ->get();

A: I solved the problem this way --
$invoices = Invoice::select('id', 'date', 'type')
              ->with('invoice_items:invoice_id,item_id,amount', 'invoice_items.item_title:id,name')
              ->latest('id')
              ->get();

foreach($invoices as $invoice)
{
   echo date('d.M.Y', strtotime($invoice->date)) . "---
 ";

   $items = $invoice->invoice_items->groupBy('item_id');

   foreach($items as $item)
   {
      echo $item[0]['item_title']['name'] . ' - ' . $item->sum('amount') . "
";
   }

   echo "

";
}

A: Looping in the controller is not good practice.
It's better to use the with method with the callback function :
Model::with(['relation',function($relationQuery){
       $relationQuery->groupBy('relation_field');
   }]);

I hope it helps.


text:
Q: How to draw a rounded rectangle in c# I am using this code to make a rounded rectangle. But it only draws upper left and right corners of rectanlge , more it doest not complete the rectangle at lower part. How to make it complete and filled . What changes should I make ?
public static Bitmap DrawRoundedRectangle(Bitmap Image, Color BoxColor, int XPosition, int YPosition,
        int Height, int Width, int CornerRadius)
    {
     Bitmap NewBitmap = new Bitmap(Image, Image.Width, Image.Height);
     using (Graphics NewGraphics = Graphics.FromImage(NewBitmap))
    {
        using (Pen BoxPen = new Pen(BoxColor))
        {
            using (GraphicsPath Path = new GraphicsPath())
            {
                   Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
                    Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
                  Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
                    Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
                 Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
                   Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
                   Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
                    Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);
                     Path.CloseFigure();
                     NewGraphics.DrawPath(BoxPen, Path);
                 }
              }
          }
         return NewBitmap;
     }

A:     public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
    {
        int diameter = radius * 2;
        Size size = new Size(diameter, diameter);
        Rectangle arc = new Rectangle(bounds.Location, size);
        GraphicsPath path = new GraphicsPath();

        if (radius == 0)
        {
            path.AddRectangle(bounds);
            return path;
        }

        // top left arc
        path.AddArc(arc, 180, 90);

        // top right arc
        arc.X = bounds.Right - diameter;
        path.AddArc(arc, 270, 90);

        // bottom right arc
        arc.Y = bounds.Bottom - diameter;
        path.AddArc(arc, 0, 90);

        // bottom left arc
        arc.X = bounds.Left;
        path.AddArc(arc, 90, 90);

        path.CloseFigure();
        return path;
    }

And you can make two extension methods for the Graphics type so you can use them as the usual Draw... and Fill... shape-drawing methods.
    public static void DrawRoundedRectangle(this Graphics graphics, Pen pen, Rectangle bounds, int cornerRadius)
    {
        if (graphics == null)
            throw new ArgumentNullException("graphics");
        if (pen == null)
            throw new ArgumentNullException("pen");

        using (GraphicsPath path = RoundedRect(bounds, cornerRadius))
        {
            graphics.DrawPath(pen, path);
        }
    }

    public static void FillRoundedRectangle(this Graphics graphics, Brush brush, Rectangle bounds, int cornerRadius)
    {
        if (graphics == null)
            throw new ArgumentNullException("graphics");
        if (brush == null)
            throw new ArgumentNullException("brush");

        using (GraphicsPath path = RoundedRect(bounds, cornerRadius))
        {
            graphics.FillPath(brush, path);
        }
    }

Update 2020:
Recently I made my drawing libraries publicly available (NuGet). Feel free to explore the GraphicsExtensions class for more overloads (custom corner radius for each corners), and for other goodies.

A: I have modified György Kőszeg's answer for those who wants different corners.
public static GraphicsPath RoundedRect(Rectangle bounds, int radius1, int radius2, int radius3, int radius4)
    {
        int diameter1 = radius1 * 2;
        int diameter2 = radius2 * 2;
        int diameter3 = radius3 * 2;
        int diameter4 = radius4 * 2;

        Rectangle arc1 = new Rectangle(bounds.Location, new Size(diameter1, diameter1));
        Rectangle arc2 = new Rectangle(bounds.Location, new Size(diameter2, diameter2));
        Rectangle arc3 = new Rectangle(bounds.Location, new Size(diameter3, diameter3));
        Rectangle arc4 = new Rectangle(bounds.Location, new Size(diameter4, diameter4));
        GraphicsPath path = new GraphicsPath();

        // top left arc
        if (radius1 == 0)
        {
            path.AddLine(arc1.Location, arc1.Location);
        }
        else
        {
            path.AddArc(arc1, 180, 90);
        }

        // top right arc
        arc2.X = bounds.Right - diameter2;
        if (radius2 == 0)
        {
            path.AddLine(arc2.Location, arc2.Location);
        }
        else
        {
            path.AddArc(arc2, 270, 90);
        }

        // bottom right arc

        arc3.X = bounds.Right - diameter3;
        arc3.Y = bounds.Bottom - diameter3;
        if (radius3 == 0)
        {
            path.AddLine(arc3.Location, arc3.Location);
        }
        else
        {
            path.AddArc(arc3, 0, 90);
        }

        // bottom left arc
        arc4.X = bounds.Right - diameter4;
        arc4.Y = bounds.Bottom - diameter4;
        arc4.X = bounds.Left;
        if (radius4 == 0)
        {
            path.AddLine(arc4.Location, arc4.Location);
        }
        else
        {
            path.AddArc(arc4, 90, 90);
        }

        path.CloseFigure();
        return path;
    }


text:
Q: w3c Validation error message - Facebook widget I echo a url from xml file
$mapurl = '"../villas-crete.php?adults='.$getadults.'&arrival='.$getarrival.'&departure='.$getdeparture.'&avail='.$getavail.'"';

echo '» Crete
    '
    ;

When I validate the page I get following errors:
Line 3182, Column 43: general entity "arrival" not defined and no default entity
…» Cre…

Error Line 3182, Column 50: reference to entity "arrival" for which no system identifier could be generated
…ef="../villas-crete.php?adults=2&arrival=&departure=&avail=0">» Crete

ang goes on....
Also I have erors for Facebook widget
Widget is:

there is no attribute "data-href"
<div class="fb-like-box" data-href="http://www.facebook.com/pages/

there is no attribute "data-width"
…-" data-width="364" data-show-faces="true" data-stream…

A: I had a quick look at:
http://validator.w3.org/docs/errors.html

25: general entity X not defined and no default entity
This is usually a cascading error caused by a an undefined entity reference or use of an unencoded ampersand (&) in an URL or body text.
325: reference to entity X for which no system identifier could be generated
This is usually a cascading error caused by a an undefined entity reference or use of an unencoded ampersand (&) in an URL or body text.

Perhaps try replacing those ampersands with & and see how you get on?
Edit for facebook question: think you need a doctype that supports data-href etc. See:
W3C validation error with data-href


text:
Q: image replacement Struts 2 hello
i want to develop an application in which six images can be upload by user and stored into the db and if user wants to enter an additional image, delete the oldest image(i.e the image which inserted first to db);plz give me useful logic, information &links for above stated probelm;
thanx in advance

A: Question is not clear. Anyway I am suggesting a solution from what I understand from your question.
You can use timestamp as a column in db table and use min function to find the row with oldest timestamp. Then update that row's file name and timestamp with new file name and current timestamp. I think this will solve your problem


text:
Q: How to fix use dependancy error in docker? I found a base firefox standalone image, I am trying to run a script using selenium with geckodriver inside a docker container, I've tried to install requirements from the dockerfile but get ModuleNotFoundError: No module named 'selenium'
This is my Dockerfile:
From selenium/node-firefox:3.141.59-iron

 # Set buffered environment variable
ENV PYTHONUNBUFFERED 1

 # Set the working directory to /app
USER root
RUN mkdir /app
WORKDIR /app

EXPOSE 80

 # Install packacges needed for crontab and selenium

RUN apt-get update && apt-get install -y sudo libpulse0 pulseaudio software-properties-common libappindicator1 fonts-liberation python-pip virtualenv
RUN apt-get install binutils libproj-dev gdal-bin cron nano -y

# RUN virtualenv -p /usr/bin/python3.6 venv36
# RUN . venv36/bin/activate

 # Install any needed packages specified in requirements.txt
ADD requirements.txt /app/
RUN pip install -r requirements.txt
ADD . /app/

ENTRYPOINT ["/bin/bash"]

I am expecting my script to run, I'm not sure why there it is using Python2.7 in the interactive shell, I thought the selenium docker image came with 3.6 and selenium already installed

A: Your container comes with both python (python 2) and python3. It's just python defaults to the 2.7 instance. You can change this behavior by issuing:
RUN alias python=python3

in your Dockerfile


text:
Q: Can I use Dagger 2's field injection in Kotlin? I posted a question (Dagger 2 does not generate the component class (Android, Kotlin)), and after some experiments, it seems that the problem might be due to that Kotlin hides the field.
class CoffeeShop {
    @Inject
    var theCoffee: Coffee? = null
}

The error message is,
:app:kaptDebugKotline: ...\CoffeeShop.java:7:
error: Dagger does not support injection into private fields
e:     private ....Coffee theCoffee;

theCoffee was not private in my source code. But I think Kotlin may be translating
class CoffeeShop {
    @Inject
    var theCoffee: Coffee? = null
}

into Java code of
class CoffeeShop {
    @Inject
    private Coffee theCoffee = null;
    public Coffee getTheCoffee();
    public void setTheCoffee();
}

Can I use field injection in Kotlin?

A:
I think Kotlin may be translating [...] into Java code of [...]

And you would be correct, that's exactly what happens.
Typically in Kotlin you wouldn't write
@Inject var coffee: Coffee? = null

because when you're going to access coffee, it will never be null. In other words you will always inject the object before accessing it's fields. That makes the operators !! redundant and ? unnecessary. Kotlin has lateinit property modifier to express this.
@Inject lateinit var coffee: Coffee

When you use lateinit the generated field has the same visibility as its getter and setter, in this case public. This makes it work with Dagger.
You can see the result by viewing generated Kotlin bytecode.

Main menu > Tools > Kotlin > Show Kotlin Bytecode

However, even better approach would be injecting the class constructor:
class CoffeeShop @Inject constructor(val coffee: Coffee) {
    //...
}

In this case coffee is not var and can't be reassigned.
Injecting constructor is not an option when the instance is created for you by a framework, Android activity is a good example.

Note: When using qualifiers you have to specify field annotation target on them:
@Inject @field:Named("Arabica") @field:Arabica
lateinit var coffee: Coffee

Edit: You don't need to add the field target when using Dagger 2.25 or newer.

Can I use field injection in Kotlin?

Yes you can. As explained above, field injection is actually applied for lateinit properties.
But you were probably interested in generating and injecting fields without getter/setter in Kotlin.
@JvmField @Inject
var coffee: Coffee? = null


text:
Q: How to give access to an update page to one particular user only? I have a user entity and later I want to allow the users to update their details. I do this by sending to a route http://localhost:8000/update/{id}
I want to make this page to be accessed by that owner of the profile only. For an instance, if the user with the id 20 is logged in, he should have access to only http://localhost:8000/update/20 and should not allow to access someone else's. How to do this in symfony 4?

A: Furthermore, you can get the current logged in user by the following code.
$this->get('security.token_storage')->getToken()->getUser();

A: Use session variables, so that it is unique only to the user and the user cannot access other user's pages.
It is similar to the way in which when one user is logged in, he can't access other accounts.
That is also done using session variables.
Session variables in symfony


text:
Q: Fast multiple string compare In c# is there a quick way to replace the following with more efficient code:
string letters = "a,b,c,d,e,f";

if (letters.Contains("a"))
{
    return true;
}

if (letters.Contains("b"))
{
    return true;
}

if (letters.Contains("c"))
{
    return true;
}

I want to do away with having to have three compare lines of code.
Thanks!

A: You could use something like this:
return letters.Any(c => c == 'a' || c == 'b' || c == 'c');

Or this:
var lettersToLookFor = "abc";
return letters.Any(c => lettersToLookFor.Contains(c));

As per the comments, the last line of the previous code block can be shortened further:
return letters.Any(lettersToLookFor.Contains);

A: If you're literally looking for single characters in a string you can use IndexOfAny
return letters.IndexOfAny('a', 'b', 'c') >= 0;

It makes one pass over the entire string and compares each char in the string against the chars passed in.
If none of the chars exist it's still  M * N comparisons (same as 3 if's above), but if any char does exist it gets out of dodge faster.
Also for longer strings it's kinder on CPU cache memory.

A: You can use Intersect to see if there are any characters in common between the two character sets.  Note that strings implement IEnumerable<char>, so you can treat all strings as just sequences of characters.
bool result = "abc".Intersect(letters).Any();

Note that this solution, as it will put all of the characters from letters into a HashSet, will be dramatically more efficient than the other solutions currently posted that are performing multiple linear searches on the string, assuming the string is of a non-trivial size, and the search characters are not right near the start.  (You did say efficiency mattered.)

A: Simplest solution would be to club three if in single statement or can use Any() like Daniel mentioned.
if (letters.Contains("a") || letters.Contains("b") || letters.Contains("c"))
{
    return true;
}

A: LINQ is the way to go.
return letters.Any(c => c == 'a' || c == 'b' || c == 'c');

A: var arr = new []{"a","b","c"};
letters.Any(m => arr.Contains(m))

A: How about using String.IndexOfAny(Char[]) method like?
string letters = "a,b,c,d,e,f";

if ((letters.IndexOfAny(new char[] { 'a', 'b', 'c' }) >= 0))
{
   return true;
}

The zero-based index position of the first occurrence in this instance
  where any character in anyOf was found; -1 if no character in anyOf
  was found.

A: You could use a regular expression, I couldn't vouch for the efficiency though, you'd have to run a comparison and get timings:
return Regex.IsMatch(letters, "[abc]");


text:
Q: Bug in python bs4 analyzer classes? #!/usr/bin/env python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import re
doc = "
Text text empty text
"
soup = BeautifulSoup(doc)
for span in soup.find_all('span' , class_=re.compile("_\s_[0-9]+")) :
    span.decompose()

Need to find all the tags with the  and remove from DOM. But this piece of code not working for some reason!

A: BeautifulSoup splits out classes for you into a list; the regular expression won't match on multiple classes. class is one of a set of such attributes, see Multi-valued attributes.
You'll have to use a custom function to filter on multiple classes using regular expressions:
def underscored_class_span(elem, numbered=re.compile(u'_\d').match):
    if elem.name != 'span': return False
    classes = elem.get('class', [])
    return u'_' in classes and any(numbered(c) for c in classes)

for span in soup.find_all(underscored_class_span):
    span.decompose()


text:
Q: Displaying seconds, minutes and hours from total seconds in C++ I am trying to solve a problem where I have a total seconds variable, from which I am trying to determine the hours, minutes and seconds.
I do not want to use any external libraries for this task.
What I have noticed is that my seconds variable seems to result in 1 less than the actual value when it is in int form,
but when it is in double form the answer is correct. Why is this?
I would welcome a different approach, perhaps using the remainder operator.
// Example program
#include <iostream>
#include <string>

int main()
{
int total_seconds;
total_seconds = 3870;
int hours, minutes, seconds;
double total_h, total_m, total_s;
int total_hours_int, total_minutes_int;

total_h = (double)total_seconds / 3600;
total_hours_int = total_seconds / 3600;
hours = total_hours_int;

total_m = (total_h - total_hours_int) * 60;

total_minutes_int = (total_h - total_hours_int) * 60;
minutes = total_minutes_int;

total_s = ((double)total_m - total_minutes_int) * 60;

seconds = ((double)total_m - total_minutes_int) * 60;
//seconds = (double)total_s;

std:: cout << hours;
std:: cout << minutes;
std:: cout << total_s;
std:: cout << seconds;

}

Output : 143029

A: Update:
The answer below was given before the C++98 tag was added to the question.
The chono library is available since C++11, so you can use it only from that version onwards.

You haven't given any context for this task.
My asnwer below assumes you need to solve the problem in any valid C++ manner (i.e. that it is not mandatory the caculate the numbers "by hand").
If this is the case, you can use the C++ chrono library for that, as shown below. This solution is shorter and less error-prone, and avoids the type issues you had altogether.
The main class I used is std::chrono::duration and it's helper types (as you can see in the link), as well as std::chrono::duration_cast.
#include <iostream>
#include <chrono>

int main()
{
    int total_seconds = 3870;

    std::chrono::seconds total_secs(total_seconds);
    auto hours = std::chrono::duration_cast<std::chrono::hours>(total_secs);
    auto mins = std::chrono::duration_cast<std::chrono::minutes>(total_secs - hours);
    auto secs = std::chrono::duration_cast<std::chrono::seconds>(total_secs - hours - mins);

    std::cout << "totals seconds: " << total_secs.count() << std::endl;
    std::cout << "  hours: " << hours.count() << std::endl;
    std::cout << "  minutes: " << mins.count() << std::endl;
    std::cout << "  seconds: " << secs.count() << std::endl;
}

Output:
totals seconds: 3870
  hours: 1
  minutes: 4
  seconds: 30

A: I've reopened answear since it was updated to C++98.
Before C++11 it can be done nicely using standard library:
#include <iostream>
#include <string>
#include <ctime>

int main()
{
    int seconds;
    while (std::cin >> seconds) {
        std::tm t = {};
        t.tm_sec = seconds;
        t.tm_mday = 1;
        mktime(&t);
        t.tm_hour += t.tm_yday * 24;

        char buf[32];
        strftime(buf, sizeof(buf), "%H:%M:%S", &t);
        std::cout << t.tm_yday << ' ' << seconds << " = " << buf << '\n';
    }

    return 0;
}

https://godbolt.org/z/ceWWfoP6P


text:
Q: Istio on Microk8s not routing I am trying to expose the monitoring services of istio: grafana, prometheus, kiali and jaeguer through istio gateway and istio virtual-service but without success
the strange thing is when accessing through the curl the page is returned, but when accessing through the browser the gateway does not find the applications
I've tried it in several ways, put it in the default nasmespace, put it in the istio namespace, recreated the server
any help will be very welcome

*

*Environment

SO: Ubuntu 20.04.2 LTS
Kubernetes: Microk8s 1.21/stable

Client Version: version.Info{Major:"1", Minor:"21+", GitVersion:"v1.21.1-3+1f02fea99e2268", GitCommit:"1f02fea99e226878ded82f3e159f28a6706ce1fc", GitTreeState:"clean", BuildDate:"2021-05-12T21:06:02Z", GoVersion:"go1.16.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"21+", GitVersion:"v1.21.1-3+1f02fea99e2268", GitCommit:"1f02fea99e226878ded82f3e159f28a6706ce1fc", GitTreeState:"clean", BuildDate:"2021-05-12T21:02:46Z", GoVersion:"go1.16.3", Compiler:"gc", Platform:"linux/amd64"}

Istio: v1.5.1

Error

*

*yaml config

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: istio-gateway
  namespace: istio-system
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
      - "grafana.myserver.com"
      - "prometheus.myserver.com"
      - "kiali.myserver.com"
      - "jaeger.myserver.com"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: grafana-vs
  namespace: istio-system
spec:
  hosts:
  - "grafana.myserver.com"
  gateways:
  - istio-gateway
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 3000
        host: grafana.istio-system.svc.cluster.local
      weight: 100
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: prometheus-vs
  namespace: istio-system
spec:
  hosts:
  - "prometheus.myserver.com"
  gateways:
  - istio-gateway
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 9090
        host: prometheus.istio-system.svc.cluster.local
      weight: 100
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: kiali-vs
  namespace: istio-system
spec:
  hosts:
  - "kiali.myserver.com"
  gateways:
  - istio-gateway
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 20001
        host: kiali.istio-system.svc.cluster.local
      weight: 100
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: jaeger-vs
  namespace: istio-system
spec:
  hosts:
  - "jaeger.myserver.com"
  gateways:
  - istio-gateway
  http:
  - match:
    - uri:
        prefix: "/"
    route:
    - destination:
        port:
          number: 16686
        host: jaeger-query.istio-system.svc.cluster.local
      weight: 100

*

*Istio info

apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"istio-ingressgateway","chart":"gateways","heritage":"Tiller","istio":"ingressgateway","release":"istio"},"name":"istio-ingressgateway","namespace":"istio-system"},"spec":{"ports":[{"name":"status-port","port":15020,"targetPort":15020},{"name":"http2","nodePort":31380,"port":80,"targetPort":80},{"name":"https","nodePort":31390,"port":443},{"name":"tcp","nodePort":31400,"port":31400},{"name":"https-kiali","port":15029,"targetPort":15029},{"name":"https-prometheus","port":15030,"targetPort":15030},{"name":"https-grafana","port":15031,"targetPort":15031},{"name":"https-tracing","port":15032,"targetPort":15032},{"name":"tls","port":15443,"targetPort":15443}],"selector":{"app":"istio-ingressgateway","istio":"ingressgateway","release":"istio"},"type":"LoadBalancer"}}
  creationTimestamp: "2021-05-21T10:45:05Z"
  labels:
    app: istio-ingressgateway
    chart: gateways
    heritage: Tiller
    istio: ingressgateway
    release: istio
  name: istio-ingressgateway
  namespace: istio-system
  resourceVersion: "79445"
  selfLink: /api/v1/namespaces/istio-system/services/istio-ingressgateway
  uid: b2a9d401-8ecc-4c3a-bac2-a8db545b80e7
spec:
  clusterIP: 10.152.183.203
  clusterIPs:
  - 10.152.183.203
  externalTrafficPolicy: Cluster
  ipFamilies:
  - IPv4
  ipFamilyPolicy: SingleStack
  ports:
  - name: status-port
    nodePort: 30037
    port: 15020
    protocol: TCP
    targetPort: 15020
  - name: http2
    nodePort: 31380
    port: 80
    protocol: TCP
    targetPort: 80
  - name: https
    nodePort: 31390
    port: 443
    protocol: TCP
    targetPort: 443
  - name: tcp
    nodePort: 31400
    port: 31400
    protocol: TCP
    targetPort: 31400
  - name: https-kiali
    nodePort: 31537
    port: 15029
    protocol: TCP
    targetPort: 15029
  - name: https-prometheus
    nodePort: 32117
    port: 15030
    protocol: TCP
    targetPort: 15030
  - name: https-grafana
    nodePort: 31687
    port: 15031
    protocol: TCP
    targetPort: 15031
  - name: https-tracing
    nodePort: 32132
    port: 15032
    protocol: TCP
    targetPort: 15032
  - name: tls
    nodePort: 32291
    port: 15443
    protocol: TCP
    targetPort: 15443
  selector:
    app: istio-ingressgateway
    istio: ingressgateway
    release: istio
  sessionAffinity: None
  type: LoadBalancer
status:
  loadBalancer: {}


text: Q: PESSIMISTIC_WRITE lock mode during a select query in hql for the row I am performing a select query(fetching the entire row) for multiple rows with pessimistic_write lock mode to lock the rows in the select query(HQL). Will the rows be locked until I perform an update and do a commit? I am performing a load run and encountering a update count 0 for some transactions based on my where clause last transfer id whos value I fetch in my select query which means that the last transfer id has been changed leading to the fundamental doubt on locking strategy. Can someone please throw some light upon this?


text:
Q: How to find string that is not set in xml in android studio? My project needs to support multilingual functions.
But some strings are not set to the xml file, I need to search for these strings.
These strings may appear in xml layout files or java, kt files.
Does android studio have tools or recommended plug-ins that can speed up the completion of the work?
Thanks for help

A: You can find the strings hardcoded in the layout files with the following regexp:
android:text="[^@]

and in the kotlin files with this (it might not cover all the cases but you get the point): setMessage\("|setTitle\("|setText\("|text ?= ?"


text:
Q: Explanation about return object of class example I have this example ,and i need to know if the object class (ob2) in the second method came as argument from return object in the first method??
can anyone explain this example to me?
public class C {

  public B getObject(){

   B ob2 = new B ();

   return ob2; //return type
   }

   public void f3(A ob2){

   ob2.f1 (); //local variable or argument
}}

A: ob2 in method f3 comes from argument. For example:
C c = new C();
A ob2 = new A();
c.f3(ob2)

A: public class C {

    public B getObject(){
         B ob2 = new B ();
        return ob2; //return type
    }

    public void f3(A ob2){
         ob2.f1 (); //local variable or argument
   }
}

I think your question is bit confusing.
You had provided in the signature that the return type of the first function is of type ' B '.
But you are expecting the Argument of type A from type B
Here the signature of second function expects argument of type A not B


text:
Q: Symbol not loaded into templated function I created a shared library "A" that use an other shared library "B".
I have a problem when I link my program with the shared library "A".
When I use some function from the other shared library ("B") inside cpp file of the shared library "A", all is fine.
But when I use these functions inside .h file (inside a templated method or an inlined method) of the shared library "A", the symbol is not loaded and I get an error "undefined reference to symbol".
I used g++ 7.2.
I think the option -l forget to load the symbols used in header file.
Do you have an idea to avoid this?
Update 2:
Here a full reproducible example:
A.cpp
#include "A.h"

A.h
#ifndef A_H
# define A_H

#include <type_traits>
#include "B.h"

class A
{
    public:
    template <typename Type>
    std::enable_if_t<std::is_arithmetic<Type>::value,void> funcA(Type   value);
};

template <typename Type>
std::enable_if_t<std::is_arithmetic<Type>::value,void> A::funcA(Type value)
{
    B tmp;

    tmp.funcB(value);
}

#endif

B.cpp
#include "B.h"
#include <iostream>

void B::example()
{
    std::cout << "works" << std::endl;
}

B.h
#ifndef B_H
# define B_H

class B
{
    public:
    void funcB(int value);
    private:
    void example();
};

inline void B::funcB(int value)
{
    value += 1;
    example();
}

#endif

main.cpp
#include "A.h"

int main()
{
    A tmp;
    tmp.funcA(5);

    return 1;
}

Compile
g++ -std=c++17 -m64 -O2 -DNDEBUG -Wall -Wextra -Werror -fPIC -o A.o -c A.cpp
g++ -std=c++17 -m64 -O2 -DNDEBUG -Wall -Wextra -Werror -fPIC -o B.o -c B.cpp
g++ -std=c++17 -m64 -O2 -DNDEBUG -Wall -Wextra -Werror -fPIC -o main.o -c main.cpp
g++ -o libB.so B.o -shared
g++ -o libA.so A.o -shared -L. -lB
g++ -o application main.o -L . -lA

Error
main.o: In function `main':
main.cpp:(.text.startup+0x1a): undefined reference to `B::example()'
collect2: error: ld returned 1 exit status

Thank you,
SOLVED:
Finally, I solved my problem with this thread:
GCC 4.5 vs 4.4 linking with dependencies
Thank you!


text:
Q: Migrating MySQL to PostgreSQL - what features not visible in SQL code will be important? We're migrating MySQL to PostgreSQL. I can easily audit the schema and the SQL statements used throughout the (REALbasic) program. Most of the SQL is composed by building string variables.
I already know about needing to replace our use of SELECT LAST_INSERT_ID() with a SERIAL column with UNIQUE constraint.
What, if any, differences between the two which are not obviously visible in SQL statements might bite us? I'm looking for (probably subtle) assumptions about behaviour such as any differences in autocommit, need to add constraints which aren't in MySQL etc.
I'm trying to tease out any gotchas for a couple of reasonably smart, attentive guys who aren't gurus in either of the databases.
This is a one-way commitment so if there are major benefits we will get by adding new declarations I'd appreciate them pointing out.
Note: we're not using any form of parameterised queries and, yes, I've pointed out issues with injection attacks as a required audit of the code.
Yes, for the curious, this decision was prompted by GPL issues, not that we're averse to paying for licenses but, unfortunately, the sole REALbasic driver for MySQL was GPL. As of May 2009, Real Software have released a new Community driver which is GPL, and properly includes source. They have promised a non-GPL Enterprise driver in the near future.
I am prepared to believe that the answer might be there are no invisible monsters under the bed but thought I'd ask to be sure.

A: *

*
select count(*) from table;

will be slow, as it needs to read entire table. It needs workarounds if you need to count big tables often. This is needed to ensure multiversion concurrency control.

*In the latest version (8.3) there's no implicit cast to text, which means that for example

select 234 like '2%';

will throw error. You'll need explicit cast like:

select 234::text like '2%';

*Update is really a delete+insert. As space used by deleted rows is not immediately freed then if you update entire table in one transaction then you'll need double the space.
Postgresql is a very good database, you'll love it in no time. It has several very useful features that you'll then miss in other, even commercial databases. For example transactional data definition language or savepoints.

A: http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL

A: When I made the migration from MySQL to PostgreSQL, several things really got in my way:
1) The code writing to the MySQL database was broken and feeding the database garbage a real database that had foreign keys would have prevented.  Be prepared to find "surprise" garbage data once you add in referential integrity.
2) MySQL's indexes on strings are case insensitive!  If you have a primary key on something like a username, "Coryking" and "CORYKING" are the same according to MySQL.  On PostgreSQL, they are different.  I wasn't aware of this until there started to be people who were registering duplicate usernames that should already be in the database.
3) MySQL likes to automagically add nonsense default values to columns you specify as "NOT NULL".  For example, if you specify a VARCHAR(255) NOT NULL, it will turn that column definition into "VARCHAR(255) NOT NULL DEFAULT ''".
4) PostgreSQL likes huge queries--MySQL doesn't.  You'll have a lot of fun after the migration improving your database queries--don't be shy about it either.

A: Unless you've been SQL92-compliant with your column-typing, you will run into differences in the names of types between the two.
In-query variable modification doesn't work in postgreSQL, for instance, this will work in MySQL but not in postgreSQL (I haven't tested this recently, maybe it does work now.)
SET @a:=1
SELECT ID,@a:=@a+1 FROM some_table;
I also personally believe that postgreSQL has better handling of complex queries that include sub-selects and the like (which most MySQL users used to avoid).
Edit: Oh, and I nearly forgot! The way postgreSQL stores tables is utterly different than how MySQL does. This might affect your backup/restore strategies, too.

A: I don't know if you use PHP or not but I've found that addslashes works relatively well for MySQL but bombs fast in Postgres.  Either use pg_escape_string() or better yet a prepared statement.

A: Depending on the amount of queries involved (and if you have someone inhouse to do it), it might be wise to extract all the queries, adapt them as necessary and run them on two copies of the existing DB, one running mysql and one running posgresl. Looking at the produced logs and comparing resulting datas might show some interesting hints. The first step could also be done by executing unit tests, manual or script based testing of the application.

A: Based on the WikiVS comparison I just found a number of interesting points, most not really gotchas, such as:
 - subqueries are a lot faster in Postgres, this isn't really a gotcha but means some workarounds can be removed
That site did lead me to the Postgres Gotchas list, which had more details on count(*) speed and another sequential scan issue: Max and Min are sequential scans. This is much more likely to hurt our performance than anything else identified so far. However, that article includes a Max(col) workaround:
SELECT col FROM table ORDER BY col DESC LIMIT 1


text:
Q: Copy files from source to destination but deleting any files in destination but NOT in source So I am cloning one folder to another using Bash. Currently my script is recursive and noclobber. Works great.
!cp -r -n /content/gdrive/Shared\ drives/Source/. /content/gdrive/Shared\ drives/Destination

This copies just fine. I just am looking for a way to delete any files if NOT on the Source drive but IS on the Destination drive. Maybe I need an entirely different script method?
Edit. I ended up using
!rsync -v -r --ignore-existing /gdrive/Shared\ drives/Source/. /gdrive/Shared\ drives/Destination --delete

Seems to be working for now. I was using -u but it seemed to be re-copying files just because the date changed, not the file itself. Thanks 1218985 for the help!

A: You can do it like this with rsync:
rsync --delete "/content/gdrive/Shared\ drives/Source/" "/content/gdrive/Shared\ drives/Destination/"


text:
Q: Stdin Not Working As Intended [Python] I'm running through some exercises in Python right now, including a simple line counter that can take input from the command line or stdin:
#### line_count1.py ####

import sys

def count_lines(file):
    n = 0
    for line in file:
        n = n + 1
    return n

if len(sys.argv) == 1:
    print("Needs stdin")
    file = sys.stdin
else:
    print("File given at command line")
    file = open(sys.argv[1])

print (count_lines(file))

If I enter a file at the command line, ie python line_count1.py file_with_4_lines.txt, it works great, and I get the output:
File given at command line
4

However, if I enter it so that it DOES need stdin via python line_count1.py, I get the following output:
Needs stdin
_

But never actually does anything with my stdin entry. I can enter file_with_4_lines.txt, but then it just takes it and waits for me to input another stdin line, never breaking out until I have to kill the code in Task Manager.
What would be causing this to happen? From my understanding, as soon as I enter something for stdin that should trigger the rest of the code to go through. But it's not. What am I missing?

A: This is not related to your code, but related to the stdin read behaviour on a terminal. See the following post for more information: https://unix.stackexchange.com/questions/16333/how-to-signal-the-end-of-stdin-input.
EDIT:
As @Chase said, the key to terminate stdin on window is Ctrl+Z, and on linux it is Ctrl+D.

A: It sounds like you want to accept a filename from stdin if not given at the command line, when what you're doing right now is attempting to count stdin itself.
If the goal is to process a given file, where the name comes from either stdin or the command line, then the code should be changed to:
if len(sys.argv) == 1:
    # Prompt for and read a single line from stdin to get the desired file name
    filename = input("Needs stdin")  # On Py2, use raw_input, not input
else:
    print("File given at command line")
    # Use argument as filename
    filename = sys.argv[1]

# Open the name provided at stdin or command line
# Use with statement so it's properly closed when you're done
with open(filename) as file:
    print(count_lines(file))


text:
Q: Should I use sublime text editor for Web Development in Ubuntu or is there some better editors? I want to do some Web Development. I used to have sublime text editor in Windows. Now that i have switched to Ubuntu 14.04.01, I was wondering which is the best test editor to use for easily creating web pages.

A: If you felt comfortable using Sublime Text then that is ok to use since the Command Palette and extensibility were clear advantages . From my personal experience i suggest you to try "vim or emacs".

A: If you're looking for something simpler than sublime but still highlights syntax and has autocomplete, kedit is a good choice.


text:
Q: Centered picture in header and footer of LaTeX file I try to add a centered picture in the header and the footer of my documents title page. It should look like in the first picture, that I have just created in a word processing program.
I tried two different ways, to realize this idea in LaTeX:
The first one was based on scrlayer-scrpage. I used this package with the following code:
\documentclass{article}
\usepackage{scrlayer-scrpage, graphicx}
\pagestyle{scrheadings}
\clearpairofpagestyles
\chead{\includegraphics{Picture1.png}}
\begin{document}
\centering{Title}
\end{document}

The result of this code and the package was not like it wanted it to be. This can also be seen in the second picture, that I attached to this post. The picture is just too far on the left side. It is not centered.
Because of that I tried the second way, for which I used fancyhdr. For this package, I developed the following code:
\documentclass{article}
\usepackage{graphicx}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[C]{\includegraphics{Picture1.png}}
\begin{document}
\centering{Title}
\end{document}

Like you can see in the third picture, this package and the developed code is not the right solution as well, because the picture is not high enough and also to far on the right side.
Because of that I just want to ask if there is any other solution to realize my idea of a centered picture in header and footer of LaTeX file.

EDIT:

A: This is a solution with scrlayer-scrpage. Perhaps there are simpler ones with the background or tikz packages. The good thing about this is that you can apply this page style whenever you want. You can use it with many classes and geometry (margin) layouts. The ruler is just for reference.

\documentclass[a4paper]{mwart}
\usepackage{scrlayer-scrpage}
\usepackage{graphicx,xcolor}
%\usepackage[margin=2cm,includeheadfoot]{geometry}

\DeclareNewLayer[
  background,
  topmargin,
 % align=t,
  height=5cm,
  %hoffset=7cm,
  %addheight=\headheight,
  mode=picture,
  contents={\includegraphics[height=5cm]{frog.jpg}}
]{top}

\DeclareNewLayer[
  background,
  bottommargin,
  %addheight=\headheight,
  mode=picture,
  contents={\includegraphics[height=\layerheight,width=\layerwidth]{example-image-b}}
]{bottom}

\DeclareNewLayer[
  background,
  %outermargin,
  %topmargin,
  contents=\layercontentsmeasure
]{measurelayer}

%\defpairofpagestyles[plain.scrheadings]{title}{} %use this if you want plain (bottom number) on 1st page
\defpairofpagestyles{title}{}

\AddLayersToPageStyle{title}{top,bottom,measurelayer}
%\DeclareNewPageStyleByLayers{title}{top,bottom,measurelayer} %an alternative you want to create an empty style

\title{asdf} \author{asdf}

\begin{document}

\maketitle
\thispagestyle{title}
\newpage
\setcounter{page}{1}
asdf

\end{document}