Q: How to hide Qcheckbox when Qcombox box selects an item? from PyQt5 import QtCore, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(762, 590)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.checkBox = QtWidgets.QCheckBox('box', self.centralwidget)
        self.checkBox.setGeometry(QtCore.QRect(150, 75, 181, 20))
        self.checkBox.setObjectName("checkBox")

        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(150,160,100,20))
        self.comboBox.addItem("Yes")
        self.comboBox.addItem("No")
        self.comboBox.setObjectName("comboBox")

        MainWindow.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "11"))

        MainWindow.show()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

I have created a combobox with "Yes" and "No", I want to hide the checkbox when I select "No" in the combobox, Can anyone help?
I tried to creat a function that when self.comboBox.currentText == "Yes" , run self.checkBox.hide(), but it didn't work...

A: You have to use the currentTextChanged signal that notifies you if the QComboBox selection has been changed sending you the new text, then you should only compare it with the text and together with the setVisible() method fulfill your requirement.
    self.comboBox.currentTextChanged.connect(self.handle_current_text_changed)

def handle_current_text_changed(self, text):
    self.checkBox.setVisible(text == "Yes")

A: Use signals and slots to do this.  Capture the Combobox's editTextChanged signal with a slot hideCheckBox.
comboBox.currentTextChanged.connect(func)
In the function func simply setVisibility to false when the text is "NO" and true when text is "YES".

A: If you want to hide the checkbox when the comboBox state is HIDE, for example, and unhide checkBox when the combobox state is UNHIDE, use an IF construction to catch the state of the combobox. Depending on the state, apply one or the other value to the checkbox:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(762, 590)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.checkBox = QtWidgets.QCheckBox('box', self.centralwidget)
        self.checkBox.setGeometry(QtCore.QRect(150, 75, 181, 20))
        self.checkBox.setObjectName("checkBox")

        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(150,160,100,20))
        self.comboBox.addItem("UNHIDE")
        self.comboBox.addItem("HIDE")
        self.comboBox.setObjectName("comboBox")

        MainWindow.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.comboBox.currentTextChanged.connect(self.hidefunction) # code for connect to function below

    def hidefunction(self):
        text = str(self.comboBox.currentText())
        # this is the state of the current text in combobox. Below simple IF block.
        if text == "UNHIDE":
            self.checkBox.setHidden(False)
        # its HIDE - your checkBox when comboBox changed his state
        else:
            self.checkBox.setHidden(True)
        # its HIDE your checkBox when comboBox changed his state

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "11"))

        MainWindow.show()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


Q: angularjs: directive and ng-repeat add extra div I've got the directive as follows:
app.directive("photos", function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            "photoid": "@",
            "scrollable": "@",
            "size": "@",
            "list": "=",
            "inline": "@",
            "extension": "@"
        },
        template:
        '
\n\
            length={{list.length}}\n\

\n\

{{p.text}}
\n\

\n\

'
    };
});

I invoke it twice as follows:

Impact de la densité sur le rendement grain d'une variété

    <photos photoid="ImpactPrecoce"     list="[{file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactPrecoce'}]"        size="256px" extension="png"></photos>
    <photos photoid="ImpactDemiPrecoce" list="[{file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactDemiPrecoce'}]"    size="256px" extension="png"></photos>

The result is OK, except that I end up with an extraneous did tag within the photos tag replacement.
I'm stuck with this, I really dont know where it comes from.
Any one can help?

[edit 1] Those div do not come from the option text div. Here is a version with optional text provided and the related screen shot.
<photos photoid="ImpactPrecoce"
        list="[
            {file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactPrecoce', text:'first'},
            {file:'rsc/drive/4-Semis/d-ChoixDeLaDensite/ImpactDemiPrecoce', text:'second'}
        ]"
    size="256px"
    extension="png"></photos>

See screen shot:

A: You have an unclosed div at the end of your block (which should be the closing tag), the browser closes it automatically, as well as the parent one. So two last lines:

\n\

'

should be:

\n\

'

A: Ok, I found it:

\n\

'
};


Q: How to implement SSL on Apache 2.2 Is there a step by step way to configure SSL on Apache 2.2. I have searched and tried a lot of things but the configuration is not working.

A: Check these links. These might be useful for your case
http://extrimity.in/content/enable-ssl-or-https-ubuntu-1104-apache-2
http://wiki.vpslink.com/Enable_SSL_on_Apache2
http://docs.oracle.com/cd/A95431_01/install/ssl.htm
Step by step
https://www.digitalocean.com/community/articles/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-12-04
http://www.digicert.com/ssl-certificate-installation-apache.htm
http://www.debian-administration.org/articles/349


Q: Máquina Ubuntu con Vagrant no levanta Muy buenas
Estoy con Windows 10 usando Vagrant. Resulta que quiero disfrutar de una máquina virtual con Ubuntu. Cree el siguiente Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/focal64"

  config.vm.network "forwarded_port", guest: 3000, host: 3000
  config.vm.network "forwarded_port", guest: 3001, host: 3001
  config.vm.network "forwarded_port", guest: 3306, host: 3002
  config.vm.network "forwarded_port", guest: 27017, host: 3003
  config.vm.network "forwarded_port", guest: 80, host: 3004
  config.vm.network "forwarded_port", guest: 8080, host: 3005

  config.vm.synced_folder "E:\\dev", "/workspace"

  config.vm.provision "file", source: "secure_mongo.js", destination: "./"
  config.vm.provision "shell", path: "provision.sh"
  config.vm.provision "shell", path: "secure_mysql.sh"

end

Cuando levanto la máquina con vagrant up muestra el siguiente mensaje
λ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/focal64'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'ubuntu/focal64' version '20220608.0.0' is up to date...
==> default: A newer version of the box 'ubuntu/focal64' for provider 'virtualbox' is
==> default: available! You currently have version '20220608.0.0'. The latest is version
==> default: '20220610.0.0'. Run `vagrant box update` to update.
==> default: Setting the name of the VM: ubuntu-v_default_1655215167623_38012
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 3000 (guest) => 3000 (host) (adapter 1)
    default: 3001 (guest) => 3001 (host) (adapter 1)
    default: 3306 (guest) => 3002 (host) (adapter 1)
    default: 27017 (guest) => 3003 (host) (adapter 1)
    default: 80 (guest) => 3004 (host) (adapter 1)
    default: 8080 (guest) => 3005 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.

If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

Me dice que tengo que aumentar el timeout, pero es que se queda indefinidamente esperando. Cuando hago vagrant ssh no hace absolutamente nada. Con Putty intenté conectarme pero no se puede. Si fuera en el momento de aprovisionamiento, por pantalla mostraría el error al levantarlo.
¿A alguien le ha pasado lo mismo?
Gracias y cuidense.


Q: How do I search for a string using Line Input and then print the next 5 lines in Excel cell How do I search for a string, then when the string is found, write the entire line where the string is found, and then the next five lines into the same Cell in Excel using VBA?
Basically, I have a text file that I am importing into Excel using VBA. Based on a string, data from the file goes into cells under the appropriate column heading. The problem I am having is that some of my data is cut off at a line break. Due to the limitation of Line Input.
This condition does not happen for all values, just the ones with line breaks like this one:
    How To Fix: To remove this functionality, set the following Registry key settings:
    Hive: HKEY_LOCAL_MACHINE
    Path: System\CurrentControlSet\Services...
    Key: SomeKey
    Type: DWORD
    Value: SomeValue
    Related Links: Some URL

I'm trying to get everything from How to Fix:... to Value:... to write to my Excel sheet, in the same Cell along with the data on the How to fix:... line.
I know that Input Line automatically stops at line breaks and moves on to the next line. Which, w/o the my loop attempts, is what the code below does.
 If InStr(inputline, "How to Fix:") <> 0 Then
    'Do While Not InStr(inputline, "Related Links:")
    ' Get rid of special characters in string
       For i = 1 To Len(description)
            sletter = Mid(description, i, i + 1)
            iasc = Asc(sletter)
           If Not (iasc <= 153 And iasc >= 32) Then
                  description = Left(description, i - 1) & " " & Right(description, Len(description) - i)
           ' End If

       'Next
       Do Until InStr(inputline, "Related Links:") = 1
            description = Replace(description, "How to Fix:", "")
            ws.Cells(rowndx4, 7).Value = Trim(description)
        Loop
End If

I also tried using a FileSystemObject but it doesn't print anything to the Excel worksheet. The code is below:
Private Function ScanFile2$(FileToRead2 As String, rowndx4 As Long)

Dim wb As Workbook, ws As Worksheet, i As Long
Dim FNum3 As Integer, inputline As String, whatfile As Integer, testnum As String
Dim description As String
Dim finding As String

Set ws = ActiveWorkbook.Worksheets("Sheet1")
    FNum3 = FreeFile()

Dim oFSO As FileSystemObject
Set oFSO = New FileSystemObject
Dim TS As TextStream
Const ForReading = 1
Set TS = oFSO.OpenTextFile(FNum3, ForReading)

Do While TS.AtEndOfStream <> True
inputline = TS.ReadAll
description = inputline

If InStr(inputline, "How To Fix:") <> 0 Then
            description = Replace(inputline, "How To Fix:", "")
            ws.Cells(rowndx4, 2).Value = inputline
End If
Exit Do
Loop
Close FNum3
Set ws = Nothing
Application.ScreenUpdating = True
ScanFile2 = rowndx4
End Function

A: Here's the full code
  Sub test()
  ' Open the text file
    Workbooks.OpenText Filename:="C:\Excel\test.txt"

  ' Select the range to copy and copy
    Range("A1", ActiveCell.SpecialCells(xlLastCell)).Select
    Selection.Copy

  ' Assign the text to a variable
    Set my_object = CreateObject("htmlfile")
    my_var = my_object.ParentWindow.ClipboardData.GetData("text")
  ' MsgBox (my_var)   ' just used for testing
    Set my_object = Nothing

    pos_1 = InStr(1, my_var, "How to fix:", vbTextCompare)
    pos_2 = InStr(pos_1, my_var, "Related Links", vbTextCompare)
    my_txt = Mid(my_var, pos_1, -1 + pos_2 - pos_1)

  ' Return to the original file and paste the data
    Windows("stackoverflow.xls").Activate
    Range("A1") = my_txt

  ' Empty the clipboard
    Application.CutCopyMode = False
  End Sub

This works for me...
first, assign the text in the text file to a variable (my_var in the example below)
  pos_1 = InStr(1, my_var, "How to fix:", vbTextCompare)
  pos_2 = InStr(pos_1, my_var, "Related Links", vbTextCompare)
  my_txt = Mid(my_var, pos_1, -1 + pos_2 - pos_1)
  Range("wherever you want to put it") = my_txt

You can also clean up my_txt using the "replace" function if you like.

A: This code

*

