text:
Q: Stroustrup chapter 4 exercise 6: Improve efficiency The exercise asks for a code which can convert the user input of the numbers 0-9 either as an integer or string to a string or integer respectively i.e. if0 is entered "zero" will be outputted and vice versa.
string number;

cout << "Let's convert strings to numbers."
     << "Enter value/string of 0-9";

while (number!= "exit")
{
    cin >> number;

    for (int i=0; i < digits.size(); i++)
    {
        if (number == digits[i]) cout << i << endl;
    }

    if (number == "0")      cout << digits[0] << endl;
    else if (number == "1") cout << digits[1] << endl;
    else if (number == "2") cout << digits[2] << endl;
    else if (number == "3") cout << digits[3] << endl;
    else if (number == "4") cout << digits[4] << endl;
    else if (number == "5") cout << digits[5] << endl;
    else if (number == "6") cout << digits[6] << endl;
    else if (number == "7") cout << digits[7] << endl;
    else if (number == "8") cout << digits[8] << endl;
    else if (number == "9") cout << digits[9] << endl;
}

digits is a vector class which stores the strings "zero", "one" etc.
This code works fine but I don't like the long chain of if/else if statements but I can't figure out a way to convert the integers to strings. Can someone help me make this more efficient? Thanks!

A: you can use that if number == "0" then number[0] == '0' which is char.
e.i instead if/else statements:
if (number[0] >= '0' && number[0] <= '9' )
  std::cout << digits[number[0] - '0'] << std::endl;
else
  std::cout << "wrong input - needs to be digit" << std::endl;

string is basically an array of characters, std::string is an array of characters of type char.
For instance these are two legimate ways to declare and initialize strings in c or c++
char s[3] = { '0', '1', '\0' };
char s[3] = "01";

Char value is technically integer (or rather byte) that stores the character code in some encoding (usually ASCII).
For instance the character code of '0' is 48, that of '1' is 49, '2' is 50. And we use this, because we know that
'3' - '0' = 51 - 48 = 3

A: You could do digits[number[0] - 48] to get rid of the if/else if.

A: Just use isdigit to check if it's 0-9 http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
And if it is a digit you could convert it to an int using aoti http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
and finally just say
cout << digits[aoti(number)];


text:
Q: how to read from the InputStream of a bluetooth on Android I am trying to test this bluetooth communication example between a PC and an Android phone. My SPP client is exactly the one from there and it works fine. I am new to Android and I didn't want to make it run in a separate thread because I don't know how, so I just did everything in the onCreate() method. If this is not the best way, feel free to point me to a better way, but this is not my main problem.
The problem is I wanted to display the text received via bluetooth on a textView and I don't know how to read from InputStream. When the code is left like that, it displays something like java.io.DataInputStream@41b0cb68
I tried it like here it didn't display anything, also I don't know what encoding is being used.
here's my android app's code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.*;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

//based on java.util.UUID
private static UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");

// The local server socket
private BluetoothServerSocket mmServerSocket;

// based on android.bluetooth.BluetoothAdapter
private BluetoothAdapter mAdapter;
private BluetoothDevice remoteDevice;
TextView text;

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

    text = (TextView) findViewById(R.id.textView_Text);

    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();

    // Listen to the server socket if we're not connected
   // while (true) {

        try {
            // Create a new listening server socket
            Log.d((String) this.getTitle(), ".....Initializing RFCOMM SERVER....");

            // MY_UUID is the UUID you want to use for communication
            mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("MyService",    MY_UUID);
            //mmServerSocket =  mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID); // you can also try  using In Secure connection...

            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket = mmServerSocket.accept();

        } catch (Exception e) {

        }

        try {
            Log.d((String) this.getTitle(), "Closing Server Socket.....");
            mmServerSocket.close();

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams

            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();

            DataInputStream mmInStream = new DataInputStream(tmpIn);
            DataOutputStream mmOutStream = new DataOutputStream(tmpOut);

            // here you can use the Input Stream to take the string from the client  whoever is connecting
            //similarly use the output stream to send the data to the client

            text.setText(mmInStream.toString());
        } catch (Exception e) {
            //catch your exception here
        }
   // }
}
}

I commented out the while(true) loop because I think it was making my app crash when onPause() was being called. I know this is not the best implementation but I really want to read from the bluetooth I feel like I am very close :), other aspects will be dealt with afterwards (like working with threads and so on).

A: I finally managed to correctly display in a TextView the string sent from the PC ("Test String from SPP Client\r\n").
I used this question, namely this piece of code, just below DataOutputStream mmOutStream = new DataOutputStream(tmpOut);:
// Read from the InputStream
            bytes = mmInStream.read(buffer);
            String readMessage = new String(buffer, 0, bytes);
            // Send the obtained bytes to the UI Activity

This is a very rudimentary example, designed only to show how to display strings received via bluetooth on the screen of the device. It is not done in a separate thread, and after it receives the string you have to close the app and restart it again, but the main purpose of the app was achieved (as I stated when I asked this question). What I really, really wanted was to receive a string from PC and display it on screen.
Here's my complete MainActivity, if somebody wants me to post a more complete approach (like using a separate thread) I will post it here once I complete it.
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.*;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

//based on java.util.UUID
private static UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");

// The local server socket
private BluetoothServerSocket mmServerSocket;

// based on android.bluetooth.BluetoothAdapter
private BluetoothAdapter mAdapter;
private BluetoothDevice remoteDevice;
TextView text;

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

    text = (TextView) findViewById(R.id.textView_Text);

    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();

    // Listen to the server socket if we're not connected
   // while (true) {

        try {
            // Create a new listening server socket
            Log.d((String) this.getTitle(), ".....Initializing RFCOMM SERVER....");

            // MY_UUID is the UUID you want to use for communication
            mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("MyService",    MY_UUID);
            //mmServerSocket =  mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID); // you can also try  using In Secure connection...

            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket = mmServerSocket.accept();

        } catch (Exception e) {

        }

        byte[] buffer = new byte[256];  // buffer store for the stream
        int bytes; // bytes returned from read()
        try {
            Log.d((String) this.getTitle(), "Closing Server Socket.....");
            mmServerSocket.close();

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams

            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();

            DataInputStream mmInStream = new DataInputStream(tmpIn);
            DataOutputStream mmOutStream = new DataOutputStream(tmpOut);
            // here you can use the Input Stream to take the string from the client  whoever is connecting
            //similarly use the output stream to send the data to the client

         // Read from the InputStream
            bytes = mmInStream.read(buffer);
            String readMessage = new String(buffer, 0, bytes);
            // Send the obtained bytes to the UI Activity

            text.setText(readMessage);
        } catch (Exception e) {
            //catch your exception here
        }
   // }
}
}

Any questions? :)

A: Basically, you'll need to match the way data is sent from one device to the way data is received by the other one.
SPP is stream based and transfers bytes of data. So, whatever bytes the sending device transmits must be interpreted correctly by the receiver.
An InputStream gives you access to the raw bytes transmitted, and you'll have to do something with them; i.e. decode them in some way as needed. For instance, if the sender uses an ObjectOutputStream to do the encoding prior to transmission, the receiver will have to use an ObjectInputStream to decode the input.
You may want to read up on InputStream (read()), ObjectInputStream, and toString().
Besides, reading from a blocking stream should almost always be done in a separate thread; and especially so when reading from some remote device/host/network/... with possible unknown delays or transmission speed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SwiftUI nested API JSON call I'm working on a little SwiftUI Project with some data, hosted by my own local network.
When the view appears, I'm calling the QuestionApiCall().getAllQuestions method which returns an Array of Question Objects. So far so good.
In every Question Object inside of the returned Array, there is a variable called senderId.
This variable is necessary for calling another Method: UserByApiCall(id: senderId).getUserById for getting the name of the User which asked the Question.
My idea was:
ScrollView(showsIndicators: false) {
    VStack {
       ForEach(questions) {question in
           QuestionView(name: ?, content: question.content, creationTime: question.creation)
       }
    }
}
.onAppear() {
    QuestionApiCall().getAllQuestions { (questions) in
        self.questions = questions
}

Displaying the Question works properly but I don't know how to display their names, which can only displayed when calling the UserByApiCall(id: senderId).getUserById every time it loops threw the questions-Array with the specific senderId.
In theory I need to execute the UserByApiCall(id: senderId).getUserById every time question gets looped in the ForEach-Loop with the question.senderId for getting the User Object for every Question to display their names.
I really got no Idea how to make it or where to call it.
I can't just edit the Api and their methods because its an exercise from my Internship.

A: If you really can´t change the API move the responsibility to call the name API to your QuestionView.
As you didn´t include your QuestionView I need to make a few asumptions about it.
Your name var should look like this:
@State private var name: String = ""

In the .onApear of QuestionView add your function to call the name:
.onApear{
    if name == ""{
        UserByApiCall(id: senderId).getUserById{[weak self] name in
            self?.name = name
        }
    }
}

And finally make your VStack a LazyVStack:
LazyVStack {
   ForEach(questions) {question in
       QuestionView(name: ?, content: question.content, creationTime: question.creation)
   }
}

The LazyVstack will ensure, that not all elements are loaded at once.


text:
Q: how solve the boolean expression so my question is prove the following relation and solve the boolean expression. i'm stuck. because usually i solve the question is not like this.
i) AB+ABC+ABC=AB
ii) Z(Y+Z)(X+Y+Z)=Z

A: Hint:

*

*$LHS=AB+ABC+ABC=AB+ABC=AB(1+C)=AB.1=AB=RHS$

*$LHS=Z(Y+Z)(X+Y+Z)=Z(Y+Z+0)(Y+Z+X)=Z(Y+Z+0.X)=Z(Y+Z)=(Z+0)(Z+Y)=Z+0.Y=Z=RHS$
This assumes that you are familiar with the various properties and identities of Boolean Algebra.


text:
Q: Cyclic inequality with square roots and three variables Is the following inequality true for any a,b,c>0? I couldn't find a counterexample but I couldn't prove it either.
$\sum \sqrt{a+b} \ge \sqrt{2}  \sum   \sqrt{a}$
(The sum is cyclic)

A: Also, by C-S:
$$\sum_{cyc}\sqrt{a+b}=\frac{1}{\sqrt2}\sum_{cyc}\sqrt{(1^2+1^2)\left((\sqrt{a})^2+\sqrt{b})^2\right)}\geq\frac{1}{\sqrt2}\sum_{cyc}(\sqrt{a}+\sqrt{b})=\sum_{cyc}\sqrt{2a}.$$

A: $$\sqrt{a+b} \ge \frac{\sqrt{2}}{2} (\sqrt{a}+\sqrt{b}) $$
$$a+b \ge \frac{a+2\sqrt{ab}+b}{2}$$
$$a-2\sqrt{ab}+b \ge 0$$
$$(\sqrt{a}-\sqrt{b})^2 \ge 0$$ which is obviously true
Summing the inequality cyclically gets us to the desired inequality with equality for a=b=c


text:
Q: How to check if all keys in json equal true how can I check if all the keys in a json object equal to true?
my object looks like this
    success = {
    "first_name": false,
    "middle_name": false,
    "last_name": false,
    "d_o_b": false,
    "sex": false,
    "email": false,
    "re_email": false,
    "password": false,
    "re_password": false
};

I proccess the object and every thing that turns out ok gets changed to true,
now at the end I want to check if all are true, how can I do this?
thank's :-)

A: The most straightforward way is with a for loop. This will ensure it will work with older browsers that may not support iterators.
var all_true = true;
for (var s in success) {
    if (!success[s]) {
        all_true = false;
        break;
    }
}

The break is not strictly necessary but will short-circuit the loop if all you care about if that none are false.

A: var everythingOK = true;

for (var i = 0; i < success.length; i++)
{
    if( ! success[i])
    {
         everythingOK = false;
         break;
    }
}

if(everythingOK)
    alert('Success!');

this should do ;)

A: Or a bit more functionally:
Object.keys(success).every(function(key) {
  return success[key];
});


text:
Q: Show all ngForm Errors I have big form with Angular 1.3. The Save Button is greyed out as long as the form is invalid (myForm.$invalid). Now I want a small Box at the bottom to display all invalid fields, so the users nows, what is wrong.
How can I bind all the errors and the fields which cause them?
So that you can for example see: "Username: Contains invalid characteres"


text:
Q: JQuery in Chrome Console - Automate populating a text and clicking a button I go to a specific site to read articles. They have a textbox to enter a category and a submit button. The submission is happening via AJAX.
I am trying to automate the populating of textbox and then the clicking of the button. I can do those individually fine, but when I hook it up inside a loop, only the last iteration takes in effect.
Here is the code I tried entering on the chrome console:
var myArray1 = ['category1','category2'];
for (var i = 0; i < myArray1.length; i++) {
    $("#txt1").val(myArray1[i]);
    $("#btn1").click();
}

The population of the text box and the clicking of the button only happens at the last iteration.

A: Try this - you can change the wait for even a longer time by changing the 1000 to a bigger number.
var myArray1 = ['category1','category2'];
for (var i = 0; i < myArray1.length; i++) {
   setTimeout("addCategory('" + myArray1[i] + "')", 1 * 1000);
}

function addCategory(categoryName){
   $("#txt1").val(categoryName);
   $("#btn1").click();
}


text:
Q: Order of operations in plot(\x, {function}) I draw a random function with plot (\x, {function}):
\begin{tikzpicture}[scale=1]
\draw[thick,scale=1,domain=-0.83:10,samples=100,smooth,variable=\x] plot(\x,{(1/((\x)+1))-cos((180/pi)*0.2*(\x)^2)*0.5*\x});
\end{tikzpicture}

The output looks nice, however I don't think that this is the function given in the expression because if I give the same function to Wolframalpha, it looks very different. I know for example that one must write (\x)^2 instead of \x^2 in plot to get the square function. Is there other similar rules that I am missing? Or maybe I did not copy the function correctly into Wolframalpha but I am quite sure I did. I put all possible parenthesis in the expression to make sure that the order of operations was right but it is still different..

A: The variable \x has to be converted to degrees inside the cosine function using deg(\x) instead of \x. Another option is to work with radians using the option \pgfplotsset{trig format plots=rad} when you use pgfplots.
Here is my attempt using pgfplots:
\documentclass[border=0.2cm]{standalone}

\usepackage{pgfplots}

\pgfplotsset{trig format plots=rad, compat=newest}

\begin{document}

\begin{tikzpicture}[scale=1]

\begin{axis}
[
    ymin=-0.5,ymax=4.2,xmin=-0.85,xmax=1.05,
    axis x line = bottom,
    axis y line = left,
    axis x line shift=-0.5,
    axis y line shift=-0.85,
    minor tick num = 2,
    ticklabel style = {font=\scriptsize},
    ticklabel style = {fill=white,inner sep =2pt},
    width = 10cm,
    height = 7cm,
    grid=both,
    major grid style = {lightgray!50},
    minor grid style = {lightgray!40,dotted},
]
\addplot[thick,blue,domain=-0.7:0.96,samples=1000] {(1/(\x+1))-cos((180/pi)*0.2*(\x)^2)*0.5*\x};
\end{axis}

\end{tikzpicture}

\end{document}

which yields:

close to the Wolframalpha results:


text:
Q: raise KeyError(key) from None I am getting an error message and have no idea how to proceed, the error message is displayed below. I have downloaded all necessary tools for it to run however it seems to be having a problem with the keys. I have inputted them right however to keep my account private I have substituted the account username and password hidden. Thanks in advance
C:\Users\User\Downloads\real-time-intrinio-python-master\real-time-intrinio-python-master> python realtime.py AAPL
Using Ticker: AAPL
Traceback (most recent call last):
  File "realtime.py", line 18, in <module>
     r=requests.get(auth_url, headers={"Authorization": "Basic %s" % base64.b64encode(os.environ['myUsername'] + ":" + os.environ['myPassword'])})
  File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
     raise KeyError(key) from None
KeyError: 'myUsername'

This is the code I am using and line 18 is "r=requests.get(auth_url, headers..."
import websocket
import _thread
import time
import requests
import base64
import json
import sys
import os
from requests.auth import HTTPBasicAuth

try:
    print ("Using Ticker: " + str(sys.argv[1]))
except:
    print ("Please include ticker as first argument")
    sys.exit()

auth_url = "https://realtime.intrinio.com/auth";
r=requests.get(auth_url, headers={"Authorization": "Basic %s" % base64.b64encode(os.environ['7641353c8540cd7c795c96f097185c26'] + ":" + os.environ['c15d32295cf254ab57d5523c5bf95f80'])})

socket_target = "wss://realtime.intrinio.com/socket/websocket?token=%s" % (r.text)

def on_message(ws, message):
    try:
        result = json.loads(message)
        print (result["payload"])
    except:
        print (message)

def on_error(ws, error):
    print ("###ERROR### " + error)

def on_close(ws):
    print ("###CONNECTION CLOSED###")

def on_open(ws):
    def run(*args):
        security = "iex:securities:" + str(sys.argv[1]).upper()
        message = json.dumps({"topic": security,"event": "phx_join","payload": {},"ref": "1"})
        ws.send(message)
    thread.start_new_thread(run, ())

websocket.enableTrace(True)
ws = websocket.WebSocketApp(socket_target, on_message = on_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()

A: To summarize and add to the conversation.
As chickity already pointed out, you need to set your environment variables. This can be down with Python or via CMD/terminal.
# Set environment variables
os.environ['myUsername'] = 'username'
os.environ['myPassword'] = 'secret'

However, doing this in a script can lead to the potential fatal mistake that your secrets/passwords are added to git. Therefore, it is advised to do this via CMD. To permanently add the environment variables use setx. For some more details and caveats see this post.
setx myUsername username
setx myPassword secret

After doing this, you could change line 18 to:
# Get environment variables and create request
USER = os.getenv('myUsername')
PASSWORD = os.environ.get('myPassword')
token = base64.b64encode(f"{USER}:{PASSWORD}")
r=requests.get(auth_url, headers={"Authorization": f"Basic {token}"})


text:
Q: How to make specular lighting on python to implement the Phong lighting? I need your help. Using python, I have to implement the lighting of my three-dimensional shape by the phong model. My figure is a deltoidal icositetrahedron. I was able to build this shape, found the coordinates of the vertices, and also calculated the normals to each face.
I used pygame, pyopengl.
To implement the phong lighting model, I managed to make ambient lighting and diffuse lighting, but I do not know what functions to use for specular lighting.
I tried to apply functions such as glMaterialfv() with different parameters, but it didn't work out for me.

Here is my code:
import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (0, - 0, 1.15894198417663574),
    (0.63384598493576048, -0.63384598493576048, 0.63384598493576048),
    (0.81949597597122192, 0, 0.81949597597122192),
    (1.15894198417663574, 0, -0),
    (0.81949597597122192, 0.81949597597122192, -0),
    (0.81949597597122192, 0, -0.81949597597122192),
    (0.63384598493576048, 0.63384598493576048, 0.63384598493576048),
    (0.81949597597122192, -0.81949597597122192, 0),
    (-0, 0.81949597597122192, 0.81949597597122192),
    (-0.81949597597122192, 0, 0.81949597597122192),
    (0.63384598493576048, 0.63384598493576048, -0.63384598493576048),
    (0, 0, -1.15894198417663574),
    (0, -0.81949597597122192, -0.81949597597122192),
    (-0.81949597597122192, 0, -0.81949597597122192),
    (0, 0.81949597597122192, -0.81949597597122192),
    (0.63384598493576048, -0.63384598493576048, -0.63384598493576048),
    (-0, 1.15894198417663574, 0),
    (-0.81949597597122192, 0.81949597597122192, 0),
    (-1.15894198417663574, 0, 0),
    (-0.63384598493576048, 0.63384598493576048, 0.63384598493576048),
    (0, -1.15894198417663574, 0),
    (-0.81949597597122192, -0.81949597597122192, 0),
    (0, -0.81949597597122192, 0.81949597597122192),
    (-0.63384598493576048, -0.63384598493576048, 0.63384598493576048),
    (-0.63384598493576048, 0.63384598493576048, -0.63384598493576048),
    (-0.63384598493576048, -0.63384598493576048, -0.63384598493576048),
    )

surfaces = (
    (20, 21, 25, 12),
    (21, 25, 13, 18),
    (17, 24, 14, 16),
    (18, 13, 24, 17),
    (16, 14, 10, 4),
    (3, 5, 15, 7),
    (0, 2, 6, 8),
    (0, 2, 1, 22),
    (0, 22, 23, 9),
    (0, 9, 19, 8),
    (13, 11, 12, 25),
    (11, 13, 24, 14),
    (11, 14, 10, 5),
    (11, 5, 15, 12),
    (3, 5, 10, 4),
    (17, 18, 9, 19),
    (17, 19, 8, 16),
    (16, 8, 6, 4),
    (3, 2, 6, 4),
    (3, 2, 1, 7),
    (7, 1, 22, 20),
    (20, 21, 23, 22),
    (9, 23, 21, 18),
    (15, 7, 20, 12),
)

normals = [
    (-0.35740624923526854, -0.8628558767968414, -0.3574080425574267),
    (-0.8628548655932644, -0.3574083665235253, -0.3574083665235253),
    (-0.3574083665235253, 0.8628548655932644, -0.3574083665235253),
    (-0.8628558767968414, 0.3574080425574267, -0.35740624923526854),
    (0.3574080425574267, 0.8628558767968414, -0.35740624923526854),
    (0.8628558767968414, -0.3574080425574267, -0.35740624923526854),
    (0.35740624923526854, 0.3574080425574267, 0.8628558767968414),
    (0.35740624923526854, -0.3574080425574267, 0.8628558767968414),
    (-0.3574080425574267, -0.35740624923526854, 0.8628558767968414),
    (-0.35740624923526854, 0.3574080425574267, 0.8628558767968414),
    (-0.35740647831364963, -0.35740647831364963, -0.8628564298415289),
    (-0.35740624923526854, 0.3574080425574267, -0.8628558767968414),
    (0.3574080425574267, 0.35740624923526854, -0.8628558767968414),
    (0.35740624923526854, -0.3574080425574267, -0.8628558767968414),
    (0.8628558767968414, 0.3574080425574267, -0.35740624923526854),
    (-0.8628564298415289, 0.35740647831364963, 0.35740647831364963),
    (-0.3574083665235253, 0.8628548655932644, 0.3574083665235253),
    (0.3574080425574267, 0.8628558767968414, 0.35740624923526854),
    (0.8628558767968414, 0.3574080425574267, 0.35740624923526854),
    (0.8628558767968414, -0.3574080425574267, 0.35740624923526854),
    (0.3574083665235253, -0.8628548655932644, 0.3574083665235253),
    (-0.35740624923526854, -0.8628558767968414, 0.3574080425574267),
    (-0.8628548655932644, -0.3574083665235253, 0.3574083665235253),
    (0.35740624923526854, -0.8628558767968414, -0.3574080425574267)
]

colors = (
    (1,1,1),
    (0,1,0),
    (0,0,1),
    (0,1,0),
    (0,0,1),
    (1,0,1),
    (0,1,0),
    (1,0,1),
    (0,1,0),
    (0,0,1),
    )