*uses a RegExp to remove the linebreaks (replaced with a |) to flatten then string

*then extracts each match with a second RegExp
change your filepath here c:\temo\test.txt
sample input and output at bottom
code
Sub GetText()

Dim objFSO As Object
Dim objTF As Object
Dim objRegex As Object
Dim objRegMC As Object
Dim objRegM As Object
Dim strIn As String
Dim strOut As String
Dim lngCnt As Long

Set objRegex = CreateObject("vbscript.regexp")
Set objFSO = CreateObject("scripting.filesystemobject")
Set objts = objFSO.OpenTextFile("c:\temp\test.txt")

strIn = objts.readall

With objRegex
.Pattern = "\r\n"
.Global = True
.ignorecase = True
strOut = .Replace(strIn, "|")
.Pattern = "(How to Fix.+?)Related"
Set objRegMC = .Execute(strOut)
For Each objRegM In objRegMC
lngCnt = lngCnt + 1
Cells(lngCnt, 7) = Replace(objRegM.submatches(0), "|", Chr(10))
Next
End With

End Sub

input

test
  How To Fix: To remove this functionality, set the following Registry key settings:
      Hive: HKEY_LOCAL_MACHINE
      Path: System\CurrentControlSet\Services...
      Key: SomeKey
      Type: DWORD
      Value: SomeValue
      Related Links: Some URL
  otherstuff
  How To Fix: To remove this functionality, set the following Registry key settings:
      Hive: HKEY_LOCAL_MACHINE
      Path: System\CurrentControlSet\Services...
      Key: SomeKey
      Type: DWORD
      Value: SomeValue2
  Related Links: Some URL2

output


Q: The different meanings
Items believed to belong to passengers have also been found in the water, including baby shoes, ID cards and driver's licences.

The text is from bbc news
My question here is can i used the following words instead.
1.items believed to be belonging to
2.items believed to be belonged to
I think the first 1 i can use definately but what about the second one

A: "Believed to belong to..." seems the most concise and straightforward way of saying this. However, "believed to be belonging to..." is perfectly correct grammatically, it just sounds a bit odd.
In a simpler example, you could say "I give you this ring" (simple sentence) or "I am (conjugation of "to be") giving you this ring". In both these cases, when you add -ing to the end of the verb, you change it to the present participle.
"Believed to be belonged to..." doesn't make sense, as something can "be belonging" (present participle), but can't "be belonged". You could use the past participle construction - "have belonged", and say "Believed to have belonged to..." This would also imply that the items no longer belong to the passengers, which may be inaccurate.


Q: Python threading - continuously save results from other threads I want to get data from two sensor by means of threads. Assume, that these data are available by calling a corresponding funtion. These sensors should continuously be queried, but their values should only be saved when the time difference between two measurements is greater than a pre-defined threshold (only save data when the time difference to the last saved data is greater than 10 seconds). Since both threads for the data collection run in a while loop, I use another thread for saving the data. However, I have to somehow ensure that these data are available when saving. So the thread for saving has to wait for both other threads. Currently, I use time.sleep() which is working. But is there a better way to save the data of the two other threads?
import threading
import copy
import time

def thread1():
    global connected
    global data
    while connected:
        sensor_data = getSensorData()
        data['x'] = sensor_data.x
        data['y'] = sensor_data.y
        data['time'] = sensor_data.time

def thread2():
    global connected
    global data
    while connected:
        other_sensor_data = getOtherSensorData()
        data['h'] = other_sensor_data.h

def save_data():
    global connected
    global data
    global results
    while connected:
        time.sleep(0.1)
        if len(results) == 0 and len(data) > 0:
            results.append(copy.deepcopy(data))
        elif len(results) >= 1:
            if data['time'] - results[-1]['time'] >= 10:
                results.append(copy.deepcopy(data))

if __name__ == '__main__':
    global connected
    global data
    global result

    connected = True
    data = {}
    if 'result' not in globals():
        result = []

    first_thread = threading.Thread(target=thread1)
    second_thread = threading.Thread(target=thread2)
    save_thread = threading.Thread(target=save_data)
    first_thread.start()
    second_thread.start()
    save_thread.start()

A: Personally I would use the build-in module queue which is designed to safely retrieve data from threads.
Using the LIFO functionality to create piles and then emptying them.
Here's a working example:
import threading
import queue
import time

sensor_pile = queue.LifoQueue()
other_sensor_pile = queue.LifoQueue()

def getSensorData():
    time.sleep(0.05)

    class Test:
        x = "x " + str(time.time())
        y = "y " + str(time.time())
        time = time.time()
    return Test

def getOtherSensorData():
    time.sleep(0.01)

    class Test:
        h = "h " + str(time.time())
    return Test

def thread1():
    global connected
    while connected:
        sensor_pile.put(getSensorData())

def thread2():
    global connected
    while connected:
        other_sensor_pile.put(getOtherSensorData())

def save_data():
    global connected
    global results

    last_time = -float("inf")

    # Use other_sensor_pile.get() if the first h value should not be None
    h = None

    while connected:
        data = sensor_pile.get()  # Will wait to receive data.
        # As the main pile, the main while loop will keep it empty.

        try:
            # Update h to the latest value and then empty the pile.

            # get_nowait will get the data if it is available
            # or raise a queue.Empty error if it isn't.
            h = other_sensor_pile.get_nowait().h

            while True:
                other_sensor_pile.get_nowait()
        except queue.Empty:
            pass

        if data.time - last_time >= 0.2:  # Shortened for the sake of testing.
            last_time = data.time
            results.append({
                'time': last_time,
                'x': data.x,
                'y': data.y,
                'h': h
            })

if __name__ == '__main__':
    global connected
    global results

    connected = True
    if 'results' not in globals():
        results = []

    first_thread = threading.Thread(target=thread1)
    second_thread = threading.Thread(target=thread2)
    save_thread = threading.Thread(target=save_data)
    first_thread.start()
    second_thread.start()
    save_thread.start()

    time.sleep(1)

    connected = False
    save_thread.join()
    second_thread.join()
    first_thread.join()
    for line in results:
        print(line)

With the example output:
{'time': 1627652645.7188394, 'x': 'x 45.7188', 'y': 'y 45.7188', 'h': 'h 45.7032'}
{'time': 1627652645.9584458, 'x': 'x 45.9584', 'y': 'y 45.9584', 'h': 'h 45.9584'}
{'time': 1627652646.1991317, 'x': 'x 46.1991', 'y': 'y 46.1991', 'h': 'h 46.1991'}
{'time': 1627652646.4394188, 'x': 'x 46.4394', 'y': 'y 46.4394', 'h': 'h 46.4394'}
{'time': 1627652646.6793587, 'x': 'x 46.6793', 'y': 'y 46.6793', 'h': 'h 46.6793'}

The emptying of the pile isn't very efficient and can cause problems if the data is put in faster than it can be emptied.
There may be some other methods to do this but I'm not sure how it would work. See:
multithreading - overwrite old value in queue?


Q: JNA with Fortran assumed size array I have a Fortran subroutine taking an assumed size array:
subroutine sub(arr)
  implicit none
  double precision arr(*)
end subroutine

I made a native call from Java using JNA, the Fortran subroutine is compiled as a shared library mylib.so:
import com.sun.jna.Library;
import com.sun.jna.Native;

public class Wrapper {
    public interface MyLib extends Library {
        public void sub_(double[] arr);
    }

    public static void main(String[] args) {
        System.setProperty("jna.library.path", ".");
        MyLib lib = (MyLib) Native.loadLibrary("mylib.so", MyLib.class);
        double[] myarr = new double[10];
        lib.sub_(myarr);
    }
}

Now, is there a way to get (in the Fortran subroutine) the size of the array I passed into this subroutine without passing the actual size (10 in this case) as an additional argument?
I tried (Fortran) print*, size(arr), but that gives a compiler error:
   print*,size(arr)
              1
Error: The upper bound in the last dimension must appear in the reference to the assumed size array ‘arr’ at (1)

A: You will need to pass the length as an additional parameter. Using an assumed-shape array will not work, here's why:
In the ABI employed by most Fortran compilers, arrays as parameters ("dummy arguments") can take one of two representations, depending on the interface used in the subroutine/function:

*

*Those passed with known sizes or assumed sizes, like arr(n) or arr(*), usually receive just a pointer to the first element, with elements assumed to be contiguous.

*Those passed with assumed shapes, like arr(:) receive an array descriptor structure. This is completely implementation dependent, but usually such a structure contains the pointer to the first element of the data plus information on the bounds of each dimension, the stride, etc.

That is the reason why you can directly pass a single row, or only the elements in even indices, of an array if the function receives it as an assumed shape array: the descriptor structure encodes the information that the data is not necessarily contiguous and so the Fortran compiler does not need to copy arr(5:2:) to a temporary location in memory.
The reason why you cannot use such facilities to communicate with Java is that the descriptor structure is completely non-standard, a part of the particular ABI of each compiler. Thus, even if you somehow managed to understand how to build it (and it would be non trivial) the next version of your compiler could bring a total change.


Q: Calling service from one docker container to other container is causing net::ERR_NAME_NOT_RESOLVED i am running application with multi containers as below..
feeder - is a simple nodejs container from image node:alpine
api - is nodejs container with expressjs from image node:alpine
ui-app - is react app container from image node:alpine
i am trying to call the api service in ui-app i am getting error as below
image to Console Log
image to Console Log
not sure what is causing the problem
if i access the services as http://192.168.99.100/ping it works (that is my docker machine default ip)...
but if i use container name like http://api:3200/ping it is not working...? please help..
the below is my docker-compose.
version: '3'

services:
  feeder:
    build: ./feeder
    container_name: feeder
    tty: true
    depends_on:
      - redis
    links:
      - redis
    environment:
      - IS_FROM_DOCKER=true
    ports:
      - "3100:3100"
    networks:
      - hmdanet
  api:
    build: ./api
    container_name: api
    tty: true
    depends_on:
      - feeder
    links:
      - redis
    environment:
      - IS_FROM_DOCKER=true
    ports:
      - "3200:3200"
    networks:
      hmdanet:
        aliases:
          - "hmda-api"
  ui-app:
    build: ./ui-app
    container_name: ui-app
    tty: true
    depends_on:
      - api
    links:
      - api
    environment:
      - IS_FROM_DOCKER=true
    ports:
      - "3000:3000"
    networks:
      - hmdanet
  redis:
    image: redis:latest
    ports:
      - '6379:6379'
    networks:
      - hmdanet
networks:
  hmdanet:
    driver: bridge

A: You can only use service name as a domain name when you are inside a container. In you case it's your browser making the call, it does not know what api is. In you web app, you should have an env like base url set to the ip of your docker machine or localhost.


Q: Substring extraction using bash shell scripting and awk So, I have a file called 'dummy' which contains the string:
"There is 100% packet loss at node 1".