edges = (
    (16, 17),
    (17, 18),
    (18, 21),
    (20, 21),
    (3, 4),
    (4, 16),
    (7, 3),
    (20, 7),
    (0, 2),
    (0, 9),
    (0, 22),
    (0, 8),
    (11, 13),
    (11, 12),
    (11, 14),
    (2, 3),
    (8, 16),
    (9, 18),
    (22, 20),
    (2, 1),
    (1, 22),
    (1, 7),
    (5, 11),
    (5, 15),
    (15, 12),
    (15, 7),
    (5, 3),
    (12, 20),
    (16, 14),
    (22, 23),
    (23, 9),
    (23, 21),
    (13, 24),
    (14, 24),
    (17, 24),
    (13, 25),
    (12, 25),
    (25, 21),
    (13, 18),
    (8, 6),
    (2, 6),
    (6, 4),
    (10, 4),
    (14, 10),
    (5, 10),
    (17, 19),
    (19, 9),
    (19, 8),
    )

def Cube():
    glBegin(GL_QUADS)
    for i_surface, surface in enumerate(surfaces):
        x = 0
        glNormal3fv(normals[i_surface])
        for vertex in surface:
            #x+=1
            glColor3fv(colors[x])
            glVertex3fv(verticies[vertex])
    glEnd()

    glColor3fv(colors[0])
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()

def main():
    global surfaces

    pygame.init()
    display = (800, 600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    clock = pygame.time.Clock()

    glMatrixMode(GL_PROJECTION)
    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)

    glMatrixMode(GL_MODELVIEW)
    glTranslatef(0, 0, -5)

    # Источник света - "от нас"
    glLight(GL_LIGHT0, GL_POSITION,  (0, 0, 1, 0.4))

    # Ambient lighting
    glLightfv(GL_LIGHT0, GL_AMBIENT, (0, 0, 0, 1))
    # Diffuse lighting
    glLightfv(GL_LIGHT0, GL_DIFFUSE, (0, 0.5, 0.1, 0))

#---------------------------------Specular Lighting------------It does not work!!!-----------
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (1,1,1,0))
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 128)
#--------------------------------------------------------------------------------------------

    glEnable(GL_DEPTH_TEST)

    while True:
        # Обрабатываем события
        for event in pygame.event.get():
            # Если нажимаем крестик на окошке - выходим
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glEnable(GL_COLOR_MATERIAL)
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE )
        #glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR)

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            glRotatef(10, 0, 1, 0)
        elif keys[pygame.K_RIGHT]:
            glRotatef(-10, 0, 1, 0)
        elif keys[pygame.K_UP]:
            glRotatef(10, 1, 0, 0)
        elif keys[pygame.K_DOWN]:
            glRotatef(-10, 1, 0, 0)

        Cube()

        glDisable(GL_LIGHT0)
        glDisable(GL_LIGHTING)
        glDisable(GL_COLOR_MATERIAL)

        pygame.display.flip()
        clock.tick(20)

if __name__ == '__main__':
    main()

A: Everything in your code is correct. With the legacy OpenGL fixed function pipeline this is the best result you can get.
The fixed functions pipeline uses a Blinn–Phong reflection model. However, Gouraud Shading and not Phong Shading is used. While Phong Shading generally means the technique with which the light calculations are carried out per fragment, in Gouraud Shading the light calculations are carried out per vertex. The calculated light is interpolated along the (triangular) Primitives.
In the case of specular highlights, the light distribution is not linear and cannot be calculated with linear interpolation. The effect is distorted or is completely lost.
See what the difference between phong shading and gouraud shading? and OpenGL Lighting on texture plane is not working.
The lighting can be improved by tessellating the mesh in small triangles. This causes that the light is computed for more points (vertices) and the interpolation has less effect.
Nowadays the light is calculated per fragment (Phong shading). To do this, you need to implement a Shader program. See GLSL fixed function fragment program replacement.
Describing this all in detail would be way too broad for a single Stack Overflow answer. I recommend reading a good OpenGL tutorial. e.g.: Python Opengl (my favorite one is for c++ LearnOpenGL).