I also have a small script that I want to use to grab the percentage from this file. The script is below.
result=`grep 'packet loss' dummy` |
awk '{  first=match($0,"[0-9]+%")
        last=match($0," packet loss")
        s=substr($0,first,last-first)
        print s}'

echo $result

I want the value of $result to basically be 100% in this case. But for some reason, it just prints out a blank string. Can anyone help me?

A: You would need to put the closing backtick after the end of the awk command, but it's preferable to use $() instead:
result=$( grep 'packet loss' dummy |
awk '{  first=match($0,"[0-9]+%")
    last=match($0," packet loss")
    s=substr($0,first,last-first)
    print s}' )

echo $result

but you could just do:
result=$( grep 'packet loss' | grep -o "[0-9]\+%" )

A: Try
awk '{print $3}'

instead.

A: the solution below can be used when you don't know where the percentage numbers are( and there's no need to use awk with greps)
$ results=$(awk '/packet loss/{for(i=1;i<=NF;i++)if($i~/[0-9]+%$/)print $i}' file)
$ echo $results
100%

A: You could do this with bash alone using expr.
i=`expr "There is 98.76% packet loss at node 1" : '[^0-9.]*\([0-9.]*%\)[^0-9.]*'`; echo $i;

This extracts the substring matching the regex within \( \).

A: Here I'm assuming that the output lines you're interested in adhere strictly to your example, with the percentage value being the only variation.
With that assumption, you really don't need anything more complicated than:
awk '/packet loss/ { print $3 }' dummy

This quite literally means "print the 3rd field of any lines containing 'packet loss' in them".  By default awk treats whitespace as field delimiters, which is perfect for you.
If you are doing more than simply printing the percentage, you could save the results to a shell variable using backticks, or redirect the output to a file.  But your sample code simply echoes the percentages to stdout, and then exits.  The one-liner does the exact same thing.  No need for backticks or $() or any other shell machinations whatsoever.
NB: In my experience, piping the output of grep to awk is usually doing something that awk can do all by itself.


Q: How to display percentile stats per URL on the console I'm am working on writing some performance tests using Taurus & Jmeter.
After executing a set of tests on a some URLs, I see the stats on console as below.
19:03:40 INFO: Percentiles:
+---------------+---------------+
| Percentile, % | Resp. Time, s |
+---------------+---------------+
|          95.0 |         2.731 |
+---------------+---------------+
19:03:40 INFO: Request label stats:
+--------------+--------+---------+--------+-------+
| label        | status |    succ | avg_rt | error |
+--------------+--------+---------+--------+-------+
| /v1/brands   |   OK   | 100.00% |  2.730 |       |
| /v1/catalogs |   OK   | 100.00% |  1.522 |       |
+--------------+--------+---------+--------+-------+

I'm wondering if there is a way to display other labels per URL. for ex.  percentile response time per URL.
Below are all the stats that could be captured from Taurus. (according to taurus documentation), but I couldn't figure out the configuration required to display them onto the console. Appreciate any help.
label - is the sample group for which this CSV line presents the stats. Empty label means total of all labels
concurrency - average number of Virtual Users
throughput - total count of all samples
succ - total count of not-failed samples
fail - total count of saved samples
avg_rt - average response time
stdev_rt - standard deviation of response time
avg_ct - average connect time if present
avg_lt - average latency if present
rc_200 - counts for specific response codes
perc_0.0 .. perc_100.0 - percentile levels for response time, 0 is also minimum response time, 100 is maximum
bytes - total download size

A: Looking into documentation on Taurus Console Reporter it is possible to amend only the following parameters:
modules:
  console:
    # disable console reporter
    disable: false  # default: auto

    # configure screen type
    screen: console
    # valid values are:
    # - console (ncurses-based dashboard, default for *nix systems)
    # - gui (window-based dashboard, default for Windows, requires Tkinter)
    # - dummy (text output into console for non-tty cases)

    dummy-cols: 140  # width for dummy screen
    dummy-rows: 35   # height for dummy screen

If you can understand and write Python code you can try amending reporting.py file which is responsible for generating stats and summary table. This is a good point to start:
def __report_summary_labels(self, cumulative):
    data = [("label", "status", "succ", "avg_rt", "error")]
    justify = {0: "left", 1: "center", 2: "right", 3: "right", 4: "left"}

    sorted_labels = sorted(cumulative.keys())
    for sample_label in sorted_labels:
        if sample_label != "":
            data.append(self.__get_sample_element(cumulative[sample_label], sample_label))
    table = SingleTable(data) if sys.stdout.isatty() else AsciiTable(data)
    table.justify_columns = justify
    self.log.info("Request label stats:\n%s", table.table)

Otherwise alternatively you can use Online Interactive Reports or configure your JMeter test to use Grafana and InfluxDB as 3rd-party metrics storage and visualisation systems.


Q: open a new page using onClick but after that back to the previous page is not working when I click a image. It's open a new page and a value pass through this click. It's working properly. but when I click back, It's do not show the previous page.
I use this code for click.
<img src="images/view.png" hspace="5" title="View" onClick="javascript:location.href='map_view.php?ad_id=<?php echo($row["ad_id"]); ?>'" style="cursor:pointer;" />

A: In order to geocode any phisical address, or get its coordinates , you should use a geocoding API, being google maps api v3 the most popular, which by the way gives you a free starting point of up to 2500 daily requests.
There is a bunch of documentation and starting guides, the best are the google maps's own.
Of course you can geocode on PHP or Javascript. Its really easy.

A: As other answer mentioned it is possible using google maps api, you can read more and get your own API KEY (More info and Get api key).
What you need is API key from google. This will help you fetching coordinates from given address.
I have made a little demonstration how it works it might be useful for other SO users.
By using following address
https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ADDRESS&key=YOUR_API_KEY
It will return you JSON formatted results with coordinates.
Now we need to build a tiny address form and pass it it to PHP script to return us the results
HTML Address form
<form action="index.php" method="post">
    Enter Address:

    <input type="text" name="address">
    <input type="submit">
</form>

PHP code
if (isset($_POST["address"]))
{
    $addressInput = $_POST["address"];
    $address = str_replace(" ", "+", $addressInput);
} else
{
    // stack-overflow office address as default
    $address = "110+William+St,+28th+Floor+New+York,+NY+10038";

}

echo "Latitude and Longitude for address : " . str_replace("+", " ", $address) . '
';

$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=PUT_YOUR_OWN_API_KEY');
$data = json_decode($json, true);
//var_dump($data);

$getLat = $data['results'][0]['geometry']['location']['lat'];
$getLng = $data['results'][0]['geometry']['location']['lng'];

echo 'latitude ' . $getLat . ', longitude ' . $getLng;

The above working code can be tested on this link.
Moving theses data to mysql database or what ever you want to use it for, is left to you.

A: You'll probably use JavaScript for getting location of the user; not PHP. You can use HTML5 Geolocation for the purpose.
If you need to map the users location, pass the coordinates obtained using the HTML5 Geolocation API to Google Maps.
You may also need Modernizr to determine your users browser supports HTML5 Geolocation API.


Q: AutoCompleteTextView, como fazer pesquisa em qualquer ponto da sentença? Galera,
Tenho um AutoCompleteTextView e preciso que ele faça o filtro não apenas pelo início da sentença mas de qualquer parte dela.
ex> minha lista: KMF Avaré, Florisio (KMF Sorocaba)
Quando digito a letra "K" ele traz apenas o KMF Avaré, mas preciso que traga também o Florisio KMF Sorocaba.
É possível fazer a pesquisa/filtro a partir de qualquer ponto da sentença?

A: Consegui resolver. Fiz o seguinte:
Criei um BaseAdapter implementando Filterable e nela fiz a lógica do filtro:
@Override
public Filter getFilter() {

    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            if (results != null && results.count > 0) {
                notifyDataSetChanged();
            }
            else {
                notifyDataSetInvalidated();
            }
        }

        @SuppressLint("DefaultLocale") @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            listaAdapter = new ArrayList<String>();

            if (constraint != null) {

                for (String item : listaCompleta) {
                    if (item.toLowerCase().contains(constraint.toString().toLowerCase())) {
                        listaAdapter.add(item);
                    }
                }
            }
            else listaAdapter = listaCompleta;

            FilterResults results = new FilterResults();
            results.values = listaAdapter;
            results.count = listaAdapter.size();

            return results;
        }
    };

    return filter;
}


Q: PHP & MySQL username submit problem I want to allow users to either have there username field empty at any time but I get the username error message Your username is unavailable! how can I correct this problem?
Here is the PHP code.
if(isset($_POST['username'])) {

    $u = "SELECT *
          FROM users
          WHERE username  = '$username'
          AND user_id <> '$user_id'";
    $r = mysqli_query ($mysqli, $u) or trigger_error("Query: $q\n
MySQL Error: " . mysqli_error($mysqli));

    if (mysqli_num_rows($r) == TRUE) { // Unavailable.
        echo '
Your username is unavailable!
';
        $username = NULL;
    } else if(mysqli_num_rows($r) == 0) { // Available.
        $username = mysqli_real_escape_string($mysqli, $purifier->purify(htmlentities(strip_tags($_POST['username']))));
    }
}

NONE of these examples are working. I want to know how can I let my users have no username?

A: if(isset($_POST['username']) && trim($_POST['username'])!=='') {

Otherwise, $_POST['username'] will be set even if the form is submitted with an empty field.

A: if(isset($_POST['username']) && !empty($_POST['username'])) {
...


Q: Important topics/APIs list for Java interview This is little different from what already been asked for here
I would like to know what topics/APIs are most important for Java interviews. for example -

*

*Concurrency,

*Collections
.....and like that.

The reason is because implementations like ConcurrentHashMap (read here) have so much details in them, that one would like to discuss about them as it covers many important aspects

A: *

*java.io - difference between streams and writers. Buffered streams.

*java.util - the collection framework. Set and List. What's HashMap, TreeMap. Some questions on efficiency of concrete collections

*java.lang - wrapper types, autoboxing

*java.util.concurrent - synchronization aids, atomic primitives, executors, concurrent collections.

*multithreading - object monitors, synchronized keyword, methods - static and non-static.

A: I'd say there are two things you need for every java interview:

*

*For Basic knowledge of the Language, consult your favorite book or the Sun Java Tutorial

*For Best Practices read Effective Java by Joshua Bloch
Apart from that, read whatever seems appropriate to the job description, but I'd say these two are elementary.
I guess these packages are relevant for every java job:

*

*java.lang (Core classes)

*java.io   (File and Resource I/O)

*java.util (Collections Framework)

*java.text (Text parsing / manipulation)

A: IMHO its more important to have a firm understanding of the concepts rather than specific knowledge of the API and especially the internal workings of specific classes. For example;

*

*knowing that HashMap is not synchronized is important

*knowing how this might affect a multithreaded app is important

*knowing what kind of solutions exist for this problem is important

A: I wouldn't worry too much about specific API details like individual methods of ConcurrentHashMap, unless you're interviewing for a job that is advertised as needing a lot of advanced threading logic.
A thorough understanding of the basic Java API's is more important, and books like Effective Java can help there. At least as important though is to know higher level concepts like Object Orientation and Design Patterns.
Understanding what Polymorphism, Encapsulation and Inheritance are, and when and how to use them, is vital. Know how to decide between Polymorphism and Delegation (is-a versus has-a is a decent start, but the Liskov Substitution Principle is a better guide), and why you may want to favor composition over inheritance. I highly recommend "Agile Software Development" by Robert Martin for this subject. Or check out this link for an initial overview.
Know some of the core patterns like singleton, factory, facade and observer. Read the GoF book and/or Head First Design Patterns.
I also recommend learning about refactoring, unit testing, dependency injection and mocking.
All these subject won't just help you during interviews, they will make you a better developer.

A: We usually require the following knowledge on new developers:
Low level (programming) questions:
http://www.interview-questions-java.com/
Antipatterns:
http://en.wikipedia.org/wiki/Anti-pattern
Design:
http://en.wikipedia.org/wiki/Design_Patterns

A: On some of the interviews I have been to, there is also the java.io package covered, sometimes with absurd questions on what kind of exceptions would some rarely used method declare to throw, or whether some strange looking constructor overload exists.
Concurrency is always important for higher-level positions, but I think that knowing the concepts well (and understanding them ofc) would win you more points than specific API knowledge.
Some other APIs that get mentioned at interviews are Reflection (maybe couple questions on what can be achieved with it) and also java.lang.ref.Reference and its subclasses.

A: I ask some basic questions ('whats the difference between a list and a set?', 'whats an interface?', etc) and then I go off the resume.  If hibernate is on there 5 times, I expect the candidate to be able to define ORM.  You would be surprised how often it happens that they can't.  I am also interested in how the candidate approaches software -- do they have a passion for it?  And it is very important that the candidate believes in TDD.  Naturally, if its a really senior position, the questions will be more advanced (e.g. 'whats ThreadLocal and when do you use it'), but for most candidates this is not necessary.

A: Completely agree with Luke here. We can not stick to some API's to prepare for Core Java interviews. I think a complete understanding of the OOPS concept in Java is must. Have good knowledge of oops shows the interviewer that the person can learn new API's easily and quick.
Topics that should be covered are as follows:
OOPS Concept
Upcasting & DownCasting
Threading
Collection framework.
Here is a good post to get started. Core Java Interview Q & A


Q: Is it possible to determine the facet content in a custom controls design definition? I'm putting together the design definition for a custom control and would like to vary how it displays based on whether or not a different custom control has been placed in the one of the facet areas. Is this possibe with the design definition and if so, how?
I know I can reference properties of the custom control by using "this", but I couldn't guess as to how to get to the facet content information.
Any ideas? Thanks

A: In the design definition you can add a callback node where your facet should appear. This should expose the Editable Area when you add your control to another page.
The format for the callback node would look similar to
<xp:callback id="callbackID" facetName="facetname" />

A: Dan,
Can you get the Editable Area as a javax.faces.component.UIComponent and then do .getFacets()?
BTW, hope you're well!


Q: Mysql install ERROR: Database files are locked. Daemon already running? Warning: Unable to start the server At first I removed previous MySQL installation
apt autoremove  mysql-server-8.0

MySQL has been removed from services. Then I tried to install new MySQL
apt install mysql-server

which throws me an error: ERROR: Database files are locked. Daemon already running? Warning: Unable to start the server.
Installation ends up but I am not able to start the service cause it throws me an error Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Can somebody tell me please what it means? What daemon is running if I removed it from system?
Here is the whole installation log from terminal:
root@camotestserver:~# apt install mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libcgi-fast-perl libcgi-pm-perl libencode-locale-perl libevent-core-2.1-7 libfcgi-perl libhtml-parser-perl libhtml-tagset-perl libhtml-template-perl libhttp-date-perl
  libhttp-message-perl libio-html-perl liblwp-mediatypes-perl libmecab2 libtimedate-perl liburi-perl mecab-ipadic mecab-ipadic-utf8 mecab-utils mysql-server-8.0 mysql-server-core-8.0
Suggested packages:
  libdata-dump-perl libipc-sharedcache-perl libwww-perl mailx tinyca
The following NEW packages will be installed:
  libcgi-fast-perl libcgi-pm-perl libencode-locale-perl libevent-core-2.1-7 libfcgi-perl libhtml-parser-perl libhtml-tagset-perl libhtml-template-perl libhttp-date-perl
  libhttp-message-perl libio-html-perl liblwp-mediatypes-perl libmecab2 libtimedate-perl liburi-perl mecab-ipadic mecab-ipadic-utf8 mecab-utils mysql-server mysql-server-8.0
  mysql-server-core-8.0
0 upgraded, 21 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/26.1 MB of archives.
After this operation, 182 MB of additional disk space will be used.
Do you want to continue? [Y/n]
Preconfiguring packages ...
Selecting previously unselected package libevent-core-2.1-7:amd64.
(Reading database ... 100373 files and directories currently installed.)
Preparing to unpack .../00-libevent-core-2.1-7_2.1.11-stable-1_amd64.deb ...
Unpacking libevent-core-2.1-7:amd64 (2.1.11-stable-1) ...
Selecting previously unselected package libmecab2:amd64.
Preparing to unpack .../01-libmecab2_0.996-10build1_amd64.deb ...
Unpacking libmecab2:amd64 (0.996-10build1) ...
Selecting previously unselected package mysql-server-core-8.0.
Preparing to unpack .../02-mysql-server-core-8.0_8.0.20-0ubuntu0.20.04.1_amd64.deb ...
Unpacking mysql-server-core-8.0 (8.0.20-0ubuntu0.20.04.1) ...
Selecting previously unselected package mysql-server-8.0.
Preparing to unpack .../03-mysql-server-8.0_8.0.20-0ubuntu0.20.04.1_amd64.deb ...
Unpacking mysql-server-8.0 (8.0.20-0ubuntu0.20.04.1) ...
Selecting previously unselected package libhtml-tagset-perl.
Preparing to unpack .../04-libhtml-tagset-perl_3.20-4_all.deb ...
Unpacking libhtml-tagset-perl (3.20-4) ...
Selecting previously unselected package liburi-perl.
Preparing to unpack .../05-liburi-perl_1.76-2_all.deb ...
Unpacking liburi-perl (1.76-2) ...
Selecting previously unselected package libhtml-parser-perl.
Preparing to unpack .../06-libhtml-parser-perl_3.72-5_amd64.deb ...
Unpacking libhtml-parser-perl (3.72-5) ...
Selecting previously unselected package libcgi-pm-perl.
Preparing to unpack .../07-libcgi-pm-perl_4.46-1_all.deb ...
Unpacking libcgi-pm-perl (4.46-1) ...
Selecting previously unselected package libfcgi-perl.
Preparing to unpack .../08-libfcgi-perl_0.79-1_amd64.deb ...
Unpacking libfcgi-perl (0.79-1) ...
Selecting previously unselected package libcgi-fast-perl.
Preparing to unpack .../09-libcgi-fast-perl_1%3a2.15-1_all.deb ...
Unpacking libcgi-fast-perl (1:2.15-1) ...
Selecting previously unselected package libencode-locale-perl.
Preparing to unpack .../10-libencode-locale-perl_1.05-1_all.deb ...
Unpacking libencode-locale-perl (1.05-1) ...
Selecting previously unselected package libhtml-template-perl.
Preparing to unpack .../11-libhtml-template-perl_2.97-1_all.deb ...
Unpacking libhtml-template-perl (2.97-1) ...
Selecting previously unselected package libtimedate-perl.
Preparing to unpack .../12-libtimedate-perl_2.3200-1_all.deb ...
Unpacking libtimedate-perl (2.3200-1) ...
Selecting previously unselected package libhttp-date-perl.
Preparing to unpack .../13-libhttp-date-perl_6.05-1_all.deb ...
Unpacking libhttp-date-perl (6.05-1) ...
Selecting previously unselected package libio-html-perl.
Preparing to unpack .../14-libio-html-perl_1.001-1_all.deb ...
Unpacking libio-html-perl (1.001-1) ...
Selecting previously unselected package liblwp-mediatypes-perl.
Preparing to unpack .../15-liblwp-mediatypes-perl_6.04-1_all.deb ...
Unpacking liblwp-mediatypes-perl (6.04-1) ...
Selecting previously unselected package libhttp-message-perl.
Preparing to unpack .../16-libhttp-message-perl_6.22-1_all.deb ...
Unpacking libhttp-message-perl (6.22-1) ...
Selecting previously unselected package mecab-utils.
Preparing to unpack .../17-mecab-utils_0.996-10build1_amd64.deb ...
Unpacking mecab-utils (0.996-10build1) ...
Selecting previously unselected package mecab-ipadic.
Preparing to unpack .../18-mecab-ipadic_2.7.0-20070801+main-2.1_all.deb ...
Unpacking mecab-ipadic (2.7.0-20070801+main-2.1) ...
Selecting previously unselected package mecab-ipadic-utf8.
Preparing to unpack .../19-mecab-ipadic-utf8_2.7.0-20070801+main-2.1_all.deb ...
Unpacking mecab-ipadic-utf8 (2.7.0-20070801+main-2.1) ...
Selecting previously unselected package mysql-server.
Preparing to unpack .../20-mysql-server_8.0.20-0ubuntu0.20.04.1_all.deb ...
Unpacking mysql-server (8.0.20-0ubuntu0.20.04.1) ...
Setting up libmecab2:amd64 (0.996-10build1) ...
Setting up libhtml-tagset-perl (3.20-4) ...
Setting up liblwp-mediatypes-perl (6.04-1) ...
Setting up libencode-locale-perl (1.05-1) ...
Setting up mecab-utils (0.996-10build1) ...
Setting up libevent-core-2.1-7:amd64 (2.1.11-stable-1) ...
Setting up libio-html-perl (1.001-1) ...
Setting up mysql-server-core-8.0 (8.0.20-0ubuntu0.20.04.1) ...
Setting up libtimedate-perl (2.3200-1) ...
Setting up libfcgi-perl (0.79-1) ...
Setting up liburi-perl (1.76-2) ...
Setting up mysql-server-8.0 (8.0.20-0ubuntu0.20.04.1) ...
update-alternatives: using /etc/mysql/mysql.cnf to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Renaming removed key_buffer and myisam-recover options (if present)
/var/lib/mysql/ibdata1: 44899
ERROR: Database files are locked. Daemon already running?
Warning: Unable to start the server.

Job for mysql.service failed because the control process exited with error code.
See "systemctl status mysql.service" and "journalctl -xe" for details.
invoke-rc.d: initscript mysql, action "start" failed.
● mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
     Active: activating (auto-restart) (Result: exit-code) since Thu 2020-05-21 16:39:31 CEST; 9ms ago
    Process: 48199 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
    Process: 48224 ExecStart=/usr/sbin/mysqld (code=exited, status=1/FAILURE)
   Main PID: 48224 (code=exited, status=1/FAILURE)
     Status: "Server startup in progress"
dpkg: error processing package mysql-server-8.0 (--configure):
 installed mysql-server-8.0 package post-installation script subprocess returned error exit status 1
Setting up libhttp-date-perl (6.05-1) ...
Setting up mecab-ipadic (2.7.0-20070801+main-2.1) ...
Compiling IPA dictionary for Mecab.  This takes long time...
reading /usr/share/mecab/dic/ipadic/unk.def ... 40
emitting double-array: 100% |###########################################|
/usr/share/mecab/dic/ipadic/model.def is not found. skipped.
reading /usr/share/mecab/dic/ipadic/Suffix.csv ... 1393
reading /usr/share/mecab/dic/ipadic/Noun.proper.csv ... 27328
reading /usr/share/mecab/dic/ipadic/Noun.verbal.csv ... 12146
reading /usr/share/mecab/dic/ipadic/Noun.adverbal.csv ... 795
reading /usr/share/mecab/dic/ipadic/Noun.csv ... 60477
reading /usr/share/mecab/dic/ipadic/Others.csv ... 2
reading /usr/share/mecab/dic/ipadic/Adnominal.csv ... 135
reading /usr/share/mecab/dic/ipadic/Noun.nai.csv ... 42
reading /usr/share/mecab/dic/ipadic/Prefix.csv ... 221
reading /usr/share/mecab/dic/ipadic/Conjunction.csv ... 171
reading /usr/share/mecab/dic/ipadic/Interjection.csv ... 252
reading /usr/share/mecab/dic/ipadic/Postp.csv ... 146
reading /usr/share/mecab/dic/ipadic/Postp-col.csv ... 91
reading /usr/share/mecab/dic/ipadic/Verb.csv ... 130750
reading /usr/share/mecab/dic/ipadic/Filler.csv ... 19
reading /usr/share/mecab/dic/ipadic/Noun.name.csv ... 34202
reading /usr/share/mecab/dic/ipadic/Auxil.csv ... 199
reading /usr/share/mecab/dic/ipadic/Noun.place.csv ... 72999
reading /usr/share/mecab/dic/ipadic/Adverb.csv ... 3032
reading /usr/share/mecab/dic/ipadic/Noun.demonst.csv ... 120
reading /usr/share/mecab/dic/ipadic/Noun.others.csv ... 151
reading /usr/share/mecab/dic/ipadic/Noun.adjv.csv ... 3328
reading /usr/share/mecab/dic/ipadic/Noun.number.csv ... 42
reading /usr/share/mecab/dic/ipadic/Symbol.csv ... 208
reading /usr/share/mecab/dic/ipadic/Adj.csv ... 27210
reading /usr/share/mecab/dic/ipadic/Noun.org.csv ... 16668
emitting double-array: 100% |###########################################|
reading /usr/share/mecab/dic/ipadic/matrix.def ... 1316x1316
emitting matrix      : 100% |###########################################|

done!
update-alternatives: using /var/lib/mecab/dic/ipadic to provide /var/lib/mecab/dic/debian (mecab-dictionary) in auto mode
Setting up mecab-ipadic-utf8 (2.7.0-20070801+main-2.1) ...
Compiling IPA dictionary for Mecab.  This takes long time...
reading /usr/share/mecab/dic/ipadic/unk.def ... 40
emitting double-array: 100% |###########################################|
/usr/share/mecab/dic/ipadic/model.def is not found. skipped.
reading /usr/share/mecab/dic/ipadic/Suffix.csv ... 1393
reading /usr/share/mecab/dic/ipadic/Noun.proper.csv ... 27328
reading /usr/share/mecab/dic/ipadic/Noun.verbal.csv ... 12146
reading /usr/share/mecab/dic/ipadic/Noun.adverbal.csv ... 795
reading /usr/share/mecab/dic/ipadic/Noun.csv ... 60477
reading /usr/share/mecab/dic/ipadic/Others.csv ... 2
reading /usr/share/mecab/dic/ipadic/Adnominal.csv ... 135
reading /usr/share/mecab/dic/ipadic/Noun.nai.csv ... 42
reading /usr/share/mecab/dic/ipadic/Prefix.csv ... 221
reading /usr/share/mecab/dic/ipadic/Conjunction.csv ... 171
reading /usr/share/mecab/dic/ipadic/Interjection.csv ... 252
reading /usr/share/mecab/dic/ipadic/Postp.csv ... 146
reading /usr/share/mecab/dic/ipadic/Postp-col.csv ... 91
reading /usr/share/mecab/dic/ipadic/Verb.csv ... 130750
reading /usr/share/mecab/dic/ipadic/Filler.csv ... 19
reading /usr/share/mecab/dic/ipadic/Noun.name.csv ... 34202
reading /usr/share/mecab/dic/ipadic/Auxil.csv ... 199
reading /usr/share/mecab/dic/ipadic/Noun.place.csv ... 72999
reading /usr/share/mecab/dic/ipadic/Adverb.csv ... 3032
reading /usr/share/mecab/dic/ipadic/Noun.demonst.csv ... 120
reading /usr/share/mecab/dic/ipadic/Noun.others.csv ... 151
reading /usr/share/mecab/dic/ipadic/Noun.adjv.csv ... 3328
reading /usr/share/mecab/dic/ipadic/Noun.number.csv ... 42
reading /usr/share/mecab/dic/ipadic/Symbol.csv ... 208
reading /usr/share/mecab/dic/ipadic/Adj.csv ... 27210
reading /usr/share/mecab/dic/ipadic/Noun.org.csv ... 16668
emitting double-array: 100% |###########################################|
reading /usr/share/mecab/dic/ipadic/matrix.def ... 1316x1316
emitting matrix      : 100% |###########################################|

done!
update-alternatives: using /var/lib/mecab/dic/ipadic-utf8 to provide /var/lib/mecab/dic/debian (mecab-dictionary) in auto mode
Setting up libhtml-parser-perl (3.72-5) ...
Setting up libhttp-message-perl (6.22-1) ...
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-8.0; however:
  Package mysql-server-8.0 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                Setting up libcgi-pm-perl (4.46-1) ...
Setting up libhtml-template-perl (2.97-1) ...
Setting up libcgi-fast-perl (1:2.15-1) ...
Processing triggers for systemd (245.4-4ubuntu3) ...
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for libc-bin (2.31-0ubuntu9) ...
Errors were encountered while processing:
 mysql-server-8.0
 mysql-server
E: Sub-process /usr/bin/dpkg returned an error code (1)
W: Operation was interrupted before it could finish

A: Solution for me was in this three commands:
sudo apt-get clean
sudo apt-get update
sudo apt-get upgrade -f

A: I had this issue and after trying the above the installation was stuck at mysqld is running as PID 2802.
I killed the MySQL processes on a different terminal

pkill mysql

A: What does sudo service mysqld status have to say about this? In any case, sudo service mysqld stop might be enough to do the trick.


Q: How to perform a simple Couchbase Lite query I wanted to know how it's possible to do some simple CouchbaseLite queries.
I have a document named "test", with key-values "id": 5 and "name":"My first test".
I wanted to search following:

*

*I want to get the id (5) where name = "My first test".

*I also wanted to know if this name = "My first test" entry is already available?  I only wanted to add it if it's not there.

Database db = new Database("test_db");

using (var testDoc = new MutableDocument("test"))
{
      testDoc.SetInt("id", 5)
             .SetString("name", "My first test");

      db.Save(testDoc);
}

Thanks!

A: Assuming I understood your question right that you want to fetch documents with a specific property value only if it exists, you can do something like this
 var query = QueryBuilder.Select(SelectResult.expression(Meta.id),
                SelectResult.expression(Expression.property("id")))
    .From(DataSource.Database(db))
.Where(Expression.Property("name").NotNullOrMissing()
.And(Expression.Property("name").EqualTo(Expression.string("My first test"))))

Alternatively, if you know the Id of the document, it would be faster to do a GetDocument with the Id. Once you have the document, do a GetString on the name property. If it returns null, you can assume it does not exist.
Refer to the documentation on Couchbase Lite query fundamentals here.There are several examples. You may also want to check out API specs on NotNullOrMissing


Q: Generating Function for a polynomial If $P(n)$ is a polynomial of degree $d$ then I have to show that there is a polynomial $h_p(x)$ of degree $\leq (d-1)$ such that $$\sum_{n\geq 0} P(n)x^{n} = \frac{h_p(x)}{(1-x)^{d+1}}.$$
I have no idea where to begin. There is a hint which says use the generating function for the polynomial. Now what is a generating function for any polynomial ?
Any helpful thought on the problem will be highly appreciated.  Thank you.


Q: Lifting a function which takes implicit parameter using functor (Scalaz7) Just started learning Scalaz. Here is my code
trait Monoid[A] {
     def mappend(a1: A, a2: A): A
     def mzero: A
}

object Monoid {
    implicit val IntMonoid: Monoid[Int] = new Monoid[Int] {
        def mappend(a1: Int, a2: Int): Int = a1 + a2
        def mzero: Int = 0
    }

    implicit val StringMonoid: Monoid[String] = new Monoid[String] {
        def mappend(a1: String, a2: String): String = a1 + a2
        def mzero: String = ""
    }
}

trait MonoidOp[A] {
    val F: Monoid[A]
    val value: A
    def |+|(a2: A): A = F.mappend(value, a2)
}

object MonoidOp{
    implicit def toMonoidOp[A: Monoid](a: A): MonoidOp[A] = new MonoidOp[A]{
        val F = implicitly[Monoid[A]]
        val value = a
    }
}

I have defined a function (just for the sake of it)
def addXY[A: Monoid](x: A, y: A): A = x |+| y

I want to lift it so that it could be used using Containers like Option, List, etc. But when I do this
def addXYOptioned = Functor[Option].lift(addXY)

It says error: could not find implicit value for evidence parameter of type scalaz.Monoid[A]
       def addOptioned = Functor[Option].lift(addXY)
How to lift such functions?

A: Your method addXY needs a Monoid[A] but there is no Monoid[A] in scope when used in addXYOptioned, so you also need to add the Monoid constraint to addXYOptioned.
The next problem is that Functor.lift only lifts a function A => B, but we can use Apply.lift2 to lift a function (A, B) => C.
Using the Monoid from Scalaz itself :
import scalaz._, Scalaz._

def addXY[A: Monoid](x: A, y: A): A = x |+| y

def addXYOptioned[A: Monoid] = Apply[Option].lift2(addXY[A] _)

We could generalize addXYOptioned to make it possible to lift addXY into any type constructor with an Apply instance :
def addXYApply[F[_]: Apply, A: Monoid] = Apply[F].lift2(addXY[A] _)

addXYApply[List, Int].apply(List(1,2), List(3,4))
// List[Int] = List(4, 5, 5, 6)

addXYApply[Option, Int].apply(1.some, 2.some)
// Option[Int] = Some(3)


Q: MS Chart Control Scale - Line graph show 12 months On my X Axis, I have months. The chart shows up to 11 points, i.e. Jan - Nov of the same year, but when I add 12 points (Jan - Dec), it will do an auto label thing and change the interval for every 4 months.
How can I change the graph so that it shows 12 months before it does the auto labels?
Here is the server control code I am currently using.
<asp:CHART ID="Chart1" runat="server"
    BorderColor="181, 64, 1" BorderDashStyle="Solid" BorderWidth="2" Height="296px"
    ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)" ImageType="Png"
    Palette="None" Width="700px"
    BorderlineColor="">
        <legends>
            <asp:Legend BackColor="Transparent"
                                    Font="Trebuchet MS, 8pt, style=Bold"
                IsTextAutoFit="False" Name="Default" Alignment="Center"
                DockedToChartArea="ChartArea1" Docking="Top" IsDockedInsideChartArea="False"
                Title="Legend">
            </asp:Legend>
        </legends>
        <series>
            <asp:Series BorderColor="180, 26, 59, 105" BorderWidth="2" ChartType="Line"
                                    Color="220, 65, 140, 240" MarkerSize="6"
                Name="Series1" ShadowColor="Black"
                                    ShadowOffset="2" XValueType="DateTime" YValueType="Double"
                                    LabelFormat="c0" LegendText="Actual"
                MarkerStyle="Circle">
            </asp:Series>
            <asp:Series BorderColor="180, 26, 59, 105" BorderWidth="2" ChartType="Line"
                                    Color="220, 224, 64, 10" MarkerSize="6" Name="Series2" ShadowColor="Black"
                                    ShadowOffset="2" XValueType="DateTime" YValueType="Double"
                                    LabelFormat="c0" LegendText="Projected"
                MarkerStyle="Circle">
            </asp:Series>
            <asp:Series BorderColor="180, 26, 59, 105" BorderWidth="2"
                ChartArea="ChartArea1" ChartType="Line"
                                    Legend="Default" Name="Series3" LabelFormat="c0" XValueType="DateTime"
                                    YValueType="Double" Color="0, 192, 192" MarkerSize="6"
                ShadowColor="Black" ShadowOffset="2" LegendText="Actual Credit Limit"
                MarkerStyle="Circle">
            </asp:Series>
        </series>
        <chartareas>
            <asp:ChartArea BackColor="#DEEDF7" BackGradientStyle="TopBottom"
                                    BackSecondaryColor="White" BorderColor="64, 64, 64, 64" BorderDashStyle="Solid"
                                    Name="ChartArea1" ShadowColor="Transparent">
                <area3dstyle inclination="40" isclustered="False" isrightangleaxes="False"
                                        lightstyle="Realistic" perspective="9" rotation="25" wallwidth="3" />
                <axisy linecolor="64, 64, 64, 64" islabelautofit="False"
                                        isstartedfromzero="False">
                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" Format="c0" />
                    <majorgrid linecolor="64, 64, 64, 64" />
                </axisy>
                <axisx linecolor="64, 64, 64, 64" intervaloffsettype="Months"
                                        intervaltype="Months" islabelautofit="False" isstartedfromzero="False">
                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" Angle="-60"
                                            Format="MMM yy" />
                    <majorgrid linecolor="64, 64, 64, 64" />
                </axisx>
            </asp:ChartArea>
        </chartareas>
    </asp:CHART>

Thanks.

A: Try to change the Chart's Width to a higher value...
<asp:Chart ID="Chart1" runat="server"
BorderColor="181, 64, 1" BorderDashStyle="Solid" BorderWidth="2" Height="296px"
ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)" ImageType="Png"
Palette="None" Width="800px"
BorderlineColor="">

Try to set the inverval property to 1 on axisx:
 <axisx Interval="1" linecolor="64, 64, 64, 64" intervaloffsettype="Months"
  intervaltype="Months" islabelautofit="False" isstartedfromzero="False">

To fully understand how to format chart axis, take a look at:
Formatting Axis Labels on a Chart

(source: microsoft.com)
How the Chart Calculates Axis Label Intervals?
On the category axis, the minimum and maximum value types are determined depending on the type of your category field. Any field in a dataset can be categorized into one of three category field types: Numeric, Date/Time and Strings.
Displaying All Labels on the Category Axis
On the value axis, axis intervals provide a consistent measure of the data points on the chart. However, on the category axis, this functionality can cause categories to appear without axis labels. Typically, you want all categories to be labeled. You can set the number of intervals to 1 to show all categories. For more information, see How to: Specify an Axis Interval.

A: Use Microsoft chart
chart.ChartAreas[0].AxisY.ScaleBreakStyle = true

to chart the second set of values in thier on Y Axis with thier own Y values


Q: How do you mount a VueJS UMD build onto existing HTML? I've been attempting to take a couple of small components from our main app to use on a landing page, but haven't had much luck!
I have some existing HTML in the DOM, let's say:

Demo Feature #1

 <demo-component />

I have the following entry file, marketing.ts:
import Vue from "vue";
import Demo from "Demo.vue";

new Vue({
 el: 'app',
  components: {
    'demo-component': Demo,
  }
});

When the output build runs on the site, the DOM ends up looking like this:

I expected the custom HTML tag to be replaced with my Vue component.
The docs state this should be the case:

If neither render function nor template option is present, the in-DOM HTML of the mounting DOM element will be extracted as the template. In this case, Runtime + Compiler build of Vue should be used.

Furthermore, the docs go on to state:

When using vue-loader or vueify, templates inside *.vue files are pre-compiled into JavaScript at build time. You don’t really need the compiler in the final bundle, and can therefore use the runtime-only build.

In this case, I am using the VueCLI (with Vue Loader) to build my output, which from the above I understand to be a runtime-only build.
The component works fine in the full application. The glaring thing I can see is a lack of render. When I use that, it replaces the DOM with the whole component supplied and loses what was already inside.
Is it possible to extract multiple components via a lib build and render them in an existing DOM?

Further details:

*

*Using the build command vue-cli-service build --target lib --inline-vue --dest dist/lib/marketing --name marketing src/marketing.ts  --no-clean

*Using VueCLI 4.2.2

*Using TypeScript and Vue Class components

*This CodePen show's it's possible to do

A: The way I've done it is by...
1) wrapping my component in a js file
import MyWidgit from './MyWidgit.vue';