To implement Phong Shading for your specific legacy code, you need to write a version 1.10 GLSL shader. For a good example, see Per Fragment Lighting. You need to make some adjustments to the shader program in order for the color material to work.
Vertex shader
varying vec3 vN;
varying vec3 v;
varying vec4 color;
void main(void)
{
   v = vec3(gl_ModelViewMatrix * gl_Vertex);
   vN = normalize(gl_NormalMatrix * gl_Normal);
   color = gl_Color;
   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

Fragment shader
varying vec3 vN;
varying vec3 v;
varying vec4 color;
#define MAX_LIGHTS 1
void main (void)
{
   vec3 N = normalize(vN);
   vec4 finalColor = vec4(0.0, 0.0, 0.0, 0.0);

   for (int i=0;i<MAX_LIGHTS;i++)
   {
      vec3 L = normalize(gl_LightSource[i].position.xyz - v);
      vec3 E = normalize(-v); // we are in Eye Coordinates, so EyePos is (0,0,0)
      vec3 R = normalize(-reflect(L,N));

      vec4 Iamb = gl_LightSource[i].ambient;
      vec4 Idiff = gl_LightSource[i].diffuse * max(dot(N,L), 0.0);
      Idiff = clamp(Idiff, 0.0, 1.0);
      vec4 Ispec = gl_LightSource[i].specular * pow(max(dot(R,E),0.0),0.3*gl_FrontMaterial.shininess);
      Ispec = clamp(Ispec, 0.0, 1.0);

      finalColor += Iamb + Idiff + Ispec;
   }
   gl_FragColor = color * finalColor;
}

Use PyOpenGLs OpenGL.GL.shaders module to compile and linke the shader:
def main():
    global surfaces, program

    pygame.init()
    display = (800, 600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    clock = pygame.time.Clock()

    program = compileProgram(
        compileShader(vertex_shader, GL_VERTEX_SHADER),
        compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    # [...]

Install the shader and enable lighting before drawing the polygons and disable is before drawing the wireframe. e.g.:
def Cube():

    glEnable(GL_POLYGON_OFFSET_FILL)
    glPolygonOffset(1.0, 1.0)
    glEnable(GL_LIGHTING)

    glUseProgram(program)
    glBegin(GL_QUADS)
    for i_surface, surface in enumerate(surfaces):
        x = 0
        glNormal3fv(normals[i_surface])
        for vertex in surface:
            #x+=1
            glColor3fv(colors[x])
            glVertex3fv(verticies[vertex])
    glEnd()

    glDisable(GL_LIGHTING)
    glDisable(GL_POLYGON_OFFSET_FILL)

    glUseProgram(0)
    glColor3fv(colors[0])
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()

Complete example:

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GL.shaders import *

vertex_shader = """
varying vec3 vN;
varying vec3 v;
varying vec4 color;
void main(void)
{
   v = vec3(gl_ModelViewMatrix * gl_Vertex);
   vN = normalize(gl_NormalMatrix * gl_Normal);
   color = gl_Color;
   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
"""

fragment_shader = """
varying vec3 vN;
varying vec3 v;
varying vec4 color;
#define MAX_LIGHTS 1
void main (void)
{
   vec3 N = normalize(vN);
   vec4 finalColor = vec4(0.0, 0.0, 0.0, 0.0);

   for (int i=0;i<MAX_LIGHTS;i++)
   {
      vec3 L = normalize(gl_LightSource[i].position.xyz - v);
      vec3 E = normalize(-v); // we are in Eye Coordinates, so EyePos is (0,0,0)
      vec3 R = normalize(-reflect(L,N));

      vec4 Iamb = gl_LightSource[i].ambient;
      vec4 Idiff = gl_LightSource[i].diffuse * max(dot(N,L), 0.0);
      Idiff = clamp(Idiff, 0.0, 1.0);
      vec4 Ispec = gl_LightSource[i].specular * pow(max(dot(R,E),0.0),0.3*gl_FrontMaterial.shininess);
      Ispec = clamp(Ispec, 0.0, 1.0);

      finalColor += Iamb + Idiff + Ispec;
   }
   gl_FragColor = color * finalColor;
}
"""

verticies = (
    (0, - 0, 1.15894198417663574),
    (0.63384598493576048, -0.63384598493576048, 0.63384598493576048),
    (0.81949597597122192, 0, 0.81949597597122192),
    (1.15894198417663574, 0, -0),
    (0.81949597597122192, 0.81949597597122192, -0),
    (0.81949597597122192, 0, -0.81949597597122192),
    (0.63384598493576048, 0.63384598493576048, 0.63384598493576048),
    (0.81949597597122192, -0.81949597597122192, 0),
    (-0, 0.81949597597122192, 0.81949597597122192),
    (-0.81949597597122192, 0, 0.81949597597122192),
    (0.63384598493576048, 0.63384598493576048, -0.63384598493576048),
    (0, 0, -1.15894198417663574),
    (0, -0.81949597597122192, -0.81949597597122192),
    (-0.81949597597122192, 0, -0.81949597597122192),
    (0, 0.81949597597122192, -0.81949597597122192),
    (0.63384598493576048, -0.63384598493576048, -0.63384598493576048),
    (-0, 1.15894198417663574, 0),
    (-0.81949597597122192, 0.81949597597122192, 0),
    (-1.15894198417663574, 0, 0),
    (-0.63384598493576048, 0.63384598493576048, 0.63384598493576048),
    (0, -1.15894198417663574, 0),
    (-0.81949597597122192, -0.81949597597122192, 0),
    (0, -0.81949597597122192, 0.81949597597122192),
    (-0.63384598493576048, -0.63384598493576048, 0.63384598493576048),
    (-0.63384598493576048, 0.63384598493576048, -0.63384598493576048),
    (-0.63384598493576048, -0.63384598493576048, -0.63384598493576048),
    )

surfaces = (
    (20, 21, 25, 12),
    (21, 25, 13, 18),
    (17, 24, 14, 16),
    (18, 13, 24, 17),
    (16, 14, 10, 4),
    (3, 5, 15, 7),
    (0, 2, 6, 8),
    (0, 2, 1, 22),
    (0, 22, 23, 9),
    (0, 9, 19, 8),
    (13, 11, 12, 25),
    (11, 13, 24, 14),
    (11, 14, 10, 5),
    (11, 5, 15, 12),
    (3, 5, 10, 4),
    (17, 18, 9, 19),
    (17, 19, 8, 16),
    (16, 8, 6, 4),
    (3, 2, 6, 4),
    (3, 2, 1, 7),
    (7, 1, 22, 20),
    (20, 21, 23, 22),
    (9, 23, 21, 18),
    (15, 7, 20, 12),
)

normals = [
    (-0.35740624923526854, -0.8628558767968414, -0.3574080425574267),
    (-0.8628548655932644, -0.3574083665235253, -0.3574083665235253),
    (-0.3574083665235253, 0.8628548655932644, -0.3574083665235253),
    (-0.8628558767968414, 0.3574080425574267, -0.35740624923526854),
    (0.3574080425574267, 0.8628558767968414, -0.35740624923526854),
    (0.8628558767968414, -0.3574080425574267, -0.35740624923526854),
    (0.35740624923526854, 0.3574080425574267, 0.8628558767968414),
    (0.35740624923526854, -0.3574080425574267, 0.8628558767968414),
    (-0.3574080425574267, -0.35740624923526854, 0.8628558767968414),
    (-0.35740624923526854, 0.3574080425574267, 0.8628558767968414),
    (-0.35740647831364963, -0.35740647831364963, -0.8628564298415289),
    (-0.35740624923526854, 0.3574080425574267, -0.8628558767968414),
    (0.3574080425574267, 0.35740624923526854, -0.8628558767968414),
    (0.35740624923526854, -0.3574080425574267, -0.8628558767968414),
    (0.8628558767968414, 0.3574080425574267, -0.35740624923526854),
    (-0.8628564298415289, 0.35740647831364963, 0.35740647831364963),
    (-0.3574083665235253, 0.8628548655932644, 0.3574083665235253),
    (0.3574080425574267, 0.8628558767968414, 0.35740624923526854),
    (0.8628558767968414, 0.3574080425574267, 0.35740624923526854),
    (0.8628558767968414, -0.3574080425574267, 0.35740624923526854),
    (0.3574083665235253, -0.8628548655932644, 0.3574083665235253),
    (-0.35740624923526854, -0.8628558767968414, 0.3574080425574267),
    (-0.8628548655932644, -0.3574083665235253, 0.3574083665235253),
    (0.35740624923526854, -0.8628558767968414, -0.3574080425574267)
]

colors = (
    (1,1,1),
    (0,1,0),
    (0,0,1),
    (0,1,0),
    (0,0,1),
    (1,0,1),
    (0,1,0),
    (1,0,1),
    (0,1,0),
    (0,0,1),
    )

edges = (
    (16, 17),
    (17, 18),
    (18, 21),
    (20, 21),
    (3, 4),
    (4, 16),
    (7, 3),
    (20, 7),
    (0, 2),
    (0, 9),
    (0, 22),
    (0, 8),
    (11, 13),
    (11, 12),
    (11, 14),
    (2, 3),
    (8, 16),
    (9, 18),
    (22, 20),
    (2, 1),
    (1, 22),
    (1, 7),
    (5, 11),
    (5, 15),
    (15, 12),
    (15, 7),
    (5, 3),
    (12, 20),
    (16, 14),
    (22, 23),
    (23, 9),
    (23, 21),
    (13, 24),
    (14, 24),
    (17, 24),
    (13, 25),
    (12, 25),
    (25, 21),
    (13, 18),
    (8, 6),
    (2, 6),
    (6, 4),
    (10, 4),
    (14, 10),
    (5, 10),
    (17, 19),
    (19, 9),
    (19, 8),
    )

def Cube():

    glEnable(GL_POLYGON_OFFSET_FILL)
    glPolygonOffset(1.0, 1.0)
    glEnable(GL_LIGHTING)

    glUseProgram(program)
    glBegin(GL_QUADS)
    for i_surface, surface in enumerate(surfaces):
        x = 0
        glNormal3fv(normals[i_surface])
        for vertex in surface:
            #x+=1
            glColor3fv(colors[x])
            glVertex3fv(verticies[vertex])
    glEnd()

    glDisable(GL_LIGHTING)
    glDisable(GL_POLYGON_OFFSET_FILL)

    glUseProgram(0)
    glColor3fv(colors[0])
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()

def main():
    global surfaces, program

    pygame.init()
    display = (800, 600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    clock = pygame.time.Clock()

    program = compileProgram(
        compileShader(vertex_shader, GL_VERTEX_SHADER),
        compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    glMatrixMode(GL_PROJECTION)
    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)

    glMatrixMode(GL_MODELVIEW)
    glTranslatef(0, 0, -5)

    # Источник света - "от нас"
    glLight(GL_LIGHT0, GL_POSITION,  (0, 0, 1, 0.4))
    # Ambient lighting
    glLightfv(GL_LIGHT0, GL_AMBIENT, (0.2, 0.2, 0.2, 1))
    # Diffuse lighting
    glLightfv(GL_LIGHT0, GL_DIFFUSE, (0, 0.5, 0.1, 0))

#---------------------------------Specular Lighting------------It does not work!!!-----------
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (1,1,1,0))
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 128)
#--------------------------------------------------------------------------------------------

    glEnable(GL_DEPTH_TEST)

    while True:
        # Обрабатываем события
        for event in pygame.event.get():
            # Если нажимаем крестик на окошке - выходим
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glEnable(GL_COLOR_MATERIAL)
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
        #glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR)

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            glRotatef(5, 0, 1, 0)
        elif keys[pygame.K_RIGHT]:
            glRotatef(-5, 0, 1, 0)
        elif keys[pygame.K_UP]:
            glRotatef(5, 1, 0, 0)
        elif keys[pygame.K_DOWN]:
            glRotatef(-5, 1, 0, 0)

        Cube()

        glDisable(GL_LIGHT0)
        glDisable(GL_LIGHTING)
        glDisable(GL_COLOR_MATERIAL)

        pygame.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()


text:
Q: What do I do to upgrade docker.io if it fails with apt upgrade? I am trying to upgrade Ubuntu 18.04 with a standard apt update && apt upgrade but I am getting a failure. What should I do to proceed and keep the system updated?
I'm getting the error:
Setting up docker.io (20.10.2-0ubuntu1~18.04.2) ...
mv: cannot stat '/var/lib/docker.migrating/*': No such file or directory
dpkg: error processing package docker.io (--configure):
 installed docker.io package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 docker.io
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: The issue has been reported and a workout was suggested here: https://github.com/ubuntu/zsys/issues/170#issuecomment-826359558
Following the steps worked for me.
sudo mkdir /var/lib/docker.migrating
echo 'dummy' | sudo tee /var/lib/docker.migrating/workaround.txt

this will allow the stat '/var/lib/docker.migrating/*' to not fail with an error.
After the successful apt update docker.io run, you can remove the workaround dummy file:
sudo rm /var/lib/docker/workaround.txt


text:
Q: Can the Asus TF700 run ubuntu? So i'm thinking of getting the Asus Transformer Infinity TF700 and I was wondering if it could run ubuntu.
Also I have heard that there are not many good apps for tablet android OS, if I did get ubuntu would it have more apps? What other benefits does ubuntu have over android?

A: Long story short: if you can live without rotation; or not knowing if you will have sound, video codification or Suspend/resume capabilities; or some other minor glitches go ahead, otherwise, look for another table.
Details
Following the table State of Things (updated till 2013-05-03) this is the actual status of the tablet:

Graphics          Perfect
Boot process      Working          -- No boot animation
Rotation          Bloked/Broken    -- General issue: not supported in Ubuntu Touch yet.
Wireless network  Work in Progress -- OK, but can't enter password with on-screen keyboard
Sound             Unknown          -- No details
Touch             Perfect
Camera            Working          -- Not working zoom & face camera
Video Decode      Unknown          -- No details
Suspend/Resume    Unknown          -- No details
Dock keyboard     Work in Progress -- Special keys not working, on input shell restarted sometimes
Dock touchpad     Unknown          -- No cursor in the shell
Dock Battery      Working          -- No dock battery indicator

Legend:

*

*Perfect: Work without problems.

*Working: Works, minor issues only, some patches pending.

*Work in progress: Self-explanatory

*Bloked/Broken: Severely broken, unusable or progress is blocked

*Unknown: Unknown status


text:
Q: Selection Sort on an Array of Objects Looked around online, but haven't been able to find anything concerning this.
I'm in a C++ introductory class and have a project that is dealing with Arrays of Objects. An object (called media) has a name and a rating. I have three different media objects put into an media object array. I need to find a way to sort them by name. I was given code for selection sort for c-strings, but haven't been able to figure out what exactly to do with this to change it over to dealing with the media objects. Here is my selection sort for the c-strings.
void selectsort(char str[][20], int N)
{
int pass, j, min;
char temp[20];
for (pass = 0; pass <= N - 2; pass++)  // passes
{
min = pass;
for (j = pass + 1; j < N; j++)  // in each pass
if (strcmp(str[min], str[j]) > 0)
min = j;
    strcpy(temp, str[min]);
    strcpy(str[min], str[pass]);
    strcpy(str[pass], temp);
    }
}

I have gotten rid of strcmp by overloading < with
int media::operator<(media med)
    {
        return strcmp(mname, med.mname);
    }

and strcpy by overloading = with
void media::operator=(media med)
    {
        strcpy(mname, med.mname);
    }

I believe that this would return the same results, yes?
So here is my code so far (have just been throwing myself at it non-understanding of how to do it).
void selsort(media mry[], int n) // mry[] is the object array, n is the
                                 // number of objects in the array
{
    int pass, j, min;
    media temp[1];
    for (pass = 0; pass <= n - 2; pass++)  // passes
    {
        min = pass;
        for (j = pass + 1; j < n; j++)  // in each pass
            if ((mry[min] < mry[j]) < 0)
                min = j;
        temp = mry[min];
        mry[min] = mry[pass];
        temp = mry[min];
    }
}

I understand that there are a lot of flaws in this code. The temp comparison doesn't work and when I try to get it to using *temp or temp[0] (trying everything under the sun over here) I get corrupted data errors. I can't seem to figure it out though. I've always struggled with understanding sorts, and this just adds insult to injury.
(Also please note that some notations might not be correct, but this is what I was taught in this class and what this professor asks that we code in)
Thanks for any help!

A: There are 2 things wrong with your code:

*

*media temp[1]; Why would you want your temporary media storage for swapping be an array of 1?

*The swapping: temp = mry[min]; mry[min] = mry[pass]; temp = mry[min]; See anything wrong with it?

Here is the adjusted function, which BTW works fine:
void selsort(media mry[], int n) // mry[] is the object array, n is the
                                 // number of objects in the array
{
    int pass, j, min;
    media temp;
    for (pass = 0; pass <= n - 2; pass++)  // passes
    {
        min = pass;
        for (j = pass + 1; j < n; j++)  // in each pass
            if ((mry[min] < mry[j]) < 0)
                min = j;
        temp = mry[min];
        mry[min] = mry[pass];
        mry[pass] = temp;
    }
}


text:
Q: dynamic ssl for SaaS my SaaS application create subdomain for each customer customer.myapp.com. in my nginx i configured wildcard ssl certificate. (*.myapp.com) and it works.
how can I allow my customer to connect their own domain to their subdomain with ssl?
i.e customer.com => customer.myapp.com
I don't want to manually add certificate each customer. I want it to be automatically.
how could it have done with nginx?


text:
Q: How to get the count of elements in database using delphi XE8 I am trying to make an e-mail sender with Delphi. I have database with statuses and emails and I need to get the number of elements in my database so that I can make a for loop. This is part of my code:
procedure TForm1.bDataBaseClick(Sender: TObject);
      var
        i : integer;
    begin
      FDConnection1.StartTransaction;
      FDConnection1.Open();
      //FDQuery1.ExecSQL('UPDATE Vasko '
                               //+' SET BatchNumber = 112233 '
                               //+' WHERE StatusOfProd = 4');
      //FDQuery1.ExecSQL('select * from Vasko');
      for i := 0 to FDQuery1.ComponentCount - 1 do
      showmessage('hello');

      FDConnection1.Commit;
      FDConnection1.Close();
end;

For now I just want to make the loop that shows message several times. I think that I have mistake in this line:
 for i := 0 to FDQuery1.ComponentCount - 1 do

Thank you in advance!


text:
Q: Como adicionar uma imagem no menu? Preciso adicionar uma imagem no menu do meu programa em Python. Estou utilizando a biblioteca wxpython.
O menu está assim:
O código:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wx

class Frame(wx.Frame):
    title = "SEA"
    def __init__(self):
        wx.Frame.__init__(self, None, title=self.title, size=(800, 600))
        self.panel1 = wx.Panel(self, -1)
        self.createMainPanel()
        self.createMainMenu()
        self.Centre()

    def createMainPanel(self, color=(0, 0, 0)):
        panel = wx.Panel(self, id=wx.ID_ANY, pos=(0, 0), size=self.GetSize())
        panel.SetBackgroundColour('GRAY')

class App(wx.App):
    def OnInit(self):
        self.mainScreen = Frame()
        self.SetTopWindow(self.mainScreen)
        self.mainScreen.Show()

        return True

if __name__ == '__main__':
    app = App(False)
    app.MainLoop()

Quero adicionar a seguinte imagem no menu, na parte de cima, alinhada ao centro, que é esta:
Alguém pode me ajudar com isso? pesquisei o dia todo e não consegui. Seria melhor se fosse com botões de imagem, pois vou precisar adicionar outros depois.

A: Veja se este trecho lhe ajuda:
self.bitmap = wx.Bitmap('imagem.jpg')
        wx.EVT_PAINT(self, self.OnPaint)

        self.Centre()

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.bitmap, 60, 20)

Retirei desse tuto aqui parece bom...
Vlw espero que ajude
Qualquer coisa vai comentando...


text:
Q: ACM SIGCOMM 2015 LaTeX template not Compiling I downloaded the ACM Sigcomm 2015 template but its not compiling and giving me hundreds of errors. Kindly help me.
Here is the template link: http://conferences.sigcomm.org/sigcomm/2015/doc/sig-alternate-10pt.cls

A: The reason is that this template is a CLASS file *.cls so you need to add it in your *.tex document as:
\documentclass[conference]{sig-alternate}

where sig-alternate is the required *.cls file that needs to be in the working directory of your project. You can create this class file sig-alternate.cls by copying the code from the link: http://conferences.sigcomm.org/sigcomm/2015/doc/sig-alternate-10pt.cls and pasting it in any text editor and saving it as *.cls. I hope you got my point.


text:
Q: Working with Subversion the same as with Visual Source Safe in Visual Studio At work I just started using Subversion with AnkhSVN instead of Visual Source Safe. I managed to integrate it well enough but it doesn't seem the same.
Using VSS the following would happen:
A user check out a file by right clicking and selecting "check out" or by editing it. If another user tried to modify the same file he would get an error. No 2 users could edit the same file at the same time. No fancy merging. No conflicts and no conflict resolutions.
I understand the the philosophy behind Subversion is different but is there any way that this behavior described above could be duplicated with Subversion?
There is an option in AnkhSVN called "Automatically lock files on change..." but even if I activate this option when I edit a file it never gets automatically locked.
Even if this option worked the other users wouldn't see the lock until they commited the file. They wouldn't get an error when they tried to edit it like they would in Visual Source Safe.
So basically: can Visual Source Safe's behavior be duplicated using Subversion and AnkhSVN?

A: The point of using subversion over source safe is that you don't have exclusive lock and many people can work on the same file.
You are loosing quite a lot of the benefits of SVN if you start using it with exclusive locks on files.
The idea is that you fix conflicts during merges of code.
See this SO question and answers for a bit of a discussion on the issues (Revision control locking: Is the jury still out?).

A: The Agent SVN is a MS-SCCI plugin (just like VSS) for Subversion so it integrates with Visual Studio just like VSS.
It also has a Lock on check out option and with that feature on it does feel a lot like VSS.

A: You need to set svn:needs-lock subversion properties on the files that you want to explicitly lock. It's really only recommended for files that cannot be easily merged, like (most) binary files and not on text/code files. Usually text/code files merge great automatically, and when they don't conflicts are usually easy to solve.
AnkhSVN will ask you to take lock the file (same as checkout in VSS) when you attempt to edit it when the svn:needs-lock property is set. If you enable the "Automatically lock files" feature, the lock dialog is suppressed, and you will take a lock on the file without a dialog showing up.
Svnbook explains the differences between a lock-modify-unlock and copy-modify-merge, and the svn:needs-lock behavior is also described


text:
Q: SSH remote connection closes immediately after login When I try to connect via ssh to a certain web server I get immediately after successful login the message Connection to xx.xx.xx.xx closed.
I wanted to post what I get in verbose mode, but unfortunately I get the message This looks like spam. when I try to post the whole output, so I just can post excerpts, sorry …
dave@VideoBeast ~ % ssh -vvv mylogin@xx.xx.xx.xx
OpenSSH_8.1p1, LibreSSL 2.7.3
[…]
debug1: Connection established.
[…]
debug1: Authentication succeeded (password).
Authenticated to xx.xx.xx.xx ([xx.xx.xx.xx]:22).
[…]
Last login: Sat Jul 10 08:44:35 2021 from 79.206.178.207
debug3: receive packet: type 98
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug3: receive packet: type 98
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
debug2: channel 0: rcvd eow
debug2: channel 0: chan_shutdown_read (i0 o0 sock -1 wfd 4 efd 6 [write])
debug2: channel 0: input open -> closed
debug3: receive packet: type 96
debug2: channel 0: rcvd eof
debug2: channel 0: output open -> drain
debug2: channel 0: obuf empty
debug2: channel 0: chan_shutdown_write (i3 o1 sock -1 wfd 5 efd 6 [write])
debug2: channel 0: output drain -> closed
debug3: receive packet: type 97
debug2: channel 0: rcvd close
debug3: channel 0: will not send data after close
debug2: channel 0: almost dead
debug2: channel 0: gc: notify user
debug2: channel 0: gc: user detached
debug2: channel 0: send close
debug3: send packet: type 97
debug2: channel 0: is dead
debug2: channel 0: garbage collecting
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
  #0 client-session (t4 r0 i3/0 o3/0 e[write]/0 fd -1/-1/6 sock -1 cc -1)

debug3: send packet: type 1
debug3: fd 1 is not O_NONBLOCK
Connection to xx.xx.xx.xx closed.
Transferred: sent 2344, received 2868 bytes, in 1.1 seconds
Bytes per second: sent 2176.7, received 2663.3
debug1: Exit status 1
dave@VideoBeast ~ %

What could be the reason? Is there something I could fix on my Mac or should the server administrator something?
For your hints and thoughts many thanks in advance!


text:
Q: Is mysql automatically compressing the database? My table entry was pretty long , around 10000 characters , so i'm wondering if i need to compress that myself , e.g use gzip library , before inserting to mysql ?
Current i'm using MyISAM database format.
Thanks !

A: InnoDB support data compression:
http://dev.mysql.com/doc/innodb-plugin/1.0/en/innodb-compression-usage.html

A: you can use the attributes ROW_FORMAT=COMPRESSED, KEY_BLOCK_SIZE, or both in the CREATE TABLE and ALTER TABLE statements to enable table compression. Depending on the combination of option values, InnoDB attempts to compress each page
For more details go through below link:
Enabling Compression for a Table

A: The mysqlclient library may do some compression (with CLIENT_COMPRESS flag to mysql_real_connect) to minimize network bandwidth, but AFAIK the mysqld server program won't compress data on disk, unless asked (see Moshe's reply). And you probably don't want to search inside compressed data.
BTW, you should use InnoDB not MyISAM (which is sort-of deprecated).