// eslint-disable-next-line import/prefer-default-export
export const mount = (el, props) =>
  new window.Vue({
    el,
    render: h => h(Filter, {props})
  });

2) using rollup to generate the code (I think it's a better fit for generating libraries)
{
    input: `./src/${widgetName}/${widgetName}.js`, // Path relative to package.json
    output: {
      format: 'umd',
      name: widgetName,
      file: `./dist/${widgetName}.js`,
      exports: 'named',
      external: ['vue'], // requires vuejs lib to be loaded separately
      globals: {
        vue: 'Vue',
      },
    },
    //... etc
}

3) add to html

A: To solve this issue, I removed the --inline-vue argument from the CLI build and added Vue.JS via the CDN, ie.

I believe this should work from a single lib, so this is potentially an issue with the build tool.


Q: Getting error while installing mongodb on Mac Warning: No available formula with the name "mongosh" (dependency of mongodb/brew/mongodb-community). Did you mean mongocli?
==> Searching for similarly named formulae...
This similarly named formula was found:
mongodb/brew/mongocli ✔
To install it, run:
brew install mongodb/brew/mongocli ✔
It was migrated from mongodb/brew to homebrew/core.
Trying to install mongoDB from Official website and encountered this error.


Q: Button onClickListener on AlertBuilder not working I have an activity and a layout to call in AlertBuilder,
I have 3 buttons in layout and some code for each one.
The problem is that when I create and show alert, onClickListener not working
I don't want use alert buttons and have to use my buttons on layout
MainActivity Code (Call Alert)
LayoutInflater inflater = (MainActivity.this).getLayoutInflater();
builder.setTitle("Login Form");