A: To Enable compression on table you need to follow the below steps.
1)Need to set parameter in mysqlconfig file
SET GLOBAL innodb_file_per_table=1;
SET GLOBAL innodb_file_format=Barracuda;
2)Need to add clauses
ROW_FORMAT=COMPRESSED or KEY_BLOCK_SIZE on create or alter table command.
you can use any of this they are optional.
ALTER TABLE node ROW_FORMAT=compressed;


text: Q: Verify third party finger print - xamarin.forms I am trying to develop a xamarin.forms app for employee clock In .When user clock in, I can get the finger print data of that user stored in database through API. Can we compare the fetched finger print against users fingerprint when they apply their finger against phones scanner? I know we can authenticate against phones enrolled fingerprint. Is it possible to authenticate with applied finger print against fetched finger print in xamarin ? Any guidance is appreciated.


text:
Q: Configure root@localhost mail on postfix dovecot postfixadmin virtual mail server using postgresql freebsd 12 Using freebsdI I setup a postfix, dovecot, postgresql and postfixadmin virtual email server.  Everything is working to my satisfaction except email to root@localhost and my user email to localhost.  Having done a lot of investigation and some trial I'm not finding the answer.
I looked at mydestination I have localhost listed, I think that is correct.
I tried adding localhost as a postfixadmin domain, this fails the x.x edit.  localhost. does not work either.  Don't really want to change code for obvious reasons.  Localhost will resolve to the correct local ip 127.0.0.1.
Tried using mail to send root@localhost and get a dead.letter file with the message in it.
I am not a email server expert only the first time I've done this so much learning to do.
how do I solve this issue?
Thanks in advance for your help.


text:
Q: Office.context.mailbox.addHandlerAsync fails when reload the frame I am implementing the pinnable taskpane in my outlook web add-in
This is my code:
Office.initialize = function (reason) {
    $(document).ready(function () {
        // Listen to ItemChanged event
        Office.context.mailbox.addHandlerAsync(Office.EventType.ItemChanged, itemChanged, function (result) {
            console.log(result)
            if (result.status === Office.AsyncResultStatus.Failed) {
                // here will be hit if I do a postback in the server, could also be replicated by choosing "reload frame" in the right click menu
             {name: "Internal Error", message: "An internal error has occurred.", code: 5001}
            }
        });
        gatherMailItemInfo();
    });
}

Everything works fine( gatherMailItemInfo get calls when I switching between items. But as long as a do a post to the server ( can simply replicated by choosing "reload frame" in the right click menu) the handler will fail.
I am using office 365 for testing. Windows desktop client has no such issues.


text:
Q: How to totally get rid of Category in my blog? I prefer using tags and have no interest in using the categories. All my posts now are labeled with a category named "Uncategorized" and I want to turn them off! I want no more categories at all. How can I do that? Please help!
[Edit]
I'm using wordpress.com, not wordpress.org

A: You can't disable categories altogether, but you can prevent WP from displaying them:

*

*in the post editor screen within the admin interface, use screen options to hide the category picker.

*in your theme, remove category-related lines.
This won't, technically, disable everything category-related from showing (WP may still output, say, category RSS feeds and the like in HTML meta, and these will still work), but most of your authors and end users won't notice them.

A: There is no way at all to remove the uncategorized category from a wordpress.com webblog. It's not even possible with a self hosted wordpress w/o extensively hack the theme and the core.
The uncategorized category is a placeholder for a post not having any category. You can't even delete that category to not have any categories.
So sorry but the answer is no, there is no way to remove categories. Not on wordpress.com and only with a lot of changing the overall design of wordpress on a own copy.

A: Denis is right, there's no way to actually remove categories as a taxonomy from the 'post' post-type. If you're the only user, just use screen options to remove the categories meta box. If you want to remove it for all users, or you're trying to package a theme without categories, use this function:
add_action( 'add_meta_boxes', 'hide_categories_metabox' );

function hide_categories_metabox() {
    remove_meta_box('categorydiv','post','side');
}

If you really need to remove the functionality of categories altogether, hide the 'post' post type and register your own without support for categories. Just be aware that you won't be able to use WP's built-in archive functionality, at least until 3.1...?

A: I know I'm late to the party and maybe there is a way to completely get rid of the categories, but this is how I did it.
function modify_default_category() {
    $category_args = get_taxonomy( 'category' ); // returns an object of the category args
    // now re-register the taxonomy
    register_taxonomy( 'category', '', (array) $category_args ); //!the post type '' is not existing, so the category will not be shown at all
}
// hook it up to 11 so that it overrides the original register_taxonomy function
add_action( 'init', 'modify_default_category', 11 );

Alltough this does not really "remove" the categories, at least they will not be available for the default "post" post type. So no hiding metaboxes, admin columns and menu entries.


text:
Q: NodeJS how to write a file in a defined line I have a file with 10 lines of text, I have written a script to add more text, but only the end, I would like to add text in another line, for example in line 5
const fs = require('fs');
var comment = "/* \n */"
fs.appendFileSync("jsComents.js", comment, "UTF-8",{'flags': 'w+'});

The result in jsComments.js
var Food =
['hamburger',
    'pizza',
    'Sandwich',
    'Burritos'
];
var drink = [
'water',
'soda']
/*
*/

I would like to add the comment before the var drink

A: const fs = require('fs');
var comment = "/* \n */"

var lineNumber  = 5;
var data = fs.readFileSync('jsComents.js').toString().split("\n");
data.splice(lineNumber, 0, comment);
var text = data.join("\n");

fs.writeFile('jsComents.js', text, function (err) {
if (err) return console.log(err);
});

It works. the result:
var Food =
['hamburger',
    'pizza',
    'Sandwich',
    'Burritos'
];
/*
*/
var drink = [
'water', 'soda']


text:
Q: Manipulate element.style in React.js not working I am doing a project where I am trying to achieve the hover effects where the element enlarge and background color change. I made it happen toggling class but when I try to make the component I made more reusable by setting the props into the module I realize toggling class maybe not be a good option.So I tried to add inline style when hover.
I find the solution but the way to achieve it doesn't make a lot of sence to me, instead of adding lots of element.style.arribute="somthing"(if there is more than one attribute to change) I would like to just add one object with list of attributes inside.
So instead of
wrapper.current.style.backgroundColor = "red"; wrapper.current.style.color = "blue"; wrapper.current.style.fontSize = "2rem";
I believe when there is a lot of attributes to be manipulate it makes more sense if it can be like something like this:
wrapper.current.style = { backgroundColor: "red",color:blue,fontSize:2rem, };
But this just won't work for me.
snippet of this component here
import React from "react";
import { useRef } from "react";
import { useEffect } from "react";
import { useState } from "react";
// img:"../sources/computer-and-chair.jpg"
// imgName: "computer and chair"
// subtitle:"First website finnished with vanilla javascript"
function Project(props) {
  const [isHover, setIsHover] = useState(false);
  const wrapper = useRef(null);

  useEffect(() => {
    if (isHover) {
      wrapper.current.classList.add("effect");
      // wrapper.current.style.backgroundColor = "red"; work this way but not the way below...
      wrapper.current.style = { backgroundColor: "red" };
    } else {
      wrapper.current.classList.remove("effect");
      // wrapper.current.style.backgroundColor = "transparent"; work this way but not the way below...
      wrapper.current.style = { backgroundColor: "red" };
    }
  }, [isHover]);
  return (

         {
            setIsHover(true);
          }}
          onMouseOut={() => {
            setIsHover(false);
          }}
        />

{props.subtitle}

  );
}

export default Project;

I have tried those:
Looked into inline-styling, no direcly answer to my question.
Looked into element.style from MDN, no direcly answer to my question.


text:
Q: Get the sum and product of integres defined in a tree I have a little problem understanding how to to the following in Haskell:
Lets say I have a statement similar to this ones:

*

*a * (b + c)

*a + (b * c)

*a + (b * ( c + d))

*a * (b + ( c * d))

*etc. etc.

I want to express these statements in a tree and evaluate the result of each, for starters I defined the following data structure:
data statement = Number Int
               | Product statement statement
               | Sum statement statement
               deriving (Eq, Show)

For an example Tree to work with, I used the following function:
a :: statement
a = Product (Number 2) (Sum (Number 5) (Number 1))

Now I want to build a function treeResult which gives me the result of my statement defined, but I don't know how to approach this problem. The integer returned for the above statement should be 12.
My first guess was to write a function that takes "statement" as a parameter and returns an int, for starters only with simple statements.
treeResult :: statement -> Int
treeResult (Number a) = a
treeResult (Product (Number a) (Number b)) = a*b
treeResult (Sum (Number a) (Number b)) = a+b

Now I know that I need something that works recursive but I don't know how to write it in haskell, can someone help me out here, please?

A: treeResult (Sum statement1 statement2) = treeResult statement1 + treeResult statement2

Similar for Product. This is simply recognizing

*

*result of (a + b) == result of a + result of b

(BTW, the data type should be called Statement with an uppercase S.
data Statement = Number Int | Product Statement Statement | Sum Statement Statement
                 deriving (Eq, Show)

)

A: First off: statement needs to be capitalized since it's not a type variable. But that's the least important thing.
treeResult :: Statement -> Int
treeResult (Number x) = x

Obviously correct so far. We're matching the Number constructor, extract the Int and return that - well-typed and does what it should.
treeResult (Product (Number a) (Number b)) = a*b
treeResult (Sum (Number a) (Number b)) = a+b

This is well-typed, but it is not general enough. In this pattern, you are restricting the fields of Product and Sum to Numbers, but in fact they can be any Statement. So you instead need to define the Product/Sum:
treeResult (Product a b) = ...
treeResult (Sum a b) = ...

But we can't just add/multiply the two Statements. (+) and (*) are not defined for them (we're kind of doing that right now). When one operand is a Product, how do we get its value as an Int? By evaluating it. Statement is recursive, so we need recursion to evaluate it. Thus, the function becomes
treeResult (Product a b) = (treeResult a) * (treeResult b)
treeResult (Sum a b) = (treeResult a) + (treeResult b)


text:
Q: Get the number of queries in a batch I'm using batch execution with prepared statements to reduce the number of times I need to query the database.
The code that I am planning to write as part of our DB interface looks something like this
public void insertPerson(String name ) {
   psInsertPerson.setString(1, name);
   psInsertPerson.addBatch();
}

I can keep track of how many objects are in the batch by explicitly keeping track of it whenever the method is called, but is there a way to just ask the prepared statement how many it's batched up?


text:
Q: SimpleXMLElement::xpath: extracting-data from osm xml file with php i know little php but i am no expert here... - unfortunatley... so this question needs your advice: I tried to extract some data from an .Osm File. -.-you can run a demo-command here at overpass turbo i want to store the data in a database - (or at least in an excel-file)
> /* This has been generated by the overpass-turbo wizard. The original
> search was: "hospital in rome"
> */ [out:json][timeout:25]; // fetch area "" to search in {{geocodeArea:rome}}->.searchArea; // gather results (   // query part
> for:rome "hospital"   node["amenity"="hospital"](area.searchArea);
> way["amenity"="hospital"](area.searchArea);
> relation["amenity"="hospital"](area.searchArea); ); // print results
> out body;
> >; out skel qt;

So I have - within an amount of xml-data - something like this:

"tags": {
      "addr:city": "Barcelona",
      "addr:housenumber": "1",
      "addr:postcode": "08022",
      "addr:street": "Carrer de Torras i Pujalt",
      "amenity": "hospital",
      "contact:email": "info@clinicasagradafamilia.com",
      "contact:fax": "+34 932124050",
      "contact:phone": "+34 932122300",
      "contact:website": "http://csf.com.es/",
      "name": "Cliníca Sagrada Família"   }

So, the question is this: how can store all those values I tried to make some kind of foreach without sucess. And definitely I don't know why is suposse we have one Iteration that get all the values and why is not possible to store together.
Well i heard about that we can use SimpleXMLElement::xpath here to get all the values and the corresponding values. For example :
> $raw = <<<EOF <root> {   "type": "node",   "id": 583257940,   "lat":
> 41.4134446,   "lon": 2.1426945,   "tags": {
>     "amenity": "hospital",
>     "emergency": "yes",
>     "name": "Clinica Delfos"   } }, {   "type": "node",   "id": 618312181,   "lat": 41.4138593,   "lon": 2.1970778,   "tags": {
>     "addr:city": "Barcelona",
>     "addr:housenumber": "211",
>     "addr:postcode": "08020",
>     "addr:street": "Carrer de Fluvià",
>     "amenity": "hospital",
>     "health_facility:type": "health_centre",
>     "medical_system:western": "yes",
>     "name": "CAP Sant Martí",
>     "phone": "+93 307 07 66"   } }, {   "type": "node",   "id": 876348001,   "lat": 41.3841883,   "lon": 2.1952253,   "tags": {
>     "amenity": "hospital",
>     "emergency": "yes",
>     "name": "Hospital del Mar",
>     "website": "http://www.parcdesalutmar.cat/hospitals/hospital-del-mar/index.html",
>     "wheelchair": "yes"   } },
>
> </root> EOF; $xml = simplexml_load_string($raw);
>
> foreach($xml->xpath("//way") AS $way){
>     $via = $way->xpath("tag[@k='name']/@v")[0];
>     foreach($way->nd AS $nd){
>         $idnode = $nd["ref"];
>         echo $idnode .", ". $via  ."<br>";
>     } }

question: how to use SimpleXMLElement::xpath here?
xpath-approach that may help here:
i need to select all the data from above:
>   "tags": {
>     "addr:city": "Barcelona",
>     "addr:housenumber": "1",
>     "addr:postcode": "08022",
>     "addr:street": "Carrer de Torras i Pujalt",
>     "amenity": "hospital",
>     "contact:email": "info@clinicasagradafamilia.com",
>     "contact:fax": "+34 932124050",
>     "contact:phone": "+34 932122300",
>     "contact:website": "http://csf.com.es/",
>     "name": "Cliníca Sagrada Família"   }

That means that i have to  selects all above mentioned elements anywhere in the XML document.
tag[@k='name'] selects  child of current context node having k attribute value equal name. Then from that , /@v returns v attribute.
Finallyi have to getthe following dataset:
>   "tags": {
>     "addr:city": "Barcelona",

 "addr:housenumber": "1",
    "addr:postcode": "08022",
    "addr:street": "Carrer de Torras i Pujalt",
    "amenity": "hospital",
    "contact:email": "info@clinicasagradafamilia.com",
    "contact:fax": "+34 932124050",
    "contact:phone": "+34 932122300",
    "contact:website": "http://csf.com.es/",
    "name": "Cliníca Sagrada Família"   }

btw - you can run a demo-command here at overpass turbo
then you get lots of results....
question: how to store those results in either excel or mysql?
i really love to hear from you
many thanks in advance

A:
"tags": { "addr:city": "Barcelona", "addr:housenumber": "1",
 "addr:postcode": "08022", "addr:street": "Carrer de Torras i Pujalt",
 "amenity": "hospital", "contact:email": "info@clinicasagradafamilia.com",
 "contact:fax": "+34 932124050", "contact:phone": "+34 932122300",
 "contact:website": "http://csf.com.es/", "name": "Cliníca Sagrada Família" }

and:

question: how to use SimpleXMLElement::xpath here?

XPath is for XML. This is text data, looks like structured as JSON. While XPath 3.1 has functions to deal with JSON-structured data, it is not supported by PHP through their XPath processor.

That means that i have to selects all above mentioned elements anywhere in the XML document.

There was only one element, <root>, in your example PHP code. You can select that with the xpath /root but it won't help you further, you will still have the unstructured JSON-as-a-string.
Instead, check out json_decode, it is meant to parse JSON and turn it into a PHP variable. The page shows a couple of examples on how to do just this.


text:
Q: Problems with abstract data type code in C I have this types defined:
#define NAME_LENGTH_LIMIT 25
#define LNULL (-1)
#define MAX 1000

typedef char tParticipantName[NAME_LENGTH_LIMIT];
typedef int tNumVotes;
typedef bool tEUParticipant;

typedef struct tItemL {
    tParticipantName participantName;
    tNumVotes numVotes;
    tEUParticipant EUParticipant;
} tItemL;
typedef int tPosL;
typedef struct tList {
    tItemL data[MAX];
    tPosL lastPos;
} tList;

This code below is creating problems, because it needs to read a character but when I insert one I recived this error-> error: invalid operands to binary == (have 'tItemL' and 'tItemL').
tPosL findItem(tItemL d, tList L) {
    tPosL t;
    if (L.lastPos == LNULL) {
        return LNULL;
    } else {
        t = first(L); //p=0;
        while (t != LNULL && (L.data[t] == d)) { //error in this line
            t = next(t, L);
        }
        if (L.data[t] == d) return t;//error in this line
        else return LNULL;
    }
}

I don't know how to solve the problem

A: if (L.data[t] == d)

Here L.data[t] and d evaluates to structs.
You can't compare two structs for equality with the == operator.
You need to compare each member separately.