builder.setCancelable(false);
builder.setView(inflater.inflate(R.layout.activity_login_prompt, null));
builder.create();
builder.show();

LoginPromptActivity
public class LoginPromptActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_prompt);
    Button bLogin = (Button)findViewById(R.id.btnLogin);
    bLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(LoginPromptActivity.this, "Button Clicked",  Toast.LENGTH_SHORT).show();
        }

    });
}
}

Layout XML Code
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".LoginPromptActivity"
tools:showIn="@layout/activity_login_prompt">

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="192dp"
    android:layout_height="147dp"
    android:layout_marginStart="32dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="32dp"
    android:layout_marginRight="32dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/login" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:layout_marginEnd="32dp"
    android:layout_marginRight="32dp"
    android:text="Username"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView2" />

<EditText
    android:id="@+id/txtUserName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="17dp"
    android:layout_marginEnd="32dp"
    android:layout_marginRight="32dp"
    android:ems="10"
    android:inputType="textPersonName"
    app:layout_constraintEnd_toStartOf="@+id/textView4"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView2" />

<TextView
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:layout_marginEnd="32dp"
    android:layout_marginRight="32dp"
    android:text="Password"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView4" />

<EditText
    android:id="@+id/txtPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:ems="10"
    android:inputType="textPassword"
    app:layout_constraintEnd_toStartOf="@+id/textView5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtUserName" />

<Button
    android:id="@+id/btnLogin"
    android:layout_width="127dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:text="Login"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtPassword" />

<Button
    android:id="@+id/btnRegister"
    android:layout_width="94dp"
    android:layout_height="46dp"
    android:layout_marginTop="32dp"
    android:text="Register"
    app:layout_constraintEnd_toStartOf="@+id/btnLogin"
    app:layout_constraintTop_toBottomOf="@+id/txtPassword" />

<Button
    android:id="@+id/btnCancel"
    android:layout_width="126dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="32dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:text="Exit App"
    app:layout_constraintEnd_toStartOf="@+id/btnRegister"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtPassword" />

</android.support.constraint.ConstraintLayout>

A: I have read your question and I think you have face some problem to implement onclick listener
on alert dialog buttons. if we have use any custom layout for alert dialog so do not need any activity  to handle this layout. According to your code sinppet you have create a alert dialog using custom layout and use a activity to handle this layout button click
Try this this code create custom alert dialog , and handle its click listener
  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle("Login Form");
    View view= getLayoutInflater().inflate(R.layout.dialog_custom, null);
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setView(view);

    alertDialogBuilder.create();
     //alert dialog button
    TextView ok_btn=view.findViewById(R.id.ok_btn);
    //buttton click
   ok_btn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            Toast
               .makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT)
               .show();
        }
    });
    alertDialogBuilder.show();

A:  private void showAlertDialog(){
@SuppressLint("InflateParams") final View promptView = LayoutInflater.from(mainActivity).inflate(R.layout.enter_pin_dialog, null);

 Button accept= (Button) promptView.findViewById(R.id.accept_btn);
    Button deny= (Button) promptView.findViewById(R.id.deny_btn);

 deny.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           // do what you want
        }
    });

accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           // do what you want
        }
    });

 NotificationUtil.messageDialog(
            mainActivity,
            null,
            null,
            null,
            false,
            true,
            promptView,
            null,
            null,
            null,
            null,
            null,
            null
    );}

public class NotificationUtil {

private static ProgressDialog progressDialog;
private static AlertDialog cancelDialog;
private static AlertDialog messageDialog;
private static Vector<AlertDialog> dialogs= new Vector<AlertDialog>();

public static void messageDialog(Context context, String title, String message, Integer iconResId,
                                 boolean cancelable, boolean openKeyboard, View view,
                                 String positiveStr, DialogInterface.OnClickListener positiveListener,
                                 String negativeStr, DialogInterface.OnClickListener negativeListener,
                                 DialogInterface.OnShowListener showListener, DialogInterface.OnDismissListener dismissListener) {

    AlertDialog.Builder builder = new AlertDialog.Builder(context);

    builder.setTitle(title);
    builder.setMessage(message);
    builder.setCancelable(cancelable);

    if (iconResId != null) {
        builder.setIcon(iconResId);
    }

    if (view != null) {
        builder.setView(view);
    }

    if (positiveStr != null) {
        builder.setPositiveButton(positiveStr, positiveListener);
    }

    if (negativeStr != null) {
        builder.setNegativeButton(negativeStr, negativeListener);
    }

    messageDialog = builder.create();
    dialogs.add(messageDialog);

    if (openKeyboard) {
        Window window = messageDialog.getWindow();
        if (window != null) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }
    }

    if (showListener != null) {
        messageDialog.setOnShowListener(showListener);
    }

    if (dismissListener != null) {
        messageDialog.setOnDismissListener(dismissListener);
    }

    messageDialog.show();

    ScrollView buttonsContainer = (ScrollView) messageDialog.findViewById(R.id.buttonPanel);
    if (buttonsContainer != null) {
        List<View> views = new ArrayList<>();
        for (int i = 0; i < buttonsContainer.getChildCount(); i++) {
            views.add(buttonsContainer.getChildAt(i));
        }
        buttonsContainer.removeAllViews();
        for (int i = views.size() - 1; i >= 0; i--) {
            buttonsContainer.addView(views.get(i));
        }
    }
}}

A: try this
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
            alertbox.setMessage("ddddd");
            alertbox.setTitle("dddd");
            alertbox.setIcon(R.drawable.ic_del);

            alertbox.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface arg0,
                                            int arg1) {

                            }
                        }
                    });
            alertbox.setNegativeButton("No",new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0,
                                    int arg1) {

                }
            });
            alertbox.show();

A: Open your MainActivity.java and add OnClickListener to your button to create an alert dialog :
  btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Create a Custom Alert Dialog
            final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.list_layout,null);
            TextView tv = (TextView)view.findViewById(R.id.head);
            ImageView iv = (ImageView)view.findViewById(R.id.iv);
            builder.setView(view);
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Dismiss the dialog here
                    dialog.dismiss();
                }
            });
            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Add ok operation here
                }
            });

            builder.show();

        }
    });

You can also add custom buttons to your alert dialog.


Q: Can we name the 6 degrees of freedom of a 2d affine transform in an intuitive manner? A 2d affine transformation is characterized by the following formula:
$$
   x' = a x + b y + c,  \\
   y' = d x + e y + f.
$$
Hence it has 6 degrees of freedom.  I can name the following 5 special types:

*

*translate parallel to the $x$-axis

*translate parallel to the $y$-axis

*rotate inside $xy$-plane about the origin $O$

*scale in the direction of $x$-axis

*scale in the direction of $y$-axis

The above types are basic, intuitive (has clear geometric meaning) and 'independent'. What is the other basic and independent type? I can think of 2 other basic types:

*

*shear parallel to the $x$-axis

*shear parallel to the $y$-axis

The problem is we need one more, not two more! Can we find ONE extra intuitive type that are independent of the above 5 types?
NOTE: Edited after reading EricTowers' answer.
A x-translate and a 90 degrees rotation will generate a y-translate.
A x-scale and a 90 degrees rotation will generate a y-scale.
A x-shear and a 90 degrees rotation will generate a y-shear.
It is common to think of the two translates, two scaling and 1 rotation in describing affines. Each of the above operation requires 1 continuous parameter.
So if we combine them in 6 different orders (repetition of same type allowed); we will obtain all possible affines.
I don't want to include another two shears, partly because I want one only and don't want to be forced to single out the x-shear or y-shear. A total of 7 affines to describe affines when we should only need 6 ways to describe. I am curious if it is possible to do it with exactly 6 different types.
On the other hand, we can go minimum and just do the following 3 and obtain all affines (repetition of same type allowed):
x-translation, x-scale and rotation


Q: Concatenating user input? I want to concatenate user input with a ':' colon in-between.
My script is taking options through user input and I want to store it like:
Red:yellow:blue
I have created a loop to read user input, but not sure how to store it.
while True:
    color = input("please enter Color of your choice(To exit press No): ")
    if color == 'No':
        break
    color += color
print ("colors   ", color)

A: One simple approach to keep as close to your code as possible is to start off with an empty list called colors before entering your loop, and appending to that all the valid colors as you take inputs. Then, when you are done, you simply use the join method to take that list and make a string with the ':' separators.
colors = []
while True:
     color = input("please enter Color of your choice(To exit press No): ")
     if color == 'No':
       break
     else:
         colors.append(color)

colors = ':'.join(colors)
print ("colors   ", colors)

Demo:
please enter Color of your choice(To exit press No): red
please enter Color of your choice(To exit press No): blue
please enter Color of your choice(To exit press No): green
please enter Color of your choice(To exit press No): orange
please enter Color of your choice(To exit press No): No
colors    red:blue:green:orange

A: You can concatenate a ':' after every input color
while True:
     color = input("please enter Color of your choice(To exit press No): ")
     if color == 'No':
       break
     color += color
     color += ':'
print ("colors   ", color)

A: you're looking for str.join(), to be used like so: ":".join(colors). Read more at https://docs.python.org/2/library/stdtypes.html#str.join

A: Using a list is neat:
colors = []
while True:
    color = input("please enter Color of your choice(To exit press No): ")
    if color in ('No'):
        break
    colors.append(color)
print("colors   ", ':'.join(colors))


Q: Prove that $CE=AB$
Suppose $ABC$ is an acute-angled triangle with $AB<AC$.Let $M$ be the midpoint of $BC$. Suppose $P$ is a point on side $AB$ such that, if $PC$ intersects the median $AM$ at E, then $AP=PE$.Prove that $AB=CE$.

I don't know how to start. Please give me an idea. Getting no fruitful thoughts ,I started using barycentric Coordinates.But the calculations seemed very tough and I failed to proceed. Please give me any idea to start

A: Hint:   write Menelaus' theorem for triangle $\,\triangle PBC\,$ and transversal $\,AM\,$.

A: Construct the //gm BECF.

From (1) AEM is a straight line; (2) E is a vertex of that //gm; (3) M is the midpoint of one of its diagonals; and (4) F is a vertex of that //gm and FM is a straight line, we can say that AEMF is a straight line.
The required result follows because all the green marked angles are equal.


Q: How to Redirect/Forward data from Spring MVC Controller to other page as POST? I'm working on a project which is a mix Spring MVC and coldfusion, I want to know how to redirect from the SpringMVC Controller to the cfm using a POST request.
I have this mapping defined
   @RequestMapping(value = "/preprocess", method = {RequestMethod.GET})
   public ModelAndView doPreprocess(HttpServletRequest request, @RequestParam Map<String, String> params, HttpSession session) {
        //retrieve some parameters from db and redirect/forward here to "/postprocess.cfm"
   }

After retrieve some parameters, I need to redirect/forward those parameter to other endpoint "/postprocess.cfm", this page reads the params from a form, so the request to this page needs to be a POST
Looking forward to your help. Thanks a lot!


Q: Combine IsNumeric and Right()
Trying to return field [doc] that have no letters.  Results are all over the place.
SELECT Right([doc],4) AS ex1, IsNumeric([ex1]) AS ex2
FROM stat_converted;

The query returns two fields as it should but not evaluating correctly.  Results with all numbers and others that are all letters are coming back as True(-1).
I also tried building a temp table and then applying IsNumeric to that with same results.
I also built a small test DB and the logic works so I am really confused.

A: IsNumeric will match things like "2E+1" (2 times ten to the power of 1, i.e. 20) as that is a number in scientific format. "0D88" is also a number according to IsNumeric because it is the double-precision (hence the "D") version of "0E88".
You could use LIKE '####' to match exactly four digits (0-9).
If you had more complex match requirements, say a variable quantity of digits, you would be interested in Expressing basic Access query criteria as regular expressions.


Q: how to get the contents in brackets in a file Python I am working with files right now and i want to get text from a bracket this is what i mean by getting text from a brackets...
{
this is text for a
this is text for a
this is text for a
this is text for a
}

[
this is text for b
this is text for b
this is text for b
this is text for b
]

The content in a is this is text for a and the content for b is is text for b
my code seems to not be printing the contents in a properly it show a&b my file.
My code:
with open('file.txt','r') as read_obj:
  for line in read_obj.readlines():
    var = line[line.find("{")+1:line.rfind("}")]
    print(var)

A: *

*iterate over the file

*for each line check the first character

*

*if the first character is either '[' or '{' start accumulating lines

*if the first character is either ']' or '}' stop accumulating lines

a_s = []
b_s = []
capture = False
group = None
with open(path) as f:
    for line in f:
        if capture: group.append(line)
        if line[0] in '{[':
            capture = True
            group = a_s if line[0] == '{' else b_s
        elif line[0] in '}]':
            capture = False
            group = None

print(a_s)
print(b_s)

Relies on the file to be structured exactly as shown in the example.

A: This is what regular expressions are made for. Python has a built-in module named re to perform regular expression queries.
In your case, simply:
import re

fname = "foo.txt"

# Read data into a single string
with open(fname, "r") as f:
    data = f.read()

# Remove newline characters from the string
data = re.sub(r"\n", "", data)