A: *

*You should pass the pointer to this big struct, not the struct itself as every time you copy the whole thing when you call the function.

*Do hide standard types behind typedefs.

*Do not hide arrays behind typedefs

typedef struct tItemL {
    char participantName[NAME_LENGTH_LIMIT];
    int numVotes;
    bool EUParticipant;
} tItemL;

typedef int tPosL;
typedef struct tList {
    tItemL data[MAX];
    tPosL lastPos;
} tList;

int compare(const tItemL *i1, const tItemL *i2)
{
    return strcmp(i1 -> participantName, i2 -> participantName) &&
           i1 -> numVotes == i2 -> numVotes &&
           i1 -> EUParticipant && i1 -> EUParticipant;
}

int findItem(tItemL *d, tList *L) {
    int t = -1;
    if (L -> lastPos == LNULL) {
        return LNULL;
    } else {
        t = first(L); //p=0;
        while (t != LNULL && compare(&L -> data[t], d)) { //error in this line
            t = next(t, L);
        }
        if (compare(&L -> data[t], d)) return t;//error in this line
        else return LNULL;
    }
}

You need to change other functions to take pointers not struct


text:
Q: Does the sum of the series $\sum_{n=1}^{\infty}\frac{\sqrt{n+1}-\sqrt n}{n}$ have an analytic expression? Just out of curiosity, I'd like to know whether or not the sum of the series
$$\sum_{n=1}^\infty \frac{\sqrt{n+1}-\sqrt n}{n}$$
has a known analytic expression.
I stumbled across this series while trying to evaluate
$$\int_1^\infty\frac{1}{\lfloor x^2\rfloor}dx$$
The convergence of this integral can be seen by making use of the inequality $\lfloor x\rfloor > x-1$ and the fact that $\coth^{-1}(t)\to 0$ as $t\to\infty$:
\begin{align*}
\int_1^t\frac{1}{\lfloor x^2\rfloor}dx &= \int_\sqrt{1}^\sqrt{2}\frac{1}{\lfloor x^2\rfloor}dx+\int_\sqrt{2}^t\frac{1}{\lfloor x^2\rfloor}dx\\
&< \int_\sqrt{1}^\sqrt{2}\frac{1}{\lfloor x^2\rfloor}dx+\int_\sqrt{2}^t\frac{1}{x^2-1}dx\\
&= \int_\sqrt{1}^\sqrt{2}\frac{1}{1}dx-\int_\sqrt{2}^t\frac{1}{1-x^2}dx\\
&= \sqrt{2}-1-\left[\coth^{-1}(t)-\coth^{-1}\left(\sqrt 2\right)\right]\\
&= \sqrt{2}-1-\coth^{-1}(t)+\coth^{-1}\left(\sqrt 2\right)\\
&\to \sqrt{2}-1+\coth^{-1}\left(\sqrt 2\right)\text{ as }t\to\infty\\
\end{align*}
Since this implies that $\int_1^t 1/\lfloor x^2\rfloor dx$ is strictly increasing ($1/\lfloor x^2\rfloor >0$ for every $x\geq 1$) and bounded above, the integral necessarily converges. By breaking up the integral
$$\int_1^\sqrt{k+1}\frac{1}{\lfloor x^2\rfloor}dx$$
into integrals indexed by the intervals $\left[\sqrt{i},\sqrt{i+1}\right]$ for $i=1,2,3,...,k$ and simplifying the resulting sum, I was able to show that
$$\int_1^{\sqrt{k+1}}\frac{1}{\lfloor x^2\rfloor}dx=\sum_{n=1}^{k} \frac{\sqrt{n+1}-\sqrt n}{n}$$
is true for every $k\geq 0$, which yields
$$\int_1^\infty \frac{1}{\lfloor x^2\rfloor}dx=\sum_{n=1}^\infty\frac{\sqrt{n+1}-\sqrt n}{n}$$
after letting $k\to\infty$. This equality is the main reason why I'm interested in the sum of the aforementioned series.
After some (unsurprisingly) futile attempts to evaluate the integral, I expect there to be no closed-form expression for the sum, which is why I'm open to an analytic expression (gamma function, Bessel functions, Riemann zeta function, etc.). Any help is appreciated.
Edit: after seeing the bounds provided by Markus Scheuer and Jorge, I thought I'd share some of my own.
From the fact that $x-1<\lfloor x\rfloor<x$ is true for every non-integer $x\geq 1$, we can infer that for every integer $k\geq 1$,
$$\int_\sqrt{k+1}^\infty \frac{1}{x^2}dx<\int_\sqrt{k+1}^\infty \frac{1}{\lfloor x^2\rfloor}dx<\int_\sqrt{k+1}^\infty \frac{1}{x^2-1}dx$$
Using
$$\int_{x}^{\infty}\frac{1}{t^2-1}dt=\coth^{-1}(x)$$
and
$$\int_\sqrt{k+1}^\infty\frac{1}{\lfloor x^2\rfloor}dx=\int_1^\infty\frac{1}{\lfloor x^2\rfloor}dx-\int_1^\sqrt{k+1}\frac{1}{\lfloor x^2\rfloor}dx=\sum_{n=1}^\infty \frac{\sqrt{n+1}-\sqrt n}{n}-\sum_{n=1}^{k}\frac{\sqrt{n+1}-\sqrt n}{n}$$
we deduce that
$$\frac{1}{\sqrt{k+1}}+\sum_{n=1}^{k}\frac{\sqrt{n+1}-\sqrt n}{n}<\sum_{n=1}^\infty\frac{\sqrt{n+1}-\sqrt n}{n}<\coth^{-1}\left(\sqrt{k+1}\right)+\sum_{n=1}^{k}\frac{\sqrt{n+1}-\sqrt n}{n}$$

A: Complementing Markus Scheuer answer, an improvement of the lower bound with a nicer closed expresion can be achieved
\begin{align*}
\color{blue}{\sum_{n=1}^{\infty} \frac{\sqrt{n+1}-\sqrt{n}}{n}} > \sum_{n=1}^{\infty} \frac{\sqrt{n+1}-\sqrt{n}}{\sqrt{n}\sqrt{n+1}}
= \sum_{n=1}^{\infty} \left( \frac{1}{\sqrt{n}} - \frac{1}{\sqrt{n+1}} \right)= \color{blue} 1
\end{align*}
The last equality follows because the defined series is a telescoping one with a simple limit

A: Hint: At least we have nice upper and lower bounds for the series.

We obtain by expanding with $\sqrt{n+1}+\sqrt{n}$:
\begin{align*}
\color{blue}{\sum_{n=1}^{\infty} \frac{\sqrt{n+1}-\sqrt{n}}{n}}
&=\sum_{n=1}^{\infty }\frac{1}{n\left(\sqrt{n+1}+\sqrt{n}\right)}\\
&>\sum_{n=1}^{\infty }\frac{1}{(n+1)\left(\sqrt{n+1}+\sqrt{n+1}\right)}\\
&= \frac{1}{2}\sum_{n=1}^{\infty }\frac{1}{(n+1)^{\frac{3}{2}}}\\
&=\frac{1}{2}\sum_{n=2}^\infty \frac{1}{n^{\frac{3}{2}}}\\
&\,\,\color{blue}{=\frac{1}{2}\zeta\left(\frac{3}{2}\right)-\frac{1}{2}}\\
\end{align*}
and on the other hand we have
\begin{align*}
\color{blue}{\sum_{n=1}^{\infty} \frac{\sqrt{n+1}-\sqrt{n}}{n}}
&=\sum_{n=1}^{\infty }\frac{1}{n\left(\sqrt{n+1}+\sqrt{n}\right)}\\
&<\sum_{n=1}^{\infty }\frac{1}{n\left(\sqrt{n}+\sqrt{n}\right)}\\
&= \frac{1}{2}\sum_{n=1}^{\infty }\frac{1}{n^{\frac{3}{2}}}\\
&\,\,\color{blue}{=\frac{1}{2}\zeta\left(\frac{3}{2}\right)}\\
\end{align*}

and since the sequence $\left(\sum_{n=1}^{N} \frac{\sqrt{n+1}-\sqrt{n}}{n}\right)_{1\leq N<\infty}$ of partial sums is strictly increasing and bounded above by $\frac{1}{2}\zeta\left(\frac{3}{2}\right)$ we know the series converges.

A: I do not know but to me it is so nice a candidate for Euler-Maclaurin. I promise no closed form just kind of close evaluation. When I write $\infty$ I mean $\lim\limits_{n \to \infty}$
$$\sum_{n=1}^{\infty}\frac{\sqrt{n+1}-\sqrt{n}}{n}=\int\limits_{1}^{\infty}\frac{\sqrt{x+1}-\sqrt{x}}{x}\, dx + \sqrt{2}-1 + D = 1 - \sqrt{2} + 2 \log(1+\sqrt{2}) + D$$
$$f(x)=\frac{\sqrt{x+1}-\sqrt{x}}{x}$$
$$D=-\sum_{k=1}^{\infty}\frac{B_{2k}}{(2k)!}f^{(2k-1)}(1)$$
Now it is the matter of finding the odd derivatives of $f(x)$ at $1$.
Take $u(x)=\sqrt{x+1}-\sqrt{x}$ and $v(x)=\frac{1}{x}$ and apply
$$(uv)^{(n)}=\sum_{k=0}^n {n \choose k} u^{(n-k)} v^{(k)}$$
since derivatives of $u$ and $v$ are straightforward and you have it
$$u^{(n)}(x)=(-1)^{n+1}\frac{(2n-3)!!}{2^n}(\frac1{(x+1)^{\frac{2n-1}{2}}}-\frac1{x^{\frac{2n-1}{2}}})$$
$$v^{(n)}(x)=(-1)^{n}n!\frac{1}{x^{n+1}}$$
Or
$$u^{(n)}(1)=(-1)^{n+1}\frac{(2n-3)!!}{2^n}(\frac1{2^{\frac{2n-1}{2}}}-1)$$
$$v^{(n)}(1)=(-1)^{n}n!$$
Finally
$$(uv)^{(n)}(1)=(-1)^{n+1}\sum_{k=0}^n {(n)_k}(2n-2k-3)!!(\frac{\sqrt{2}}{2^{2n-2k}}-\frac1{2^{n-k}})$$
$$\sum_{n=1}^{\infty}\frac{\sqrt{n+1}-\sqrt{n}}{n}=1 - \sqrt{2} + 2 \log(1+\sqrt{2})+$$ $$\sum_{p=1}^{\infty}(-1)^{2p+1}\frac{B_{2p}}{(2p)!}\sum_{k=0}^{2p-1} {(2p-1)_k}(4p-2k-5)!!(\frac{\sqrt{2}}{2^{4p-2k-2}}-\frac1{2^{2p-k-1}})$$
Not closed, but still calculable.

A: I'm also doubtful that a closed form exists, but you can get really good approximations using power series and the zeta function.
Note:
$$
\begin{align}
\sum \frac{\sqrt{n+1} - \sqrt{n}}{n}
&= \sum \frac{\sqrt{n} \left ( \sqrt{1 + \frac{1}{n}} - 1 \right )}{n} \\\\
&= \sum \frac{1}{\sqrt{n}} \left ( \frac{1}{2n} - \frac{1}{8n^2} + \ldots \right ) \\\\
&= \frac{1}{2} \sum \frac{1}{n^{3/2}} - \frac{1}{8} \sum \frac{1}{n^{5/2}} + \ldots \\\\
&= \frac{1}{2} \zeta \left ( \frac{3}{2} \right ) - \frac{1}{8} \zeta \left ( \frac{5}{2} \right ) + \ldots
\end{align}
$$
Using the full series for $\sqrt{1+x}$, we find
$$ \sum_{n \geq 1} \frac{\sqrt{n+1} - \sqrt{n}}{n} = \sum_{k \geq 1} \binom{1/2}{k} \zeta \left ( \frac{2k+1}{2} \right ) .$$
Using series expansions for $\zeta \left ( \frac{2k+1}{2} \right )$ (which tends to $1$ as $k \to \infty$) and $\binom{1/2}{k}$ (which decays like $O \left ( k^{-3/2} \right )$) we can find a $k$ which gets us any desired precision.