# Define pattern for type A
pattern_a = r"\{(.*?)\}"

# Print text of type A
print(re.findall(pattern_a, data))

# Define pattern for type B
pattern_b = r"\[(.*?)\]"

# Print text of type B
print(re.findall(pattern_b, data))

Output:
['this is text for athis is text for athis is text for athis is text for a']
['this is text for bthis is text for bthis is text for bthis is text for b']

A: Read the file and split the content to a list.
Define a brackets list and exclude them through a loop and write the rest to a file.
file_obj = open("content.txt", 'r')
content_list = file_obj.read().splitlines()
brackets = ['[', ']', '{', '}']
for i in content_list:
    if i not in brackets:
        writer = open("new_content.txt", 'a')
        writer.write(i+ '\n')
    writer.close()

A: f1=open('D:\\Tests 1\\t1.txt','r')
for line in f1.readlines():
    flag=0
    if line.find('{\n') or line.find('[\n'):
        flag=1
    elif line.find('}\n') or line.find(']\n'):
        flag=0
    if flag==1:
        print(line.split('\n')[0])


Q: Returning value from query based on results I have this query I'm trying to build to display specific information for a stored table. I'm needing the query to also display the Enemy Guild Name but I'm having trouble getting the query to take the Enemy Guild ID and link it to the name.
SELECT g.wPos as wPos, g.szGuildName as szGuildName, g.dwGuildExpWeek as dwGuildExpWeek, g.dwEnemyGuildID as dwEnemyGuildID, gm.wPower as wPower, gd.szName as szName
FROM guild as g
LEFT JOIN guild_member AS gm ON gm.dwGuildID = g.dwGuildID AND gm.wPower = '1'
LEFT JOIN gamedata AS gd ON gd.dwID = gm.dwRoleID
WHERE g.wPos = '1'

The output of the query right now results in the following:
Query Results Currently
What I need it to do now is take the dwEnemyGuildID it finds and then use that ID to search for the szGuildName while also displaying the other data it finds.

A: Use the concept of SELF JOIN, in which we will join same table again if we have a field which is a reference to the same table. Here dwEnemyGuildID is reference to the same table.
A trivial example of the same is finding Manager for an employee from employees table.
Reference: Find the employee id, name along with their manager_id and name
SELECT
    g.wPos as wPos,
    g.szGuildName as szGuildName,
    g.dwGuildExpWeek as dwGuildExpWeek,
    g.dwEnemyGuildID as dwEnemyGuildID,
    enemy_g.szGuildName as szEnemyGuildName,  -- pick name from self joined table
    gm.wPower as wPower,
    gd.szName as szName
FROM guild as g
LEFT JOIN guild_member AS gm ON gm.dwGuildID = g.dwGuildID AND gm.wPower = '1'
LEFT JOIN guild AS enemy_g ON g.dwEnemyGuildID = enemy_g.dwGuildID   -- Use self join
LEFT JOIN gamedata AS gd ON gd.dwID = gm.dwRoleID
WHERE g.wPos = '1';


Q: Auto check textfield length and Hit a method UITextfield Hello I need to enter mobile number with validation that mobile textfield range should be 10.
And when textfield value ==10, i need to call a function when mobile textfield.text length becomes 10.
My below code work fine but i need to press 1 more character (means 11) to call it.
Please how i resolve it.
#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField==user_mobile_txtField)
   {

        if (textField.text.length >= MAX_LENGTH && range.length == 0)
        {

            if (textField.text.length==MAX_LENGTH)
            {

                NSLog(@“Want to call Call method HERE ");

            }

            return NO; // return NO to not change text
        }

    }
     return YES;
}

A: shouldChangeCharactersInRange is called just before actual text has changed. If you want to perform an action after actual text has changed, you can try the approach below:
...
//start observing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChanged:) name:UITextFieldTextDidChangeNotification object:{your UITextField}];
...

- (void)textHasChanged:(NSNotification *)notification {
    UITextField *textField = [notification object];
    //check if textField.text.length >= 10
    //do stuff...
}

A: You can get what the string will be after the characters are changed with the method stringByReplacingCharactersInRange:withString:
#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == user_mobile_txtField) {
        NSString *fullString = [textField.text stringByReplacingCharactersInRange:range withString:string];

        if (fullString.length >= MAX_LENGTH && range.length == 0) {
            if (fullString.length == MAX_LENGTH) {
                NSLog(@“Want to call Call method HERE ");
            }
            return NO; // return NO to not change text
        }
    }
    return YES;
}

A: Please try with below code -
#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField==user_mobile_txtField)
   {

        if (textField.text.length >= MAX_LENGTH )
        {

            if (textField.text.length==MAX_LENGTH)
            {

                NSLog(@“Want to call Call method HERE ");

            }

            return NO; // return NO to not change text
        }

    }
     return YES;
}


Q: Maximise population coverage subject to budget constraint

Let $t_i =$
$1$ if transmitter i is to be constructed
and $0$ otherwise,
$c_j =$
$1$ if community j is covered
and $0$ otherwise.
Obj func:
Max
$$z = [10, 15, ..., 10] \cdot c$$
s.t.

*

*the budget constraint
$$[3.6, 2.3, ..., 3.10] \cdot t \le 15$$

*If community $j$ is covered, it is done so by at least one constructed transmitter $i$:
eg if $c_1$ is covered, then $t_1$ or $t_3$ is constructed:
$$c_1 \to (t_1 \bigvee t_3)$$
$$\iff \neg c_1 \bigvee (t_1 \bigvee t_3)$$
$$\iff 1 - c_1 + t_1 + t_3 \ge 1$$
$$\iff c_1 \le t_1 + t_3$$
Similarly, we have:
$$c_2 \le t_1 + t_2$$
$$\vdots$$
$$c_{15} \le t_7$$

*If a transmitter $i$ is constructed, at least one community $j$ is covered:
eg if $t_1$ is constructed, then $c_1$ and $c_2$ are covered:
$$t_1 \to (c_1 \bigwedge c_2)$$
$$\iff \neg t_1 \bigvee (c_1 \bigwedge c_2)$$
$$\iff (\neg t_1 \bigvee c_1) \bigwedge (\neg t_1 \bigvee c_2)$$
$$\iff 1 - t_1 + c_1 \ge 1 \ \text{and} \ 1 - t_1 + c_2 \ge 1$$
$$\iff c_1 \ge t_1 \ \text{and} \ c_2 \ge t_1$$
Similarly, we have:
$$c_2, c_3, c_5 \ge t_2$$
$$c_1, c_7, c_9, c_{10} \ge t_3$$
$$\vdots$$
$$c_{12}, c_{13}, c_{14}, c_{15} \ge t_7$$

Is that right?

From Chapter 3 here.

A: Here is a way to get the constraints right.  Define $x_i$ exactly as you have done.  Define $p_i$ to be an indicator $1/0$ depending on whether community $i$ has been covered or not.
The budget constraint remains as you have set, and the objective function is now of form $\max z = 10p_1+15p_2 + \cdots + 10p_{15}$
Now how do we ensure that $p_i$ is set correctly, for any given choice of $\{x_i\}$?  One way is to note that the objective function gives positive weight to $p_i$, so define a constraint for each population based on transmitters which could cover it - e.g. for the first one : $p_1 \le x_1+x_3$, for the second $p_2 \le x_1 + x_2$ etc.  This will force the population indicator to turn $0$ if none of the relevant transmitters are selected.

A: This is a classical set covering problem.
Let $y_i$ be a binary variable that equals $1$ if and only if transmitter $i=1,\cdots,7$ is built, and $x_j$ another binary that equals $1$ if community $j$ is covered. Let $p_j$ be the population of community $j=1,\cdots,15$.
You want to maximize the total coverage:
$$
\mbox{Maximize }Z=\sum_{j=1 }^{15}p_jx_j
$$
subject to budget constraints:
$$
\sum_{i=1}^7c_iy_i\le 15 \\
$$
To link the variables, proceed like Macavity suggests:
$$
x_j\le \sum_{i\;|\;i \;covers\; j}y_i\quad \forall j=1,\cdots,15\\
y_i,x_j\in \{0,1\}\quad \forall i=1,\cdots,7\;\forall j=1,\cdots,15
$$


Q: Java/Jsp XML Dom looks like I need help again! :-/
Im trying to read this XML file with Java/Jsp:
<?xml version="1.0" encoding="iso-8859-1"  ?>
<universal_campaign>
    <campaign_details>
        <campaign_id></campaign_id>
        <campaign_title>Test Campaign</campaign_title>
        <campaign_sdate>2010-01-21</campaign_sdate>
        <campaign_edate>2010-01-25</campaign_edate>
        <campaign_priority>Normal</campaign_priority>
    </campaign_details>

    <campaign_schedule>
        <schedule_sdate>2010-01-25</schedule_sdate>
        <schedule_edate>2010-01-30</schedule_edate>
        <schedule_priority>Normal</schedule_priority>

        <schedule_content>
            <content_name>Wallpaper_A</content_name>
            <content_filename>WP_A.jpg</content_filename>
        </schedule_content>

        <schedule_content>
            <content_name>Screensaver</content_name>
            <content_filename>SCS.gif</content_filename>
        </schedule_content>

        <schedule_zone>universal.001 test 001</schedule_zone>
        <schedule_zone>universal.001 test 002</schedule_zone>
        <schedule_zone>universal.001 test 003</schedule_zone>
    </campaign_schedule>

</universal_campaign>

Here is my Java/Jsp code:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(fileName);
NodeList nl, nl2;
NodeList campaign_details = doc.getElementsByTagName("universal_campaign");
String res = "";

for(int i = 0;i<campaign_details.getLength();i++){

  nl = campaign_details.item(i).getChildNodes();

  for(int j = 0; j<nl.getLength();j++){
    nl2 = nl.item(j).getChildNodes();

      for(int k = 0; k<nl2.getLength();k++){
        res += nl2.item(k).getNodeName()+": "+nl2.item(k).getNodeValue()+"<br />";
      }
   }

}

But when I output the String res, I get:
#text:
campaign_id: null
#text:
campaign_title: null
#text:
campaign_sdate: null
#text:
campaign_edate: null
#text:
campaign_priority: null
#text:
#text:
schedule_sdate: null
#text:
schedule_edate: null
#text:
schedule_priority: null
#text:
schedule_content: null
#text:
schedule_content: null
#text:
schedule_zone: null
#text:
schedule_zone: null
#text:
schedule_zone: null
#text:

And I don't get it... how can the getNodeName() return the name of the node, but the getNodeValue() returns null....?
Please help me, I have done many search and failed attempts before posting here, but nothing worked.... :-/

A: Use getTextContent() or, even better, use a better XML API (jdom springs to mind).

A: The fact is that the node you're getting is not the text node itself. It's an Element and getNodeValue will return null (see table here). You'll have to use getTextContent instead.