I hope this helps ^_^


text:
Q: How to use CCRC to get prievous file version? I'm trying to use CCRC API in order to get pervious versions for a specific file and compare with the checkout file.
I know ClearCase can use get command. But how it works in CCRC API?
Does anybody have some example how to retrieve this version without changing the config spec?
Thanks,
Crispy

A: rcleartool has seen new commands with CC8.0.0.3 and CC8.0.4, but is still missing a 'get' command except for the very latest ClearTeam version (8.0.1: see the rcleartool list of commands).
I said as much in "How do I retreive previous or old version in CCRC 7.1.2".
With CCRC 8 (aka ClearTeam Explorer) supporting dynamic view, you can try and use version-extended path (or rcleartool get), but if you are talking about CCRC, you are likely to be with a ClearCase 7.2.x instead of 8.x.
A separate dedicated web view, with a config spec you can change remains for now your safest as in "available right now") option.

I'm writing code to compare my checkout file(some code is modified) with the latest version in clearcase. So I have to get the content of the previous version to compare with my checkout file.

That seems more a job for rcleartool diff -pred
-pre/decessor

Effectively converts the first pname argument into two names:

*

*(1) the predecessor version of pname in the version tree;

*(2) pname itself.

  If pname specifies a checked-out version, the predecessor is the version from which it was checked out.


text:
Q: api rest on CI 3 I am unable to get working API rest to check a license health.
api.php (under controller)
<?php

   require APPPATH . '/libraries/REST_Controller.php';
   use Restserver\Libraries\REST_Controller;

class Inmobiapi extends REST_Controller {

      /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function __construct() {
       parent::__construct();
       $this->load->database();
    }

    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_post()
    {
        $licencia=$this->input->post('licencia');
        if($licencia){
            $data = $this->db->get_where("clientes", ['licencia' => $licencia,'status'=>'Active'])->row_array();
        }else{
            $this->response(NULL, 404);
        }

        $this->response($data, REST_Controller::HTTP_OK);
    }

}

function to check a license, it's a helper.
function verificar_licencia($licencia){
    $curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, 'URL_TO_API');
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $licencia);

    $buffer = curl_exec($curl_handle);
    curl_close($curl_handle);

    $result = json_decode($buffer);

    if(isset($result))
    {
        return $result;
    }

    else
    {
        return FALSE;
    }
}

The return always give me FALSE. The api file is hosted on other domain with different CI3 installation but same configuration on both rest.php
Auth is not enabled so, anybody can access (I am just testing).
Can somebody guide me?
Thanks.

A: I am assuming that you have a value for 'URL_TO_API' that is valid. Check your CURL options. If you're not getting a result from the call and your URL is valid and functional, your curl_setopt calls may have missing or incorrect properties being set (or not set).
For example, in my latest project, my curl options had to be set as follows:
    curl_setopt_array($curl, [
        CURLOPT_URL => 'https://path/to/endpoint'
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_VERBOSE => 1,
        CURLOPT_NOBODY => 1,
        CURLOPT_MAXREDIRS => 1,
        CURLOPT_POST => 1,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_HTTPHEADER => []
    ]);

It may be different for you, depending on:

*

*What you want to achieve with the call.

*What the endpoint requires you to set - refer to your endpoint documentation.


text:
Q: Git won't pull changes from another branch? EDIT:  I should have noted that these are changes which should already have been merged from the "integration" branch.   They somehow did not make it into that merge, and now Git won't add them because it insists the branch is "Already up-to-date".  Arrgh.
Git won't update my branch when I try to merge another branch into it.
This file's got differences in another branch, but when I try to merge that branch, Git tells me "Already up-to-date":
$ git diff --stat integration MyApp/src/main/webapp/WEB-INF/jsp/flow/appInfo.jsp
 .../webapp/WEB-INF/jsp/flow/appInfo.jsp    | 54 ++++------------------
 1 file changed, 10 insertions(+), 44 deletions(-)

$ git merge integration
Already up-to-date.

I'm not really sure how this is possible - can anybody explain how this situation can happen?

A: When you ask git to merge, it decides what to do based on the shape of the history between the branches. Since git is reporting that it's already up to date, integration must be an ancestor of HEAD. You can investigate how this came to be by looking at the output of:
git log --oneline --graph --decorate integration HEAD

If you'd like to replace your local version of that file with the one from the integration branch, you can do a single-file checkout:
git checkout integration -- MyApp/src/main/webapp/WEB-INF/jsp/flow/appInfo.jsp

Alternatively, you can do a patch-checkout to view each diff chunk individually and decided whether or not to apply it:
git checkout -p integration -- MyApp/src/main/webapp/WEB-INF/jsp/flow/appInfo.jsp


text:
Q: Type Into save file path of excel: Object reference not set to an instance of an object I'm getting an UiPath error "Type Into save file path of excel: Object reference not set to an instance of an object"
And would like to know why.

A: I have ran the code "_" + DateTime.Now.ToString("yyyyMMdd") as can be seen below and it provides the correct output.

Based on this it would suggest that the csvName variable/argument is not set.
As a suggestion add an Assign above to initialise the variable


text:
Q: Create a static build of GraphicsMagick with all deps included? I have had a look around Google to see if I can find a static build of GraphicsMagick with all possible filetype support and (ideally) dcraw built in.
Ideally, it would be fully self contained and essentially portable.
I am only really bothered about macOS and Windows (the GraphicsMagick site suggests that the Windows build is already built like that -- though I am unsure about dcraw).
I am a web developer who wants to use this in an Electron app, so I am not sure of the correct terminology , so please forgive any inaccuracies in the ramblings above.

A: For mac I use following script to create a static version with png, jpg and webp included:
# download sources
curl -L http://ftp.icm.edu.pl/pub/unix/graphics/GraphicsMagick/1.3/GraphicsMagick-1.3.31.tar.gz | tar xvz
# zlib needed for png
curl -L http://ftp.icm.edu.pl/pub/unix/graphics/GraphicsMagick/delegates/zlib-1.2.11.tar.gz | tar xvz
curl -L http://ftp.icm.edu.pl/pub/unix/graphics/GraphicsMagick/delegates/libpng-1.6.28.tar.gz | tar xvz
curl -L http://ftp.icm.edu.pl/pub/unix/graphics/GraphicsMagick/delegates/libwebp-1.0.0.tar.gz | tar xvz
curl -L http://ftp.icm.edu.pl/pub/unix/graphics/GraphicsMagick/delegates/jpegsrc.v6b2.tar.gz | tar xvz

export mydir=$(pwd)
export CPPFLAGS="-I$mydir/include"
export LDFLAGS="-L$mydir/lib"

# use `less zlib-<TAB>/configure` to discover configure options
(cd zlib-*           && ./configure --static                             --prefix=$mydir && make install)
(cd libpng-*         && ./configure --disable-shared                     --prefix=$mydir && make install)
(cd libwebp-*        && ./configure --disable-shared --enable-libwebpmux --prefix=$mydir && make install)
(cd jpeg-*           && ./configure --disable-shared                     --prefix=$mydir && make install)
(cd GraphicsMagick-* && ./configure --disable-installed                  --prefix=$mydir && make install)
./bin/gm version
ldd ./bin/gm

# test
mkdir test && cd test
cp ../jpeg-6b2/testimg.bmp ./test.bmp
../bin/gm convert test.bmp jpg.jpg
../bin/gm convert jpg.jpg jpg.bmp
../bin/gm convert test.bmp png.png
../bin/gm convert png.png png.bmp
../bin/gm convert test.bmp webp.webp
../bin/gm convert webp.webp webp.bmp

You could use that as a start for including further libraries if needed. My use case was also to include it in electron. After trying to crosscompile a static Windows version I came to the conclusion that for the Windows version it would be less maintenance-cost to use the officially provided precompiled multi-file version.


text:
Q: Python gives me an error when trying to get anything other than first or last two elements from list I'm trying to extract some info out of a .gtf file, which is basically like a type of database where items are tab delimited(or so i'm told). I've written the following simple code to break up each line of the file into a list so each item in the list is one of the "columns" (and also print out the comment lines, but ignore that)
for line in file:
    if line.startswith('#'):
        print (line)
line = line.rstrip('\n')
field = line.split()

Pretty simple code, and when I put in a print(field) it prints out many lines like this one with varying data
['1', 'havana', 'exon', '7962767', '7962875', '.', '+', '.', 'gene_id', '"ENSG00000116288";', 'gene_version', '"12";', 'transcript_id', '"ENST00000497113";', 'transcript_version', '"1";', 'exon_number', '"1";', 'gene_name', '"PARK7";', 'gene_source', '"ensembl_havana";', 'gene_biotype', '"protein_coding";', 'transcript_name', '"PARK7-210";', 'transcript_source', '"havana";', 'transcript_biotype', '"processed_transcript";', 'exon_id', '"ENSE00001935602";', 'exon_version', '"1";', 'transcript_support_level', '"3";']

I figure it looks like a list right. So I go to test it with print()
print(field[0])
print(field[1])
print(field[-1])
print(field[-2])

and those give me this
1
havana
"5";
transcript_support_level

etc.
So it looks like a list, and acts like a list, but the data I want is in the third column so I just change the code to field[2] and it gives me this
   print(field[2])
IndexError: list index out of range

I tried putting in different numbers but it's all the same error, and I just really can't figure out why it would let me pull up the first two and last two items in the list, but nothing else? I've tried a lot of things but i'm really just stumped as to what to do here. I can't continue with my code unless I'm able to reference the third column/item in these lists.

A: Well I did find a work-around for it with the following code
for line in file:
    if line.startswith('#'):
        print (line)
    line = line.rstrip('\n')
    field = line.split("\t")
    for item in field[2:3:1]:
        print(item)

It's pretty simple and I probably should have thought of it sooner, but it lets me print out all the items in the third column, so it works but I feel like I just wrote the same thing in different words. Still confused as to why it would only work in a limited fashion the other way though...


text:
Q: Странный ответ от сервера клиент на Java.
Делаю запрос на сервер через TCP и считываю ответ в массв байтов byte[]. Он приходит в странном виде. Байты чередуются [байт ответа, '\u0000', байт ответа, '\u0000' ...]
Аналогичный php код принимает ответ корректно.
Даже ошибки выдает в таком виде:
T a k e   t o o   l o n g   t o   l o g   i n

Почему такой ответ получается?

class SampleClient{
    public static void main(String args[]){
    try{
        String host = "91.121.133.113";
        int port =25565;

        Socket s = new Socket(host, port);

        byte b1 =(byte) 0xfe01;
        byte b2 =(byte) 0xfd;
        byte b3 =(byte) (9);
        byte b4 =(byte) 73;
        byte b5 =(byte) port;
        byte [] bytes = {b1,b2,b3,b4,b5};

        s.getOutputStream().write(bytes);

        // читаем ответ
        byte buf[] = new byte[2*1024];
        int r = s.getInputStream().read(buf);
        String data = new String(buf, 0, r);

        System.out.println("Исходная строка: "+ new String (buf));
    catch(Exception e){
        System.out.println("init error: "+e);
    }
}


text:
Q: Menu Sprite Navigation this is the mockup for the site I need to code Mockup
my menu sprite is not working properly, here you can see it Website
Here is the HTML HTML file
and here the CSS CSS file

A: What is the reason of using sprite for this menu, what about css solution?