text:
Q: Parsing xml in python to get all child elements I have parsed an XML file to get all its elements. I am getting the following output
[<Element '{urn:mitel:params:xml:ns:yang:vld}vld-list' at 0x0000000003059188>, <Element '{urn:mitel:params:xml:ns:yang:vld}vl-id' at 0x00000000030689F8>, <Element '{urn:mitel:params:xml:ns:yang:vld}descriptor-version' at 0x0000000003068A48>]

I need to select the value between } and ' only for each element of the list.
This is my Code till now :
import xml.etree.ElementTree as ET
tree = ET.parse('UMR_VLD01_OAM_V6-Provider_eth0.xml')
root = tree.getroot()

# all items
print('\nAll item data:')
for elem in root:
    all_descendants = list(elem.iter())
    print(all_descendants)

How  can i achieve this ?

A: The text in {} is the namespace part of the qualified name (QName) of the XML element. AFAIK there is no method in ElementTree to return only the local name. So, you have to either

*

*extract the local part of the name with string handling, as already proposed in a comment to your question,

*use lxml.etree instead of xml.etree.ElementTree and apply xpath('local-name()') on each element,

*or provide an XML source without namespace. You can strip the namespace with XSLT.

So, given this XML input:
<?xml version="1.0" encoding="UTF-8"?>
<foo xmlns="urn:mitel:params:xml:ns:yang:vld">
    <bar>
        <baz x="1"/>
        <yet>
            <more>
                <nested/>
            </more>
        </yet>
    </bar>
    <bar/>
</foo>

You can print a list of the local names only with this variation of your program:
import xml.etree.ElementTree as ET
tree = ET.parse('UMR_VLD01_OAM_V6-Provider_eth0.xml')
root = tree.getroot()

# all items
print('\nAll item data:')
for elem in root:
    all_descendants = [e.tag.split('}', 1)[1] for e in elem.iter()]
    print(all_descendants)

Output:
['bar', 'baz', 'yet', 'more', 'nested']
['bar']

The version with lxml.etree and xpath('local-name()')  looks like this:
import lxml.etree as ET
tree = ET.parse('UMR_VLD01_OAM_V6-Provider_eth0.xml')
root = tree.getroot()

# all items
print('\nAll item data:')
for elem in root:
    all_descendants = [e.xpath('local-name()') for e in elem.iter()]
    print(all_descendants)

The output is the same as with the string handling version.

For stripping the namespace completely from your input, you can apply this XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

Then your original program outputs:
[<Element 'bar' at 0x04583B40>, <Element 'baz' at 0x04583B70>, <Element 'yet' at 0x04583BD0>, <Element 'more' at 0x04583C30>, <Element 'nested' at 0x04583C90>]
[<Element 'bar' at 0x04583CC0>]

Now the elements themselves do not bear a namespace. So, you don't have to strip it anymore.
You can apply the XSLT with with xsltproc, then you don't need to change your program. Alternatively, you can apply XSLT in python, but this also requires you to use lxml.etree. So, the last variation of your program looks like this:
import lxml.etree as ET

tree = ET.parse('UMR_VLD01_OAM_V6-Provider_eth0.xml')
xslt = ET.parse('stripns.xslt')
transform = ET.XSLT(xslt)
tree = transform(tree)

root = tree.getroot()
# all items
print('\nAll item data:')
for elem in root:
    all_descendants = list(elem.iter())
    print(all_descendants)


text:
Q: Doing math in C# generic method (known with unknown) Bonjorno, people. Could you please explain me how to perform operations inside a generic method. I want a random array of different unsigned integers. IDE doesn't allow me to multiply a Double (and others) with a generic struct. Typecasting doesn't work in any way I try.
Maybe I'd better just stop "designing a bicycle" and call from the generic method one of several method for each integer type?
public static T[] getRandArray<T>(int amount) where T: struct
{
    FieldInfo maxValueField =
        typeof(T).GetField(
            "MaxValue",
            BindingFlags.Public | BindingFlags.Static
        );

    T maxValueOfT = (T)maxValueField.GetValue(null);

    Random randNum = new Random();

    T[] array = new T[amount];

    for (int i = 0; i < amount; i++)
    {
        array[i] = (T)(randNum.NextDouble()) * maxValueOfT;
    }

    return array;
}

A: It will not work with generics.

*

*If you need only an uint[] as a result of your method then replace generic type with that.

*If you need not only uint[] but an array of any other type, e.g. int[] then you have to create an overload for your method.

Unfortunately there is no constraint you could give for the generic type that would allow you to do some math with them.
Btw. I would suggest that you create an instance of Random as a static field in your static class and then use it in the method(s).

A: Only generic methods should be made generic. The only constraint defined there is T : struct. Suppose I define the following:
public struct Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

I can supply a Point to getRandArray, but how do you use it?
Rather, choose a type that meets your needs. If the interface you're supplying is appropriate, you can often still leverage implicit conversions to achieve your goal

redpajama_set_name: RedPajamaStackExchange


text:
Q: Not receiving notification click in service I try to run a background service and display a persistent notification. When the notification is clicked, the service (providing NanoHTTPD webserver) should be stopped.
The onReceive never seems to be called when tapping the notification. "Stop" is not logged. (while "Start" is.
My code below is roughly based on https://stackoverflow.com/a/19476094/288568.
public class Webserver extends IntentService {

private final String TAG = "MyAMWebserver";

public static final int PORT = 1234;

public static Boolean isRunning = false;

private MyWebserver server;
private ContentManager contentManager = new ContentManager(this);

private NotificationManager notificationManger;

public Webserver() {
    super("webserver-service");
}

//We need to declare the receiver with onReceive function as below
protected BroadcastReceiver stopServiceReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Stop");
        unregisterReceiver(stopServiceReceiver);
        stopSelf();
        isRunning = false;
        notificationManger.cancel(01);
    }
};

@Override
public void onCreate() {
    super.onCreate(); // if you override onCreate(), make sure to call super().
    // If a Context object is needed, call getApplicationContext() here.

    try {
        server = new MyWebserver();
        isRunning = true;

        IntentFilter intentFilter = new IntentFilter("myMapWebserver");
        Intent intent = new Intent("myMapWebserver");
        registerReceiver(stopServiceReceiver, intentFilter);
        PendingIntent pendingIntent

= PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(getApplicationContext())
                .setContentTitle("Webserver Running").setContentText("Click here to Stop Webserver").setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .getNotification();

        notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManger.notify(01, notification);

        Log.d(TAG, "Started");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

@Override
protected void onHandleIntent(Intent intent) {
    // This describes what will happen when service is triggered
}

public class MyWebserver extends NanoHTTPD {

....


text:
Q: What is concept of degree at B-spline curve? Thanks to you attention to my question.
My question is what is concept of degree at B-spline curve as you as seen from the title.
In the book that I am studying, only 'Degree' is given as a factor that changes the shape of the curve.
I searched on the internet, but the results were not good.
If you know B-spline curve's degree concept, please answer that concept to me.
Thanks for reading.

A: A b-spline curve is basically a piecewise continuous polynomial curve. The degree is the degree of the polynomial. Besides degree, you also need control points and knot vector in order to fully define a b-spline curve.


text:
Q: How to call a Python script through wordpress? I'm developing a plugin for wordpress where the user will be able to upload a file and have it analyzed. I have a Python script ready for the analysis, but I'm not sure on how to run it on PHP while passing arguments (the file's path). It would be optimal to have a solution that is also able to read a "print" from the Python script as output.
So far, I have something that looks like:
$handle = popen( __DIR__ . '/' . $data['file'], 'r' );
$read = '';

while ( ! feof( $handle ) )
{
    $read .= fread( $handle, 2096 );
}

pclose( $handle );

return $read;

But "popen" does not allow me to pass arguments. Any clues on the best way to do this?

A: You can call Python script using PHP exec or shell_exec() functions, for example, you have a python file hello.py then you can call the file using below code
    exec("python hello.py",$output);
    print_r($output); //display the output

A: <?php # -*- coding: utf-8 -*-
/* Plugin Name: Python embedded */

add_shortcode( 'python', 'embed_python' );

function embed_python( $attributes )
{
    $data = shortcode_atts(
        [
            'file' => 'hello.py'
        ],
        $attributes
    );

    $handle = popen( __DIR__ . '/' . $data['file'], 'r' );
    $read = '';

    while ( ! feof( $handle ) )
    {
        $read .= fread( $handle, 2096 );
    }

    pclose( $handle );

    return $read;
}

A: Yes, you can read & write Python file by using the function popen(). This function also works for other languages.
$handle = popen( __DIR__ . '/' . $file_name, 'r' );
$read = '';
while ( ! feof( $handle ) )
 {
   $read .= fread( $handle, 2096 );
 }
pclose( $handle );

Reference


text:
Q: Junk values in dynamic array Could somebody help me figure why I am getting junk values in my array? My code is:
FILE *fp;
fp = fopen("input.txt", "r");

char buffer[5000];
int size = 0;
char *ptr;
char **fileArrayPTR;

fileArrayPTR = malloc(sizeof(char*));

while (fgets(buffer, 5001, fp) != NULL) {
    fileArrayPTR[size] = malloc(strlen(buffer) + 1);
    strcpy(fileArrayPTR[size], buffer);
    for (int p = 0; p < 5001; p++) {
        if (fileArrayPTR[size][p] == '\n') {
            fileArrayPTR[size][p] = '\0';
            break;
        }
    }
    //printf("%s\n",fileArrayPTR[size]);
    size++;
}
for (int x = 0; x < size; x++) {
    printf("%s\n", fileArrayPTR[x]);
}

If I uncomment the the printf statement in front of the size++, I get the right result, but when I take that out and try the bottom part of the code it doesn't work. It works for fileArrayPTR[16] or higher but not from 0-15. Also if I was to return fileArrayPTR to main, how could I also return the size as well?

A: You should reallocate the string array to grow it as more lines are read:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **getlines(int *sizep) {
    FILE *fp;
    char buffer[5001];
    int size = 0;
    char **fileArrayPTR = NULL;

    fp = fopen("input.txt", "r");
    if (fp == NULL) {
        *sizep = -1;
        return NULL;
    }

    while (fgets(buffer, 5001, fp) != NULL) {
        fileArrayPTR = realloc(fileArrayPTR, sizeof(*fileArrayPTR) * (size + 1));
        fileArrayPTR[size] = strdup(buffer);
        for (int p = 0; p < 5001; p++) {
            if (fileArrayPTR[size][p] == '\n') {
                fileArrayPTR[size][p] = '\0';
                break;
            }
        }
        //printf("%s\n", fileArrayPTR[size]);
        size++;
    }
    *sizep = size;
    return fileArrayPTR;
}

int main(void) {
    int size;
    char **array = getlines(&size);
    for (int x = 0; x < size; x++) {
        printf("%s\n", array[x]);
    }
    return 0;
}

Note that buffer should be defined with a size of 5001 for consistency with the rest of the code.
You can return the size to main by setting a variable to which you pass a pointer, as shown above.


text:
Q: Text in a graph in TikZ I have the following code.
\begin{tikzpicture}
 [auto,
 vertex/.style={circle,draw=black!100,fill=black!100,thick,inner sep=0pt,minimum size=1mm}]
\node (v1) at ( 1,1) [vertex,label=left:$v_1$] {};
\node (v2) at ( 0,0) [vertex,label=left:$v_2$] {};
\node (v3) at ( 2,0) [vertex,label=right:$v_3$] {};
\draw [-] (v1) to (v2);
\draw [-] (v2) to (v3);
\draw [-] (v1) to (v3);
\draw [-] [loop below] (v1) to (v1);
\end{tikzpicture}

Now this draws my graph nicely with three vertices. My problem is that I want to give names to the edges v_1v_2,v_2v_3,v_1v_3,v_1v_1 as e_1,e_2,e_3,e_4 respectively. These names should be positioned near the edges. Moreover I want TikZ to place the names for these edges automatically without disturbing each other and without me specifying the positions. What is the best way to accomplish this? I think auto is used for this but am not sure how.

A: Some thing like this?
\documentclass[tikz]{standalone}
\usetikzlibrary{automata}
\begin{document}
  \begin{tikzpicture}[auto, vertex/.style={circle,draw=black!100,fill=black!100, thick,
                inner sep=0pt,minimum size=1mm}]
\node (v1) at ( 1,1) [vertex,label=left:$v_1$] {};
\node (v2) at ( 0,0) [vertex,label=left:$v_2$] {};
\node (v3) at ( 2,0) [vertex,label=right:$v_3$] {};
\draw [-] (v1) --node[inner sep=0pt,swap]{$e_1$} (v2);
\draw [-] (v2) --node[inner sep=2pt,swap]{$e_2$} (v3);
\draw [-] (v1) --node[inner sep=0pt]{$e_3$} (v3);
\draw [-] [loop below] (v1) to node[inner sep=0pt]{$e_4$} (v1);
\end{tikzpicture}
\end{document}


text:
Q: Is there a formal proof of this basic integral property? This has really been bothering me because everywhere I have looked the answer has been "A proof has been omitted because the theorem is very intuitive" or "Proofs are very complicated and not worth showing", so I was wondering if there exists a formal proof of the basic integral property:
$$\int_a^bf(x)dx=\int_a^cf(x)dx + \int_c^bf(x)dx$$
This property is absolutely crucial to calculus and it bothers me that I haven't seen any formal proof using the definition of an integral. Does anyone know of a proof?
Edit: This is all assuming that the function is continuous on the intervals [a,b], [b,c] and [a,c]

A: At an elementary level, it is better to consider continuous functions and define the integral as a limit of sequences of left (or right) Riemann sums corresponding to regular partitions.
Let $f$ be a function continuous on $[a,b]$.
A partition of $[a,b]\,$ is a set of points $P=\{x_0,x_1,\dots,x_n\}$ with $$a=x_0<x_1<\dots<x_n=b$$ The norm of $P$ is the number $$\|P\|=\max_{1\le i\le n}\,(x_i-x_{i-1})$$ If the points are equidistant, $P$ is the n-regular partition and is denoted by $P_n\,$, so $$\|P_n\|=\frac {b-a}n$$ The number $$L(f,P)=\sum_{i=1}^n f(x_{i-1})(x_i-x_{i-1})$$ is said the left sum corresponding to $P$.
(here $L$ is for Left not for Low)
Now the comparison of two left sums.
Comparison theorem: any two left sums differ arbitrarily little from each other if the norms of the partitions to which they correspond are sufficiently small.
Formally:
For every $\varepsilon>0$ there exists $\delta>0$ such that, if $\,\|P\|<\delta\,$ and $\,\|P'\|<\delta$, then $$|L(f,P)-L(f,P')|<\varepsilon$$
($P'=\{x'_0,x'_1,\dots,x'_m\}$)
The proof is based on the (uniform) continuity of $f$.
In fact, if $$K_{ij}=[x_{i-1},x_i]\cap[x'_{j-1},x'_j]$$ then $$L(f,P)-L(f,P')=\sum_{i=1}^n \sum_{j=1}^m \,[f(x_{i-1})-f(x'_{j-1})]\,m(K_{ij})$$ where $m(K_{ij})$ is the length of the interval $K_{ij}$.
(really $K_{ij}$ can degenerate in one point or be the empty set)
Now the definition of definite integral.
The comparison theorem assures that the sequence $$S_n=L(f,P_n)$$is Cauchy so it has a limit denoted by $$\int_a^b f$$ In fact it is enough to choose $N$ such that $$\frac {b-a}N<\delta$$ to have $$|L(f,P_m)-L(,f,P_n)|<\varepsilon$$ for every $m,n \ge N$.
Finally your question.
If $a<c<b$, one also has $$S'_n=L(f,P'_n) \to \int_a^c f$$ and $$S''_n=L(f,P''_n) \to \int_c^b f$$ where $P'_n$ and $P''_n$ are the n-regular partitions of $[a,c]$ and $[c,b]$ respectively.
Note that $S'_n+S''_n$ is the left sum corresponding to $P'_n \cup P''_n$, a partition of $[a,b]$ that is not regular unless $c$ is the midpoint of $[a,b]\;$ (so it is important that the comparison theorem is valid for any partition).
Then one gets $$|S_n- S'_n-S''_n|<\varepsilon$$ for every $n\ge N$.
In fact $\,\|P'_n \cup P''_n\|<\|P_n\|<\delta\,$ for every $n\ge N$.
So one has $$|S_n- S'_n-S''_n| \to \left|\int_a^b f-\int_a^c f-\int_c^b f \right|\le \varepsilon$$ The arbitrariness of $\varepsilon$ gives the result.


text:
Q: Printing out asterisks depending on each digit of a number My program is supposed to print out asterisks depending on the digit of the number. This is what's supposed to happen:

*

*Input: 24 || Output:  2 ** 4 ****

*Input: 24000 || Output:  2 ** 4 **** 0 0 0

This is my code:
void histogram (){
int nNum, nCount, nMult, nTemp=-1, n;
printf("Please input a value: ");
scanf("%d", &nNum);
n=nNum;
do{
    nCount = 0;
    nMult = 1;
    while(n>0){
        n /= 10;
        nCount++;
    }
    while(nCount>1){
        nMult *= 10;
        nCount--;
    }
    nTemp = nNum / nMult;
    printf("%d ", nTemp);
    do{
        printf("*");nTemp--;
    }while(nTemp>0);
    printf("\n");
    nNum%=nMult;
    n = nNum;
}while(n>0);}

My code doesn't print out the trailing zeros and I'm hoping you guys can help me with this. Thanks!

A: It is better to make such a function recursive. It allows to keep trailing zeroes.
Here is a demonstrative program
#include <stdio.h>

void histogram( unsigned int n )
{
    const unsigned int Base = 10;
    const char c = '*';

    unsigned int digit = n % Base;

    if ( n /= Base ) histogram( n );

    printf( "%u ", digit );
    for ( ; digit != 0; --digit ) printf( "%c ", c );
}

int main(void)
{
    while ( 1 )
    {
        unsigned int n;

        printf( "Please input a non-negative value (0 - exit): " );

        if ( scanf( "%u", &n ) != 1 || n == 0 ) break;

        printf( "\n" );

        histogram( n );

        printf( "\n" );
    }

    return 0;
}

The program output might look the following way
Please input a non-negative value (0 - exit): 123456789

1 * 2 * * 3 * * * 4 * * * * 5 * * * * * 6 * * * * * * 7 * * * * * * * 8 * * * * * * * * 9 * * * * * * * * *
Please input a non-negative value (0 - exit): 24000

2 * * 4 * * * * 0 0 0
Please input a non-negative value (0 - exit): 0

As for your approach then you have to count trailing zeroes when you are reversing the number.

A: After the while loop, you should just check nmult value, whose value is a power of 10. If 10, print one zero. If 100, print two zeros, etc... with a loop dividing by 10 on each iteration, like this one:
while(nmult>1){
    nmult /= 10;
    printf(" 0 ");
}


text:
Q: Visual Studio Code include file not found in include directory (Windows 10) I am trying to get intellisense in Visual Studio Code. I downloaded the the C/C++ extension from the marketplace: https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools and also installed MinGW with the packages mingw32-base and mingw32-gcc-c++. I added the MinGW bin folder to Path in my Environment variables.
When I add any include statement in my .c file, such as #include <stdio.h>, Visual Studio Code says:
Include file not found in include directory

Am I not configuring correctly? How can I get intellisense for C/C++?

A: As an expansion to wbmrcb's answer, I found header files under Windows Kits directory:
C:\Program Files (x86)\Windows Kits\10\Include\10.0.10586.0\ucrt

A: On Fedora linux I added the following path where all my c header files lives.

/usr/include/**

to myc_cpp_properties.json file.
{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/**"
            ],
            ...
        }
    ],
    "version": 4
}

A: *

*First, make sure to create a c_cpp_properties.json file in your .vscode folder
Hint: Use the Command Palette (Ctrl+Shift+P) and type C/Cpp: Edit Configurations

*Add include paths like this:
{
  "configurations": [
    {
      "name": "Win32",
      "includePath": [
        "path_to_your/MinGW/lib/gcc/mingw32/4.8.1/include/c++"
      ],
      "browse": {
        "limitSymbolsToIncludedHeaders": true,
        "databaseFilename": ""
      }
    }
  ]
}

A: I am using MinGW 8.1.0 and the C/C++ extension from microsoft, this worked for me -
{
"configurations": [
    {
        "name": "Win32",
        "includePath": [
            "C:/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++",
            "C:/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/tr1",
            "C:/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/i686-w64-mingw32"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "compilerPath": "C:/mingw32/bin/gcc.exe",
        "cStandard": "c17",
        "cppStandard": "c++17",
        "intelliSenseMode": "windows-gcc-x64"
    }
],
"version": 4
}


text:
Q: txt file doesn't read from start after first loop run I've two lists, backedup.txt and current.txt.
backedup.txt contains these lines;
Chris_Jamaica.mp3
Chris_Take_Me.mp3
Chris_You_Are_Me.mp3
Chris_Dance_With_Me.mp3
Chris_Yesterday.mp3

current.txt contains these lines;
Chris_You_Are_Me.mp3
Chris_Dance_With_Me.mp3
Chris_Take_Me.mp3

I want to compare item by item in two text files, one item from backedup.txt, compare with all lines in current.txt, then print out if found.
This is the code i have
/* compare backedup list with the current list */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *current_list=fopen("/current.txt","r");
    FILE *backedup_list=fopen("/backedup.txt","r");

    char current_list_song[40],backedup_list_song[40];

    for(int i=1; i<=5; i++) {

        fscanf(backedup_list,"%s",backedup_list_song);

        for(int j=1; j<=3; j++) {
            fscanf(current_list,"%s",current_list_song);
            if(strcmp(backedup_list_song,current_list_song) != 0) {
                printf("%-30s - %s\n",backedup_list_song, current_list_song);
            }
            else{
                printf("%-30s - Found!\n",backedup_list_song);
                break;
            }
        }
    }

    fclose(current_list);
    fclose(backedup_list);
    return 0;
}

This is the result of running that code

Checking the first line in backedup.txt with the lines in current.txt works, but from the second line in backedup.txt onwards, the current.txt doesn't start checking from the beginning, it just gets stuck on the last line or continues if there are more lines.
I want to be able to check the whole current.txt, with every line from backedup.txt, always beginning at the start of current.txt

A: You need to add this before the second for loop:
fseek(current_list, 0, SEEK_SET);

so you can start over from the beginning.


text:
Q: Django URL, pass parameters in URL I want to create url like:
/api/foodfeeds/?keywords=BURGER,teste&mood=happy&location=2323,7767.323&price=2
urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^api/foodfeed/(?P<keywords>[0-9.a-z, ]+)/(?P<mood>[0-9.a-z, ]+)/(?P<location>[0-9]+)/(?P<price>[0-9]+)/$', backend_views.FoodfeedList.as_view()),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

views.py
class FoodfeedList(APIView):
    # permission_classes = (permissions.IsAuthenticated,)
    def get(self,request,keywords,mood,location,price):
        print(request.GET['keywords'])

A: As @Umair said, you're passing those keys as URL query parameters, so you don't have to mention it in URLPATTERNS

In your case, to get the data you're passing through the URL, follow the below code snippet
#urls.py
urlpatterns = [
                  path('admin/', admin.site.urls),
                  url(r'^api/foodfeed/', backend_views.FoodfeedList.as_view()),
              ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

#views.py
class FoodfeedList(APIView):
    # permission_classes = (permissions.IsAuthenticated,)
    def get(self, request):
        print(request.GET) # print all url params
        print(request.GET['keywords'])
        print(request.GET['mood'])
        # etc

A: Those keywords, mood, location, etc are query params you should not include those in url, rather you should access them via request.query_params
Reference : http://www.django-rest-framework.org/api-guide/requests/#query_params


text:
Q: how to convert current screen to landscape mode in phoneGap We are developing  phone-gap application.We have 4 pages like one.html,two.html,three.html,four.html.In this one(two.html) of the HTML file need to be landscape mode automatically.
Please guide to us.We are new to this.

A: Add this script first
<script type="text/javascript" src="cordova.js"></script>

Then inside another script tag
<script>
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        var so = cordova.plugins.screenorientation;
        so.setOrientation(so.Orientation.LANDSCAPE);
    }
</script>

A: You can use the Screen Orientation PhoneGap Plugin for Android
Following is the link.
https://github.com/their/pg-plugin-screen-orientation


text:
Q: How to show custom events to a Kronolith calendar I want to show events from an external source in the Kronolith calendar views. I don't want to do this by exporting the events to iCal and then showing them as an external calendar. The events are grouped in multiple calendars, the user should be able to disable/enable these calendars.

A: You can do this by implementing the listTimeObjects and listTimeObjectCategories API calls. Nag (task list) and Whups (ticket tracking) do it this way. If you are using the Git version, you can use TimeObjects, which wraps everything up in a nice class.
Kronolith calls these functions in initialize() (when filling $all_external_calendars) and listEvents(). It searches all APIs for this function, so you can register it with your own prefix.
timeObject is a generic name for "things that can be shown on a calendar", like events, task due dates, ... A timeObjectCategory is a group of timeObjects, which can be enabled or disabled in a group by the user. (In the default layout: using the panel in the upper-right corner of the calendar view, "Calendars".)
Your implementation for listTimeObjectCategories should return an array, with a category id as the key, and the user-visible name as the value. The category id's are also shown at the bottom of the calendar, and the user can define colors for them.
listTimeObjects is called with the currently selected categories (an array of id's), and a start and end date. These dates might already be Horde_Date objects (to be sure, convert them again: $start = new Horde_Date($start)).
You should return an array of timeObjects that belong to these categories and fall in the specified time range. The keys are event id's, the values are arrays with values for the following keys:

*

*id

*title

*description

*start (Horde_Date or timestamp)

*end (Horde_Date or timestamp)

*category (Category id)

*params
If you register the show API call, this will be used for creating the link to the timeObject detail.


text:
Q: Result of CONCAT function not showing the exact required result in first row? Here is my code:
SELECT
   usertype, CONCAT(start_station_name, 'to', end_station_name) AS Route, COUNT(*) as num_trips,
   ROUND(AVG(CAST(tripduration as int64)/60),2) AS Duration
FROM `bigquery-public-data.new_york_citibike.citibike_trips`
GROUP BY start_station_name, end_station_name, usertype
ORDER BY num_trips DESC
Limit 10

the result is screenshot is shown.


text:
Q: Is there validate-able way to use HTML label and input elements and the input not having an id? I'm using Jquery Mobile for an application, which has a login popup on every page. The problem is, Jquery Mobile will always have at least 2 pages in the DOM, so I will have two popups and login forms in the DOm, forcing me to find a way to avoid duplicate id-attributes.
I worked around this by omitting the id attributes on the login form inputs, so I'm doing this:
 <label for="email" class="inFieldLabel">#tx_email#</label>
 <input autocomplete="off" type="email" name="email" value="#XMLFormat( lostPass.email )#" class="required">

Which works fine visually, but produces a validation error, because:
 The for attribute of the label element must refer to a form control.

Question:
Is there a way to pass validation without using an id attribute? What would be workarounds?
Note: I can't use a global login popup, because this is not supported by Jquery Mobile at the moment, so I'm stuck with a popup on every page.
Thanks for insights!

A: Assuming 2 things: that you aren't going to be using IDs to style your form and you have a FORM tag around each  popup. This code will append a random number to the IDs/FORs of the elements of your form. You'll likely need to pass this number to your validate routine as well.
jQuery("FORM").each(function()
{
  var randomNum = Math.random()*1000;
  var jForm = jQuery(this);
  jForm.find("INPUT").each(function()
  {
    this.id+=randomNum;
  });
  jForm.find("LABEL").each(function()
  {
    jQuery(this).attr("for",jQuery(this).attr("for")+randomNum);
  });
});

...

validateForm(form, randomNum);

That's one way to keep the IDs on your forms unique.
I guess I'm assuming you're using the Validate plugin as well. If it's any help, you can use multiple non-unique IDs for your forms/elements as long as you pass Validate unique selectors like "#page-1 #popup-form #myInput" or "#page-2 #popup-form #myInput".
More edits:
Wait, are you looking for this? You can reference a form and it's controls via name instead of id using the forms object.
<form name="formNameAttribute">
  <input name="inputNameAttribute" value="some value" />
</form>

<script>
var inputValue=document.forms["formNameAttribute"]["inputNameAttribute"].value;
</script>

A: Put the form control the label applies to inside the label.
<label> text <input> </label>


text:
Q: Cannot call a class as a function in nodejs express Hi I am trying to follow ES6 syntax to create a middleware of my node.js application.
index.js
export default class Middleware {
  constructor() {
    //do nothing
  }

  fun1 = (req, res, next) => {
    console.log("------------------------------------");
    console.log("AAa");
    console.log("------------------------------------");
    next();
  };

  fun2 = (req, res, next) => {
    console.log("------------------------------------");
    console.log("AAa");
    console.log("------------------------------------");
    next();
  };
}

app.js
import Middleware from ".index";
app.use(Middleware);

I am getting an error Cannot call a class as a function. Does anyone know what is wrong?

A: Express app#use expects a function with the following signature:
function(req, res, next) {

To make it work, you need to do:

*

*Create an instance of Middleware class.

*Register middleware for each function in the class.

Example:
let middleware = new Middleware();

app.use(middleware.func1);
app.use(middleware.func2);


text:
Q: iTextSharp EXCEL output I am using the following code to output data from a number of tables in my database to an excel document.
Protected void btnExcelExport_Click(object sender, EventArgs e)
{

string strQuery = "SELECT s.Story, s.StoryCategoryID, CONVERT(VARCHAR(10),
s.CreationDate, 103) AS CreationDate, m.CompanyRole, af.Name FROM Story s INNER JOIN
ProjectIterationMember pm ON pm.ProjectIterationMemberID = s.ProjectIterationMemberID
INNER JOIN Iterations i ON i.ProjectIterationID = pm.ProjectIterationID INNER JOIN
Member m ON m.MemberID = pm.MemberID INNER JOIN ProjectStoryFactors psf ON psf.StoryID =
s.StoryID INNER JOIN AgileFactors af ON af.AgileFactorID = psf.AgileFactorID WHERE
i.ProjectID = '" + proj_id + "'";

SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);

GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=RetroCloud" +
DateTime.Now.Ticks + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

for (int i = 0; i < GridView1.Rows.Count; i++)
{

   GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);

string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

The output is as follows:
Story | StoryCategoryID | CreationDate | CompanyRole | Name

negative iii | 1 | 21/02/2011 | Business Analyst | Project Duration
negative iii | 1 | 21/02/2011 | Business Analyst | Team Size
negative iii | 1 | 21/02/2011 | Business Analyst | Process
negative ccc | 1 | 22/02/2011 | Admin | Workspace Layout
negative ccc | 1 | 22/02/2011 | Admin | Organisational and Reporting Structure
negative ccc | 1 | 22/02/2011 | Admin | Process

What I would like to do is 3 things. Many thanks for your help!
1) Change the header names which are clearly coming from the database fields (ie. from StoryCategoryID to Story Type),
2) For StoryCategoryID, if 1 is retrieved - display 'Negative' and if 0 is retrieved - display 'Positive' instead.
3) Have the output in the following format:
Story | Story Type | Creation Date | Company Role | Tag 1 | Tag 2 | Tag 3

negative iii | 1 | 21/02/2011 | Business Analyst | Project Duration | Team Size | Process
negative ccc | 1 | 22/02/2011 | Admin | Workspace Layout | Organisational | Process

A: You can modify the column names of the data table. Use foreach(DataColumn col in dt.Columns) then use col.ColumnName
You can access and modify the data for the specific column for your criteria using (Convert.ToInt16(col[n]) != 1)? "Positive" : "Negative" inside a loop. Use dt.Rows.Count for the loop's condition.
Hope this helps.
You can use this inside the foreach loop:
if (col.ColumnName == "StoryCategoryId") //Or "Story Type"
for(int rowCount = 0; rowCount < table.Rows.Count; rowCount++)
{
    col[rowCount] = (Convert.ToInt16(col[rowCount]) == 0) ? "Positive" : "Negative";
}


text:
Q: Python Challenge I am doing the coin-change problem. I have finished the problem, that it prints out how many coins I need to make the least amount of change possible, but how do I change my program so that it also prints those coins??
Here is a sample I/O:
input: coin_change(48, [1, 5, 10, 25, 50])

output: [6, [25, 10, 10, 1, 1, 1]]

input: coin_change(48, [1, 7, 24, 42])

output: [2, [24, 24]]

Currently my code only returns the 6.
By the way, this must be done with recursion only. No loops are allowed.
Code:
def change(C, V):
    def min_coins(i, aC):
        if aC == 0:
            return 0
        elif i == -1 or aC < 0:
            return float('inf')
        else:
            return min(min_coins(i-1, aC), 1 + min_coins(i, aC-V[i]))
    return min_coins(len(V)-1, C)

The code below is what I tried, but it does NOT work for the second input
def giveChange(C, V, res = None):
    res=[] if res is None else res
    if len(V)==0:
        return len(res),res
    maxx=max(V)
    print maxx
    V.remove(maxx)
    ans=C//maxx
    if ans==0 and maxx<C :
        print maxx
        res +=[maxx]*ans
        return  len(res),res
    else:
        res += [maxx]*ans
        return  giveChange(C % maxx,V,res)

A: Might not use maxx=max(V)
An optimal solution may comprise of small coins, for example 48=24+24, which has two coins, lesser than 48=25+10+10+1+1+1. In that case, though 25>24, you have to use more tiny coins to make a 48.
Thus if your input is (48, [1, 7, 24, 42]), you will be trapped in the second situation and get a 48 = 42+1+1+1+1+1+1. You can combine your second posted codes with your first one, add a list as parameter for storing the changes and use the same recursion design.

A: Your first code will work with a few changes. Instead of returning just count, a function can return a list or even (count, [coins]) tuple. you may also want to sort V.


text:
Q: Cells.SpecialCells(xlCellTypeVisible).Copy slow in loop I have been asked to create a macro the filters an Excel worksheet on one row, creates a new workbook, and copies the filtered rows along with the header and formulas to the new workbook.
I have created a macro that first reads the target row and generates an array contains the unique values. It then loops through the unique values. Within the loop a new workbook is created. The source worksheet is filtered using auto filter for the unique value. The matching rows along with the headers are copied to the new workbook. The new workbook is saved.
The first time the loop executes in less than one second. The second time and subsequent times it hangs up on the line:
oSheet.Cells.SpecialCells(xlCellTypeVisible).Copy Destination:=oSplitSheet.Range("A1")
It takes almost a minute for this line to execute.
I have tried: application.copyandpaste = false, sheet.empty cell.copy, and a Win32 API call to empty the clopboard all to no effect.
The test source worksheet is 91 columns wide, 285 rows long, contains a 2 row header, and the filtered column is column B.
I have included a copy of the loop below. Any suggestions would be helpful.
'Create the split books
For lngFilterRow = 1 To lngFilterRowMax
    'update the form
    Me.txtCurrent = lngFilterRow
    DoEvents

    'Get the next filter
    strFilter = rayFilter(lngFilterRow)

    'Get the split sheet name
    strSplitName = Me.txtFolder & "\" & strBaseName & "_" & strFilter & ".xlsx"

    'Open the target workbook
    Set oBook = Application.Workbooks.Add
    Set oSplitSheet = oBook.Worksheets(1)

    'Set the cell widths
    For lngCol = lngColFirst To lngColMax
        oSplitSheet.Range(oSplitSheet.Cells(1, lngCol), oSplitSheet.Cells(1, lngCol)).ColumnWidth = rayCol(lngCol).ColumnWidth
    Next

    'Filter the sheet
    oSheet.AutoFilterMode = False
    strCell = "$" & Me.txtSource & "$" & lngHeaderRowMax
    lngFilterCol = oSheet.Range(strCell).Column
    strCell = "$" & Me.txtColumnFirst & "$" & Me.txtHeaderRowLast & ":$" & Me.txtColumnLast & "$" & Me.txtHeaderRowLast
    oSheet.Range(strCell).AutoFilter Field:=lngFilterCol, Criteria1:=strFilter

    'Paste the fitlered sheet
    oSheet.Cells.SpecialCells(xlCellTypeVisible).Copy Destination:=oSplitSheet.Range("A1")

    'Get the Row Count
    strCell = "$" & Me.txtSource & "$" & lngRowFirst
    lngCol = oSplitSheet.Range(strCell).Column
    If IsEmpty(oSplitSheet.Cells(lngRowFirst + 1, lngCol).Value) Then
        lngSplitRowMax = lngRowFirst
    Else
        lngSplitRowMax = oSplitSheet.Range(strCell).End(xlDown).Row
    End If

    'add the formulas and numberformats
    For lngCol = lngColFirst To lngColMax
        Set oRange = oSplitSheet.Range(oSplitSheet.Cells(lngRowFirst, lngCol), oSplitSheet.Cells(lngSplitRowMax, lngCol))
        oRange.NumberFormat = rayCol(lngCol).NumberFormat
        oRange.Interior.Color = rayCol(lngCol).BackColor
        If rayCol(lngCol).HasFornula Then
            Set SourceRange = oSplitSheet.Range(oSplitSheet.Cells(lngRowFirst, lngCol), oSplitSheet.Cells(lngRowFirst, lngCol))
            SourceRange.Formula = rayCol(lngCol).Formula
            If lngSplitRowMax > lngRowFirst Then
                SourceRange.AutoFill Destination:=oRange
            End If
        End If
    Next

    'Save the workbook
    oBook.SaveAs Filename:= _
        strSplitName, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    oBook.Close savechanges:=False

    'Update the progress bar
    txtProgressBarB.Width = (txtProgressBarA.Width / lngFilterRowMax) * lngFilterRow
    DoEvents

    Set oRange = Nothing
    Set SourceRange = Nothing
    Set SplitRange = Nothing
    Set oSplitSheet = Nothing
    Set oBook = Nothing

Next

A: Excel-2007 onward, number of cells increased drastically. So your code will run much faster in  Excel-2003. Reason for slowness is that everywhere in your code you are referring all the cells in the worksheet.
Such as
Change  oSheet.AutoFilterMode to oSheet.UsedRange.AutoFilterMode
Change  oSheet.Cells.SpecialCells(xlCellTypeVisible) to oSheet.UsedRange.SpecialCells(xlCellTypeVisible)
Review your code and anywhere if you are referring all the cells just confine it to the exact range that you need. Mostly, usedrange will take care of that. And this will increase your code speed

A: I have found an answer of sorts. It seems that Microsoft has changed the events surrounding the use of the clipboard which account for the slow performance. In other words the code is running as designed.
Please refer the these two references for details:
https://social.msdn.microsoft.com/Forums/office/en-US/858c1c9d-a347-473d-8c81-829e22b6f592/slow-excel-2010-macro-execution?forum=exceldev
https://social.msdn.microsoft.com/Forums/office/en-US/c15acbd2-abc8-4135-b8af-4598da70c675/specialcells-function-is-very-slow-in-excel-2010?forum=exceldev


text:
Q: How (and why) do you use contrasts? Under what cases do you create contrasts in your analysis? How is it done and what is it used for?
I checked ?contrasts and ?C - both lead to "Chapter 2 of Statistical Models in S", which is not readily available to me.

A: Take a look here (pages 365-370, which are free to view). On page 364 starts a one-way analysis of variance of a plant competition experiment. The code from page 364 that is missing is:
comp<-read.table("c:\\temp\\competition.txt",header=T)
attach(comp)
names(comp)
[1] "biomass" "clipping"
The categorical explanatory variable is clipping and it has five levels as follows:
levels(clipping)
...

The definition of contrasts is given later, on page 368 (in the homonym paragraph). If you want to follow the examples, you can download the datasets. See my post here.
It is out of the question that the book is highly recommended.

A: Contrasts are needed when you fit linear models with factors (i.e. categorical variables) as explanatory variables. The contrast specifies how the levels of the factors will be coded into a family of numeric dummy variables for fitting the model.
Here are some good notes for the different varieties of contrasts used:
http://www.unc.edu/courses/2006spring/ecol/145/001/docs/lectures/lecture26.htm
When the contrasts used are changed, the model remains the same in terms of the underlying joint probability distributions allowed. Only its parametrization changes. The fitted values remain the same as well. Also, once you have the value of the parameters for one choice of contrasts, it is easy to derive what the value of the parameters for another choice of contrasts would have been.
Therefore the choice of contrasts has no statistical consequence. It is purely a matter of making coefficients and hypothesis tests easier to interpret.


text:
Q: Need Compilers on Server I'm looking to build a web service that can compile some entered code (probably C/Java) and can run some tests on it. What kind of design should I follow? What compiler can I place on my server to do the job? Recommendations? Pros? Cons?

A: Kattis uses GCC and the Sun java compiler to compile C/C++/Java. What platforms you intend to support will of course determine what compilers you can use. I think it'll be easier for you if you just go with multiple compilers instead of trying to find one that can compile every language you want to support.
One of the biggest problems will probably be to prevent the submitted code from taking over your host. Java contains built in support for limiting what classes a program can use, but I'm not sure how one would prevent things like forking and creating sockets in C/C++.

A: You will probably want something like the Go Playground

A: For Java, see the JavaCompiler.
I provide a little tool called the SSCCE Text Based Compiler that can do this on the client side, and as the docs. note, it requires a Java SDK, not just a JRE.
Pros:

*

*Server-side compilation & running of code sounds funky!

Cons:

*

*A long time ago I also provided a tool to compile code (but not run it) on one of my domains.  It turned out that particular types of code could tie the Sun compiler up in knots that would require more than 30 minutes to compile less than 100 lines of code!  Denial of Service attack, anyone?  Since I did not have the time to implement a solution, I withdrew the tool.

*For running the code, you will almost certainly need to implement a comprehensive SecurityManager.

A: The simplest thing to get going is a web container (like Tomcat or Jetty) where the users are allowed to upload their own JSP-pages.
These are automatically compiled by the web container, and executed, when requested.


text:
Q: No matter what I do, overflow-x: hidden doesn't work on mobile devices I've been working on this website, and i cannot seems to disable the horizontal scrolling on mobile devices. I've looked up countless of questions concerning this problem, but none of them seem to solve my problem.
http://athostrainingcenter.be/home.html
So the overflow-x is disabled for desktop and even if I change the width of my browser on desktop it's also disabled. It's also disabled when I click on 'inspect' and view the website on a mobile device on my computer.
But when I open the website on my actual phone I can still scroll to the right. I wish there was just one solution that fits all.
Anyone who can give me any advice?
Cheers


text:
Q: How do we prove that two propositions which are given below are equivalent? $$(\forall x\in X) p(x)\overset{?}{\equiv} \forall x [x\in X\Rightarrow p(x)]$$

A: I believe the statements $\forall x \in X(P(x))$ and $\forall x (x \in X \rightarrow P(x))$ are logically equivalent by definition of a restricted universal quantifier. In other words, the restriction of the domain of a universal quantifier is the same as taking the universal quantification of a conditional statement. An helpful example is
$$\forall x < 0 (x^2 >0) \Leftrightarrow \forall x (x < 0 \rightarrow x^2 >0)$$
Notice, however, that the restriction of the domain of an existential quantifier is the existential quantification of a conjunction. In other words, $\exists x \in X (P(x)) \Leftrightarrow \exists x (x \in X \wedge P(x))$. For example,
$$\exists x > 0 (x^2 = 2) \Leftrightarrow \exists x (x > 0 \wedge x^2 = 2)$$
Again, I believe this is also true by definition of a restricted existential quantifier.


text:
Q: Declare a class in inline-code in aspx/c# I've got a self contained aspx script that now needs a small class for one function. Is there any way to declare a class in the code of this page without adding a code behind (aspx.cs) file?
I'd like to keep everything in one single file for neatness sake.

A: I'd like to keep everything in one single file for neatness sake. I fail to see how mixing code and markup could ever be neat. That being said, you could add the class inside of a <script> block, e.g: -
<script runat="server">
  public class MyClass
  {
     public static string Example()
     {
        Response.Write("Hello world");
     }
  }
</script>

A: The most straightforward way is something like this:
<%@ Page Language="C#"%>

<script runat="server">
  public string OneFunction(string input)
  {
    return "It worked" + input;
  }
</script>

A: Yes, they are called Embedded Code Blocks, like this:
<%@ Page Language="C#" %>
<script runat=server>
protected String GetTime()
{
    return DateTime.Now.ToString("t");
}
</script>
<html>
<body>
   <form id="form1" runat="server">
       Current server time is <% =GetTime()%>.
   </form>
</body>
</html>


text:
Q: Rust htons and ntohs I have a program that has been relying on native::io::net::{htons, ntohs} but now errors on Could not find 'io' in 'packet::native'.  The change seems to have happened some time in the last week
Searching doesn't yield much info about the change and a search for htons or ntohs in the docs doesn't yield any useful information.
What is the (new?) standard way to perform htons or ntohs in Rust?
An obvious solution would be to write my own but one would expect that it would be in the standard library.

A: These are now in std::sys_common::net, but std::sys_common is private. But their implementation in src/libstd/sys/common/net.rs is very simple:
pub fn htons(u: u16) -> u16 {
    u.to_be()
}
pub fn ntohs(u: u16) -> u16 {
    Int::from_be(u)
}

A: You can use the from_be and to_be functions on the Int trait.  Network order is big endian, so this is equivalent.
You can find example usages in the documentation for them:
http://doc.rust-lang.org/core/num/trait.Int.html#method.to_be
http://doc.rust-lang.org/core/num/trait.Int.html#method.from_be


text:
Q: Paramiko doesn't return grep correctly I am building myself a tool to run/kill scripts on my VPS over SSH. So far I was able to do exactly that (start or kill processes) but I can't manage to get the ps -fA | grep python command to work.
Some of my scripts actually spawn new scripts with Popen so I really need a way to check the PID of python scripts through SSH (and the name of the file the PID belongs to).
    ssh_obj = self.get_ssh_connection()
    stdin, stdout, stderr = ssh_obj.exec_command('ps -fA | grep python')
    try:
        stdin_read = "stdin: {0}".format(stdin.readline())
    except Exception as e:
        stdin_read = "stdin: ERROR " + str(e)
    try:
        stdout_read = "stdout: {0}".format(stdout.readline())
    except Exception as e:
        stdout_read = "stdout: ERROR " + str(e)
    try:
        stderr_read = "stderr: {0}".format(stderr.readline())
    except Exception as e:
        stderr_read = "stderr: ERROR " + str(e)
    print("\n".join([stdin_read, stdout_read, stderr_read]))

But it doesn't works, the result it shows to me is:
stdin: ERROR File not open for reading
stdout: root       739   738  0 17:12 ?        00:00:00 bash -c ps -fA | grep python
stderr:

While the desired output would be something like:
PID: 123 - home/whatever/myfile.py
PID: 125 - home/whatever/myfile2.py
PID: 126 - home/whatever/myfile.py

That way I'll know which PIDs to kill for myfile script (123 and 126).
Bonus question: I'm not very linux experienced, does executing grep commands outside of the Terminal creates any PID that I have to manually kill?

A: You may need to escape the pipe character by passing the whole statement in single quotes to a shell on the other end:
ssh_obj.exec_command("sh -c 'ps -fA | grep python'")

Alternatively you could try running pgrep:
ssh_obj.exec_command('pgrep python')

pgrep will search the current running processes that match the search string python and will send just the process IDs to the stdout.


text:
Q: Installation failed when attempting to reinstall MySQL in OS X 10.6.6 I had earlier installed mysql-5.1.50-osx10.6-x86_64.dmg and then uninstalled it using the below command (found on Stack Overflow):
$ sudo rm /usr/local/mysql
$ sudo rm -rf /usr/local/mysql*
$ sudo rm -rf Library/StartupItems/MySQLCOM
$ sudo rm -rf /Library/PreferencePanes/My*
$ rm -rf ~/Library/PreferencePanes/My*
$ sudo rm -rf /Library/Receipts/mysql*
$ sudo rm -rf /Library/Receipts/MySQL*
$ sudo vi /etc/hostconfig
$ sudo rm -rf /var/db/receipts/com.mysql.mysql*
$ cd /Library/Receipts/

Then I have tried to reinstall from mysql-5.5.9-osx10.6-x86_64.dmg.
However I am getting the following error:

The installation failed
  The installer encountered an error that caused the installation to fail. Contact the software manufacturer for assistance.

A: This might be a little late, but Homebrew for Macintosh is a stellar way to install software such as mysql. There is information on the their wiki on how to install and then once brew is installed, it is just brew install mysql in your terminal window.
Good luck!
Update: DOH. I fail at reading. Problem already solved. Anyway, for people in the future, if you have trouble installing mysql, give brew a try.

A: Try to install MySql from the CD that come with your computer. It is part of apple developer tools. Once that is installed, try to install the dmg you downloaded from the official site.

A: I am able to instal MySQL at last. Details can be found @
https://stackoverflow.com/questions/5067787/re-install-mysql-in-mac-os-x-10-6-6


text:
Q: How can I differentiate colors from styled-components and usual components in React at VSCode? Does anyone knows how to differentiate tag colors from styled-components and usual components from React on VScode? Actually, i`m using Dracula theme.
Here`s an example.
enter image description here


text:
Q: Auto opening generated pdf file My application generates pdf file and writes out to some folder.
Is there any setup to automatically open it when its generated?

A: Some applications offer to open the just created file, but if not:
Assuming your temp directory is a "flat" directory (without .pdf files in subdirectories) does not contain thousands of files (since it is a temp directory), the small background script will do the job.
It keeps an eye on the directory and opens new .pdf files with your default application to open pdf files.
How to use:

*

*Copy the script below into an empty file, save it as open_newpdf.py

*In the head section of the script, set the path to your directory

*Test run it from a terminal window, type the command:
python3 /path/to/open_newpdf.py

Create a new .pdf file in your directory, it should open within 3 seconds.

*If all works fine, add it to your startup applications: Dash > Startup Applications > Add
The script
#!/usr/bin/env python3
import os
import time
import subprocess

#--- set the absolute path to your directory below
dr = "/home/jacob/Bureaublad/test"
#---

ls1 = os.listdir(dr)
while True:
    time.sleep(3)
    ls2 = os.listdir(dr)
    for item in ls2:
        if all([not item in ls1, item.endswith(".pdf")]):
            subprocess.Popen(["xdg-open", dr+"/"+item])
    ls1 = ls2

A: There is a simpler alternative. If you have a script that generates PDF files, then you can also make it run the following commands each time it creates a PDF file called file.pdf,
xdg-open file.pdf

which will open the file with the default application set to handle PDF file.

A: Create wrapper script watch_pdf:
#!/bin/bash
FILE="$1"
if [ "${FILE##*.}" = "pdf" ]
then
echo "$2/$1"
    xdg-open "$2/$1"
fi
exit 0

make it executable:
chmod +x <path_of_watch_pdf>

Watch your folder:
inoticoming <your_tmp_folder> <path_of_watch_pdf> {} <your_tmp_folder> \;


text:
Q: Checking for possibility to place word horizontally or vertically in Crossword Game I have written the following code which takes in words from the user, sorts them from longest to shortest, and then checks to see if there is a possible place for the word to be put. What I am having trouble with is figuring out how to check whether the word can be placed horizontally or vertically. Any help would be greatly appreciated.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void initialize_board(char board[][15]);
void get_user_info(char words[][16], int *numbofwords);
void sort_words(char words[][16], int numbofwords);
void display_solution_board(char board[][15]);
void place_words(char board[][15], char words[][16], int numbofwords);
int check_if_fits(char board[][15], char * word, int *j, int *n);

int main(){
    char words[20][16];
    char board[15][15];
    int numbofwords = 0;
    int i;
    //create a board of all pound symbols
    initialize_board(board);
    //get words for crossword from user
    get_user_info(words, &numbofwords);
    //sort words array to go from longest word to shortest
    sort_words(words,numbofwords);
    //places the words in appropriate places
    place_words(board,words,numbofwords);
    //displays the output of the board with answers
    display_solution_board(board);
}

void initialize_board(char board[][15]){
    int j,k;
    for(j = 0; j < 15; j++){
        for(k = 0; k < 15; k++){
            strcpy(&board[j][k],"#");
        }
    }
}

void get_user_info(char words[][16], int *numbofwords){
    char word[16];
    int i = 0;
    printf("Please enter up to 20 words of up to 15 characters in length.\n");
    printf("Use a period to end your input if you want less than 20 words.\n");
    scanf("%s", word);
    while(strcmp(word, ".") != 0){
        strcpy(words[i],word);
        i++;
        if(i == 20){
            break;
        }
        scanf("%s", word);
    }
    *numbofwords = i;

}

void sort_words(char words[][16], int numbofwords){
    int i, j;
    char temp[16];
    for(i = 0; i < numbofwords-1; i++){
        for(j = 0; j < numbofwords-i-1;j++){
            if(strlen(words[j]) < strlen(words[j+1])){
                strcpy(&temp[0],words[j]);
                strcpy(words[j],words[j+1]);
                strcpy(words[j+1],&temp[0]);
            }
        }
    }
}

void display_solution_board(char board[][15]){
    int j,k;
    for(j = 0; j < 15; j++){
        for(k = 0; k < 15; k++){
            printf("%c",board[j][k]);
        }
        printf("\n");
    }
}

void place_words(char board[][15], char words[][16], int numbofwords){
int i,j,k,max;
int n,r = 0;

//sets the longest word in the middle of the grid
max = strlen(words[0]);
printf("max is %d\n",max);
printf("num words is %d\n",numbofwords);
strncpy(&board[7][(15-max)/2],words[0], strlen(words[0]));
//goes through all other words to find a place for them
for(i = 1; i < numbofwords; i++){
    if(check_if_fits(board,words[i],&j,&k) == 0 && check_vertical_placement(board,words[i],j,k) == 0){
        //printf("The word %s fits in col %d and row %d\n", words[i],k,j);
        for(k = k;k < strlen(words[i]);k++){
            board[j][k] = words[i][r];
            r++;
        }
    }else if(check_if_fits(board,words[i],&j,&k) == 0 && check_horizontal_placement(board,words[i],j,k) == 0){
        //printf("The word %s fits in col %d and row %d\n", words[i],k,j);
        for(j = j; j < strlen(words[i]); j++){
            board[j][k] = words[i][n];
            n++;
        }
    }else if(check_if_fits(board,words[i],&j,&k) == 1){
        printf("The word %s doesn't fit\n", words[i]);
    }
}
}

int check_if_fits(char board[][15], char * word, int *j, int *n){
    int k,t,h,g;
    for(t = 0; t < 15; t++){
        for(h = 0; h < 15; h++){
            for(k = 0; k < strlen(word); k++){
                if(board[t][h] == word[k]){
                    *j = t+1;
                    *n = h+1;
                    return 0;
                }
            }
        }
    }
    return 1;
}

int check_horizontal_placement(char board[][15],char * word, int j,int k){
    int i,val;
    for(i = k; i < strlen(word);i++){
        if(board[j][i] == '#' && board[j+1][i] == '#' && board[j-1][i] == '#') val = 0;
    }
    if(val == 0) return(0);
    else{return(1);}
}

int check_vertical_placement(char board[][15],char * word, int j,int k){
    int i,val;
    for(i = j; i < strlen(word);i++){
        if(board[i][k] == '#' && board[i][k+1] == '#' && board[i][k-1] == '#') val = 0;
    }
    if(val == 0) return(0);
    else{return(1);}
}

A:
Do you have any suggestions as to how to check whether a word fits
  from above the middle row?

Replace in place_words() the body of your for(i = 1; i < numbofwords; i++) loop with
    switch (check_if_fits(board, words[i], &j, &k))
    {
    case -1:// vertical_placement
        //printf("The word %s fits in col %d and row %d\n", words[i],k,j);
        for (r = 0; r < strlen(words[i]); r++) board[j+r][k] = words[i][r];
        break;
    case 0: // horizontal_placement
        //printf("The word %s fits in col %d and row %d\n", words[i],k,j);
        for (n = 0; n < strlen(words[i]); n++) board[j][k+n] = words[i][n];
        break;
    case 1:
        printf("The word %s doesn't fit\n", words[i]);
    }

replace the lines *j = t+1;
*n = h+1; in check_if_fits() with checks for both placements:
                  if (check_vertical_placement(board, word, *j=t-k, *n=h)==0)
                    return -1;
                  if (check_horizontal_placement(board, word, *j=t, *n=h-k)==0)

and the check functions with
int check_horizontal_placement(char board[][15], char *word, int j, int k)
{
    int i;
    if (k < 0 || 15 < k+strlen(word)) return 1; // word outside board
    if (k && board[j][k-1] != '#') return 1;    // another word in front
    for (i = 0; i < strlen(word); i++)
        if (board[j][k+i] != '#' && board[j][k+i] != word[i]) return 1;
    if (k+i < 15 && board[j][k+i] != '#') return 1; // another word behind
    return 0;
}

int check_vertical_placement(char board[][15], char *word, int j, int k)
{
    int i;
    if (j < 0 || 15 < j+strlen(word)) return 1; // word outside board
    if (j && board[j-1][k] != '#') return 1;    // another word in front
    for (i = 0; i < strlen(word); i++)
        if (board[j+i][k] != '#' && board[j+i][k] != word[i]) return 1;
    if (j+i < 15 && board[j+i][k] != '#') return 1; // another word behind
    return 0;
}


text:
Q: How to insert dictionary items into a PostgreSQL table So I've connected my Postgresql database into Python with Psycopg2, and I've pulled two specific columns to update. The first column I have used as the keys in a Python dictionary, and I have run some functions on the second one and use the results as the values in the dictionary. Now what I want to do is add those values back into Postgresql table as a new column, but I want them to pair with the correct keys they are paired with in the dictionary. Essentially, I want to take dictionary values and insert them as a new column and pick which "key" in the Postgresql table they belong to (however, I don't want to manually assign them, because, well, there's hopefully a better way).
Postgresql Table
     |col1   |col2  |col3   | ... | coln
row1 | a1    | b1   | c1    | ... | n1
row2 | a2    | b2   | c2    | ... | n2
...  | ...   | ...  | ...   | ... | n...
rowm | am    | bm   | cm    | ... | nm

This is the dictionary I made in Python, where f() is a series of functions ran on variable:
{
    a1 : f(c1),
    a2 : f(c2),
    ... : ...
}

Now my goal is to add the values column back into my table so that it corresponds to the original keys. Ideally, to look something like this:
     |col1|col2|col3| ... |newcol| coln
row1 | a1 | b1 | c1 | ... | f(c1)| n1
row2 | a2 | b2 | c2 | ... | f(c2)| n2
...  | ...| ...| ...| ... |  ... | n...
rowm | am | bm | cm | ... | f(cm)| nm

I know I can insert the column into the table, but not sure how to pair it with keys. Any help is very much appreciated!

A: You want an UPDATE statement something like the following:
import psycopg2

con = psycopg2.connect('your connection string')
cur = connection.cursor()
# add newcol
cur.execute('ALTER TABLE your_table ADD COLUMN newcol text;')
con.commit()
for k,v in your_dict.iteritems():
    cursor.execute('''UPDATE your_table
                         SET newcol = (%s)
                       WHERE col1 = (%s);''',(v,k))
    conn.commit()
cur.close()
con.close()

A: Update all the rows in a single query. First turn the dictionary into a list of tuples:
l = [(k,v) for k,v in my_dict.items()]

A Python list of tuples is adapted to an array of records by Psycopg. Then unnest the array in the from clause:
query = '''
    update t
    set colX = s.val::text
    from unnest(%s) s (key integer, val unknown)
    where t.col1 = s.key
'''

print cursor.mogrify(query, (l,))
cursor.execute(query, (l,))

Records returned from unnest need to have their elements types declared. For string values is it necessary to declare their type as unknown and cast to the appropriate type at assignment or comparing time. For all other types just declare them as usual.


text:
Q: Multiple Days CVRP: Choose from Multiple Demand Matrices I would like to make the model choose a demand matrix. For example one  matrix would look like this for three days. Each line is one day:
[[0, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1]]

But a day-delivery can be substituted by a delivery on another day, so another matrix could be this:
[[0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 3, 3, 5, 2, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 1]]

Now I want the model to decide if its is better to use the first matrix or the second matrix. You can't pick the first and third line of the first matrix and the second line from the second. That would be forbidden.
I thought maybe it is possible to define a dimension for each demand matrix, but only one of these must be fulfilled.
Thank you in advance.
Thomas


text:
Q: Using variable from one component to another component without using props I have a component YourInformation:
class YourInformation extends React.Component{
constructor(props) {
    super(props);
    this.state = {
        errors: {},
        username:"",
        alterEGO:"",
        aboutYou:"",
        stage:1,
        blocking: false,
        canSubmit: false
    };

    /**** binding to make context of this to class ***/
    this.formValueChange = this.formValueChange.bind(this);
    this.disableButton = this.disableButton.bind(this);
    this.enableButton = this.enableButton.bind(this);
    this.submitInformation = this.submitInformation.bind(this);
}

/**** function to handle change in form inputs ****/
formValueChange(event) {
    event.preventDefault();
    if (event.target.id == 'username') {
      this.state.username = event.target.value;
    } else if (event.target.id == 'alterEGO') {
      this.state.alterEGO = event.target.value;
    } else if (event.target.id == 'aboutYou') {
      this.state.aboutYou = event.target.value;
    }

    return true;
}

/**** function to handle submit event ****/

submitInformation() {

    let _that = this;
    _that.setState({ blocking: true});

    /***** fetch API for your information starts **********/

    fetch(Constants.SERVER_URL + '/api/', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username: this.state.username,
            alterEGO: this.state.alterEGO,
            aboutYou: this.state.aboutYou,
            stage: this.state.stage,
        }),
}).then(function (response) {

And one more component i.e.,
class ProfileInformation extends React.Component{
constructor(props) {
    super(props);
    this.state = {
          errors: {},
          customUrl:"",
          facebookLink:"",
          youtubeLink:"",
          instagramLink:"",
          twitterLInk:"",
          coverPic:"",
          profilePic:"",
          stage:3,
          categories:[],
          blocking: false,
          canSubmit: false
    };

    /**** binding to make context of this to class ***/
    this.formValueChange = this.formValueChange.bind(this);
    this.disableButton = this.disableButton.bind(this);
    this.enableButton = this.enableButton.bind(this);
    this.submitProfile = this.submitProfile.bind(this);
    this.getCategories = this.getCategories.bind(this);

}
I would like to access "username, alterEGO, aboutYOU" from yourInformation to ProfileInformation as I need these values prefilled in the profileInformation component form.
How can I fix this issue without using props, as I can not call ProfileInformation component into YourInformation component's render method?

A: React doesn't really work this way. In react you want to have the data in the lowest parent possible that will use the information. So basically if you have 2 components working on the same data, this data should be managed by the parent component of these 2, and sent via props to both the components. I recommend you read the react documentation for further understanding.
If you want to access the data globally, I would complement your project with redux. Redux allows you to have a general store on the application that stores all the data, and you can access it from many components since it's stored on the whole application not just in a single component.


text:
Q: SSAS many-to-many relation between dimension levels in a hierarchy using a ragged hierarchy I've got a question about how to create one dimension in SSAS that contains a hierarchy built from two dimensions.
I have a fact-table:
sales
and a many-to-many relation between two dimensions:
customers
bridgecustomersTerritory
territory
And the Territorydimension is at the moment built as a ragged hierarchy containing a ID and a parentID.
This works fine if i use the Territory dimension and Customer dimension apart from eachother as dimensions.
But i would like to add the customer at the bottom of the territory hierarchy
Is this even possible with the setup that i've got right now?
If i change the Territory to a "normal" hierarchy with a solid number of levels, would that help?
//Kriss

A: You cannot have attributes from two dimensions in one hierarchy. And as you use a many-to-many relationship between customer and territory, I assume you need it as a customer can be located in several territories, and there is obviously more than one customer per territory.
But why do you want to have customers and territory in one hierarchy? You can have them in separate hierarchies, and still use them in one query. In MDX, and hence in most client tools accessing Analysis Services that I know, you can drag more than one hierarchy to the rows or columns.
UPDATE
To some extent, I can understand the requirement to combine things. In a client tool that I developed, we do not expose the dimensions to the user at all, we are just using the display folders of the attributes/hierarchies. In this way, we can show attributes/hierarchies close together even if they technically need to be in different dimensions due to the modeling requirements. But they are still separate attributes/hierarchies, and users work well with this.
Yes, if you would want one hierarchy, you would need to integrate the customers into your territory dimension, taking care that you break down a customers measures like sales correctly between the different territories. And if you can do that easily, maybe there is no need for a many-to-man relationship at all.


text:
Q: CONTAINS with multiple terms over multiple columns I'm trying to perform a CONTAINS query with multiple terms over multiple columns, like this:
SELECT ID
FROM Table
WHERE CONTAINS((Data1,Data2,Data3), '"foo" & "bag" & "weee"')

However, this query does not behave like I want it to: I want it to return all records for which all terms appear at least once in at least one of the columns, like this:
SELECT ID
FROM Table
WHERE CONTAINS((Data1,Data2,Data3), '"foo"')
AND CONTAINS((Data1,Data2,Data3), '"bag"')
AND CONTAINS((Data1,Data2,Data3), '"weee"')

While this query returns the correct results, it needs a separate AND-clause for every term. Is there a way to express the same query with a single where-clause like in the upper example? This would be convenient when including the query in a (fixed) function.

A: SQL Server once behaved this way, but it was considered a bug and "corrected".
You need to create a FULLTEXT index on a computed column:
DROP TABLE t_ft
CREATE TABLE t_ft (id INT NOT NULL,
        data1 NVARCHAR(MAX) NOT NULL, data2 NVARCHAR(MAX) NOT NULL, data3 NVARCHAR(MAX) NOT NULL,
        totaldata AS data1 + ' ' + data2 + ' ' + data3,
        CONSTRAINT pk_ft_id PRIMARY KEY (id))

CREATE FULLTEXT INDEX ON t_ft (totaldata LANGUAGE 1033) KEY INDEX pk_ft_id

INSERT
INTO    t_ft
VALUES  (1, 'foo bar', 'baz', 'text')

INSERT
INTO    t_ft
VALUES  (2, 'foo bar', 'bax', 'text')

SELECT  *
FROM    t_ft
WHERE   CONTAINS (*, 'foo AND baz')

In MySQL, on the contrary, the fulltext index searches and matches across all columns and this is a documented behavior.


text:
Q: Open GL performance on QT I am using the QT 4.8 with Open GL ES 2.0 (created my set of shaders etc...)
Running the entire application from within QGraphicsView that owns a QGraphicsScene, I get relatively low fps although I am rendering a simple model (around 30 fps).
The scene render itself is triggered by a timer that fires at 50Hz (that can be changed).
What would be the most time consuming sections to attend in order to improve the frame rate?
Also, I noticed (using gDebugger) that the functions and states associated with the GL_STENCIL_TEST and GL_SCISSOR_TEST are killer consumers here (over 30% of the time goes on that).  Is there anyway to bypass that?
Thanks.


text:
Q: My pygame/pyopengl code seems to apply a texture to every surface I'm throwing some code together to help me better understand python, pygame, pyopengl, and 3D rendering. I've used code from two different places and I'm integrating them by writing my own code as I go. I've textured cubes in one program and made camera movement work in another. But when I put them together, the colors are wrong and surfaces that I don't intend to texture are affected. I'm sure I'm missing something, but I can't figure it out.
Here is what the two programs look like seperately.
,
But when I put them together, I get this.

Here is my code, sorry I couldn't figure out how to attach it as a file!
import pygame
from pygame.locals import *

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

import math

def tex_coord(x, y, n=4):
    """ Return the bounding vertices of the texture square.

    """
    m = 1.0 / n
    dx = x * m
    dy = y * m
    return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m

def tex_coords(top, bottom, side):
    """ Return a list of the texture squares for the top, bottom and side.

    """
    top = tex_coord(*top)
    bottom = tex_coord(*bottom)
    side = tex_coord(*side)
    result = [
        (top),
        (bottom),
        (side),
        (side),
        (side),
        (side),
    ]
    """result = []
    result.extend(top)
    result.extend(bottom)
    result.extend(side * 4)"""
    return result

#block type names and location on template go here
BLOCK1 = tex_coords((3, 0), (3, 0), (3, 0))

def verts(x, y, z, n):
    vertices = (
        (1+(2*x), -1+(2*y), -1+(2*z)),
        (1+(2*x), 1+(2*y), -1+(2*z)),
        (-1+(2*x), 1+(2*y), -1+(2*z)),
        (-1+(2*x), -1+(2*y), -1+(2*z)),
        (1+(2*x), -1+(2*y), 1+(2*z)),
        (1+(2*x), 1+(2*y), 1+(2*z)),
        (-1+(2*x), -1+(2*y), 1+(2*z)),
        (-1+(2*x), 1+(2*y), 1+(2*z))
        )
    return(vertices)

print(verts(0, 0, 0, 1))

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

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

surfaces = (
    (0,1,2,3),
    (3,2,7,6),
    (6,7,5,4),
    (4,5,1,0),
    (1,5,7,2),
    (4,0,3,6)
    )

forced = False
def Cube(vx,vy,vz,block):
    if not forced:
        glBegin(GL_QUADS)
        y = 0
        for surface in surfaces:
            x = 0
            y+=1
            for vertex in surface:
                x+=1
                #glColor3fv(colors[x])
                glTexCoord2f(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
                #print(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
                glVertex3fv(verts(vx,vy,vz,1)[vertex])
        glEnd()

        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glVertex3fv(verts(vx,vy,vz,1)[vertex])
        glEnd()
    else:
        texX = 0.75
        texY = 0.25
        glBegin(GL_QUADS)
        glTexCoord2f(0.0+texX, 0.0)
        glVertex3f(-1.0, -1.0,  1.0)
        glTexCoord2f(0.25+texX, 0.0)
        glVertex3f(1.0, -1.0,  1.0)
        glTexCoord2f(0.25+texX, 0.25)
        glVertex3f(1.0,  1.0,  1.0)
        glTexCoord2f(0.0+texX, 0.25)
        glVertex3f(-1.0,  1.0,  1.0)
        glEnd()

def loadTexture():
    textureSurface = pygame.image.load('texture2.png')
    textureData = pygame.image.tostring(textureSurface, "RGBA", 1)
    width = textureSurface.get_width()
    height = textureSurface.get_height()

    glEnable(GL_TEXTURE_2D)
    texid = glGenTextures(1)

    glBindTexture(GL_TEXTURE_2D, texid)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
                 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData)

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

    return texid

pygame.init()
display = (800, 600)
scree = pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glShadeModel(GL_SMOOTH)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)

glEnable(GL_LIGHT0)
glLightfv(GL_LIGHT0, GL_AMBIENT, [0.5, 0.5, 0.5, 1])
glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0, 1.0, 1.0, 1])

"""
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)

glDepthMask(GL_TRUE)
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
#glEnable(GL_CULL_FACE)
#glCullFace(GL_FRONT)
##glFrontFace(GL_CCW)
##glShadeModel(GL_SMOOTH)
glDepthRange(0.0,1.0)
"""

sphere = gluNewQuadric()

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

glMatrixMode(GL_MODELVIEW)
gluLookAt(0, -8, 0, 0, 0, 0, 0, 0, 1)
viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
glLoadIdentity()

# init mouse movement and center mouse on screen
displayCenter = [scree.get_size()[i] // 2 for i in range(2)]
mouseMove = [0, 0]
pygame.mouse.set_pos(displayCenter)

loadTexture()

up_down_angle = 0.0
paused = False
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN:
                run = False
            if event.key == pygame.K_PAUSE or event.key == pygame.K_p:
                paused = not paused
                pygame.mouse.set_pos(displayCenter)
        if not paused:
            if event.type == pygame.MOUSEMOTION:
                mouseMove = [event.pos[i] - displayCenter[i] for i in range(2)]
            pygame.mouse.set_pos(displayCenter)

    if not paused:
        # get keys
        keypress = pygame.key.get_pressed()
        #mouseMove = pygame.mouse.get_rel()

        # init model view matrix
        glLoadIdentity()

        # apply the look up and down
        up_down_angle += mouseMove[1]*0.1
        glRotatef(up_down_angle, 1.0, 0.0, 0.0)

        # init the view matrix
        glPushMatrix()
        glLoadIdentity()

        # apply the movment
        if keypress[pygame.K_w]:
            glTranslatef(0,0,0.1)
        if keypress[pygame.K_s]:
            glTranslatef(0,0,-0.1)
        if keypress[pygame.K_d]:
            glTranslatef(-0.1,0,0)
        if keypress[pygame.K_a]:
            glTranslatef(0.1,0,0)
        if keypress[pygame.K_LSHIFT]:
            glTranslatef(0,0.5,0)
        if keypress[pygame.K_SPACE]:
            glTranslatef(0,-0.5,0)

        # apply the left and right rotation
        glRotatef(mouseMove[0]*0.1, 0.0, 1.0, 0.0)

        # multiply the current matrix by the get the new view matrix and store the final vie matrix
        glMultMatrixf(viewMatrix)
        viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)

        # apply view matrix
        glPopMatrix()
        glMultMatrixf(viewMatrix)

        #glLightfv(GL_LIGHT0, GL_POSITION, [1, -1, 1, 0])

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        glPushMatrix()

        Cube(0,0,0,BLOCK1)
        Cube(1,0,0,BLOCK1)
        Cube(0,1,0,BLOCK1)
        Cube(0,0,1,BLOCK1)
        Cube(-2,0,0,BLOCK1)

        glColor4f(0.5, 0.5, 0.5, 1)
        glBegin(GL_QUADS)
        glVertex3f(-10, -10, -2)
        glVertex3f(10, -10, -2)
        glVertex3f(10, 10, -2)
        glVertex3f(-10, 10, -2)
        glEnd()

        glTranslatef(-1.5, 0, 0)
        glColor4f(0.5, 0.2, 0.2, 1)
        gluSphere(sphere, 1.0, 32, 16)

        glTranslatef(3, 0, 0)
        glColor4f(0.2, 0.2, 0.5, 1)
        gluSphere(sphere, 1.0, 32, 16)

        glPopMatrix()

        pygame.display.flip()
        pygame.time.wait(10)

pygame.quit()

I'd be very thankful if someone could explain this to me!
Edit: Thank you Rabbid76!!!
Here is a picture, and my working code.

import pygame
from pygame.locals import *

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

import math

def tex_coord(x, y, n=4):
    """ Return the bounding vertices of the texture square.

    """
    m = 1.0 / n
    dx = x * m
    dy = y * m
    return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m

def tex_coords(top, bottom, side):
    """ Return a list of the texture squares for the top, bottom and side.

    """
    top = tex_coord(*top)
    bottom = tex_coord(*bottom)
    side = tex_coord(*side)
    result = [
        (top),
        (bottom),
        (side),
        (side),
        (side),
        (side),
    ]
    """result = []
    result.extend(top)
    result.extend(bottom)
    result.extend(side * 4)"""
    return result

#block type names and location on template go here
BLOCK1 = tex_coords((3, 0), (3, 0), (3, 0))

def verts(x, y, z, n):
    vertices = (
        (1+(2*x), -1+(2*y), -1+(2*z)),
        (1+(2*x), 1+(2*y), -1+(2*z)),
        (-1+(2*x), 1+(2*y), -1+(2*z)),
        (-1+(2*x), -1+(2*y), -1+(2*z)),
        (1+(2*x), -1+(2*y), 1+(2*z)),
        (1+(2*x), 1+(2*y), 1+(2*z)),
        (-1+(2*x), -1+(2*y), 1+(2*z)),
        (-1+(2*x), 1+(2*y), 1+(2*z))
        )
    return(vertices)

print(verts(0, 0, 0, 1))

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

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

surfaces = (
    (0,1,2,3),
    (3,2,7,6),
    (6,7,5,4),
    (4,5,1,0),
    (1,5,7,2),
    (4,0,3,6)
    )

forced = False
def Cube(vx,vy,vz,block):
    if not forced:
        glBegin(GL_QUADS)
        y = 0
        for surface in surfaces:
            x = 0
            y+=1
            for vertex in surface:
                x+=1
                #glColor3fv(colors[x])
                glTexCoord2f(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
                #print(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
                glVertex3fv(verts(vx,vy,vz,1)[vertex])
        glEnd()

        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glVertex3fv(verts(vx,vy,vz,1)[vertex])
        glEnd()
    else:
        texX = 0.75
        texY = 0.25
        glBegin(GL_QUADS)
        glTexCoord2f(0.0+texX, 0.0)
        glVertex3f(-1.0, -1.0,  1.0)
        glTexCoord2f(0.25+texX, 0.0)
        glVertex3f(1.0, -1.0,  1.0)
        glTexCoord2f(0.25+texX, 0.25)
        glVertex3f(1.0,  1.0,  1.0)
        glTexCoord2f(0.0+texX, 0.25)
        glVertex3f(-1.0,  1.0,  1.0)
        glEnd()

def loadTexture():
    textureSurface = pygame.image.load('texture2.png')
    textureData = pygame.image.tostring(textureSurface, "RGBA", 1)
    width = textureSurface.get_width()
    height = textureSurface.get_height()

    glColor3f(0.5, 0.5, 0.5)
    glEnable(GL_TEXTURE_2D)
    texid = glGenTextures(1)

    glBindTexture(GL_TEXTURE_2D, texid)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
                 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData)

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)

    return texid

    glDisable(GL_TEXTURE_2D)

pygame.init()
display = (800, 600)
scree = pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glShadeModel(GL_SMOOTH)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)

glEnable(GL_LIGHT0)
glLightfv(GL_LIGHT0, GL_AMBIENT, [0.5, 0.5, 0.5, 1])
glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0, 1.0, 1.0, 1])

"""
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)

glDepthMask(GL_TRUE)
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
#glEnable(GL_CULL_FACE)
#glCullFace(GL_FRONT)
##glFrontFace(GL_CCW)
##glShadeModel(GL_SMOOTH)
glDepthRange(0.0,1.0)
"""

sphere = gluNewQuadric()

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

glMatrixMode(GL_MODELVIEW)
gluLookAt(0, -8, 0, 0, 0, 0, 0, 0, 1)
viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
glLoadIdentity()

# init mouse movement and center mouse on screen
displayCenter = [scree.get_size()[i] // 2 for i in range(2)]
mouseMove = [0, 0]
pygame.mouse.set_pos(displayCenter)

loadTexture()

up_down_angle = 0.0
paused = False
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or event.key == pygame.K_RETURN:
                run = False
            if event.key == pygame.K_PAUSE or event.key == pygame.K_p:
                paused = not paused
                pygame.mouse.set_pos(displayCenter)
        if not paused:
            if event.type == pygame.MOUSEMOTION:
                mouseMove = [event.pos[i] - displayCenter[i] for i in range(2)]
            pygame.mouse.set_pos(displayCenter)

    if not paused:
        # get keys
        keypress = pygame.key.get_pressed()
        #mouseMove = pygame.mouse.get_rel()

        # init model view matrix
        glLoadIdentity()

        # apply the look up and down
        up_down_angle += mouseMove[1]*0.1
        glRotatef(up_down_angle, 1.0, 0.0, 0.0)

        # init the view matrix
        glPushMatrix()
        glLoadIdentity()

        # apply the movment
        if keypress[pygame.K_w]:
            glTranslatef(0,0,0.1)
        if keypress[pygame.K_s]:
            glTranslatef(0,0,-0.1)
        if keypress[pygame.K_d]:
            glTranslatef(-0.1,0,0)
        if keypress[pygame.K_a]:
            glTranslatef(0.1,0,0)
        if keypress[pygame.K_LSHIFT]:
            glTranslatef(0,0.5,0)
        if keypress[pygame.K_SPACE]:
            glTranslatef(0,-0.5,0)

        # apply the left and right rotation
        glRotatef(mouseMove[0]*0.1, 0.0, 1.0, 0.0)

        # multiply the current matrix by the get the new view matrix and store the final vie matrix
        glMultMatrixf(viewMatrix)
        viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)

        # apply view matrix
        glPopMatrix()
        glMultMatrixf(viewMatrix)

        #glLightfv(GL_LIGHT0, GL_POSITION, [1, -1, 1, 0])

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        glPushMatrix()

        glEnable(GL_TEXTURE_2D)
        Cube(0,0,0,BLOCK1)
        Cube(1,0,0,BLOCK1)
        Cube(0,1,0,BLOCK1)
        Cube(0,0,1,BLOCK1)
        Cube(-2,0,0,BLOCK1)

        glDisable(GL_TEXTURE_2D)
        glColor4f(0.5, 0.5, 0.5, 1)
        glBegin(GL_QUADS)
        glVertex3f(-10, -10, -2)
        glVertex3f(10, -10, -2)
        glVertex3f(10, 10, -2)
        glVertex3f(-10, 10, -2)
        glEnd()

        glTranslatef(-1.5, 0, 0)
        glColor4f(0.5, 0.2, 0.2, 1)
        gluSphere(sphere, 1.0, 32, 16)

        glTranslatef(3, 0, 0)
        glColor4f(0.2, 0.2, 0.5, 1)
        gluSphere(sphere, 1.0, 32, 16)
        glColor3f(1, 1, 1)

        glPopMatrix()

        pygame.display.flip()
        pygame.time.wait(10)

pygame.quit()

A: OpenGL is a state engine. A state is kept until it is changed again. Two-dimensional texturing can be enabled and disabled, see glEnable.
When texturing is activated, by default the color of the pixel is multiplied by the current color, because by default the texture environment mode (GL_TEXTURE_ENV_MODE) is GL_MODULATE. See glTexEnv.
This causes that the color of the piles of the texture is "mixed" by the last color which you have set by glColor4f.
Set a "white" color and enable texturing before you render an object with a texture. Disable texturing before you draw an object with colors:
glColor3f(1.0f, 1.0f, 1.0f)
glEnable(GL_TEXTURE_2D)

# draw object with texture
# [...]

glDisable(GL_TEXTURE_2D)

# draw object with color
# [...]

Changes in your code:
forced = False
def Cube(vx,vy,vz,block):

    glColor4f(1, 1, 1, 1)      # <--
    glEnable(GL_TEXTURE_2D)

    if not forced:
        glBegin(GL_QUADS)
        for y, surface in enumerate(surfaces):
            for x, vertex in enumerate(surface):
                glTexCoord2f(block[y-1][2*(x-1)], block[y-1][(2*x)-1])
                glVertex3fv(verts(vx,vy,vz,1)[vertex])
        glEnd()

        glDisable(GL_TEXTURE_2D)    # <--
        glColor4f(0, 0, 0, 1)

        glBegin(GL_LINES)
        for edge in edges:
            for vertex in edge:
                glVertex3fv(verts(vx,vy,vz,1)[vertex])
        glEnd()

    # [...]

run = True
while run:
        # [...]

        Cube(0,0,0,BLOCK1)
        Cube(1,0,0,BLOCK1)
        Cube(0,1,0,BLOCK1)
        Cube(0,0,1,BLOCK1)
        Cube(-2,0,0,BLOCK1)

        glDisable(GL_TEXTURE_2D)      # <--

        glColor4f(0.5, 0.5, 0.5, 1)
        glBegin(GL_QUADS)
        glVertex3f(-10, -10, -2)
        glVertex3f(10, -10, -2)
        glVertex3f(10, 10, -2)
        glVertex3f(-10, 10, -2)
        glEnd()

        # [...]


text:
Q: Login screen bumps back to login screen Ubuntu froze, so I had to perform a hard-reboot. But then when I tried to login, all I see is a brief Nvidia splash screen and then it reloads the login screen. I'm completely locked out of Gnome Shell, my normal GUI. I can still login via a text terminal.
I've seen some similar questions like this and this and this but none of the solutions worked for me. My drive isn't encrypted. My home directory has the right permissions. I tried purging all nvidia packages and reinstalling. Nothing's worked. How do I fix this?

A: A similar question recommended looking at ~/.xsession_errors to help the diagnosis. There, I found several "syntax error" messages pointing to the file /usr/sbin/lightdm-session. The syntax errors weren't actually in this file, but this is the script that LightDM uses to load my ~/.profile, ~/.bashrc and ~./bash_aliases files after I login. This step was failing, and apparently the result is that LightDM kicks you back to the login screen without any explanation.
Inspecting these files further, it turns out that at the end of my ~./profile I had the lines:
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

It was the eval command throwing the error, presumably because of some broken or corrupted Ruby install. It's possible I added these lines myself, but I don't remember. Commenting them out allowed me to again login to Gnome Shell.


text:
Q: Can I check if server is up without connecting to it? Is it possible to check if a remote server is up, without connecting to it?
Basically, telnet ip.ad.dre.ss port works, but will connect to the server. Is there an equivalent command, that will just check is the server is up, without establishing a connection with it?
I would like to check it in a bash script.

A: For a local server ss --listening  will list all listening processes.
for a remote server you could connect using ssh and run ss, or test the listening socket(s) directly using nmap
`

A: If your server is a remote server you can not check without connecting to the server. You can only check that by log into the Operating System where that server is running and then you have to use ps -ef | grep [p]rocessName


text:
Q: R ggplot2: plot min, avg, max and fill area between curves My data is of the form:
no  min     avg     max
1   0.000   42.565  30.681
2   50.292  60.203  74.392
3   65.029  73.392  81.939
...

I would like to plot curves of the minimum, average and maximum values and fill the area between the minimum and the average curve and the area between the average and the maximum curve (something similar to the chart below, without the dots). Is this possible with ggplot? Maybe with geom_ribbon()?

A: Like this:
ggplot(data) +
  geom_ribbon(aes(no,ymin=min,ymax=max),color="yellow",alpha=0.5) +
  geom_line(aes(no,avg))


text:
Q: Bit Operation Issue (shifting, masking, ...) Why does this expression always result in -2,147,483,648 (11111111 11111111 11111111 11111111)? I don't get it.
data[] is a byte-Array filled with some values.
(((int)data[29] & 0x00000001) << 31) | (((int)data[30]&0x000000FF)<<12) | (((int)data[31]&0x000000FF)<<4) | (((int)data[32]&0x000000FF)>>>4)

Thanks.

A: I don't think your expression always returns min value of signed int.
if all values in data array were zero, it would return zero.
I also don't think this would result in setting all bits to ones.
Following code (Java) where I use Integer.MAX_VALUE:
int max = Integer.MAX_VALUE;    //(2^31 - 1) - all bits apart from the sign are 1
System.out.print(Integer.toBinaryString(((max & 0x00000001) << 31) | ((max&0x000000FF)<<12) | ((max&0x000000FF)<<4) | ((max&0x000000FF)>>>4)));

returns:
10000000000011111111111111111111

using provided values:
System.out.print(Integer.toBinaryString(
        ((0b00101001 & 0x00000001) << 31) |
        ((0b11111111 & 0x000000FF) << 12) |
        ((0b11111001 & 0x000000FF) << 4)  |
        ((0b11001111 & 0x000000FF ) >>> 4))
);

returns:
10000000000011111111111110011100


text:
Q: UIImageView not show downloaded images after localized iOS app When i localized iOS app . UIImageView not showing images at all , These images i downloaded it from urls .
NOTE: i am using AsyncImageView component .
@implementation CategoryView

+ (CategoryView *)getViewWithTitle:(NSString *)title andImageUrl:(NSString *)imgUrl {

    CategoryView *view = [[[NSBundle getBundle] loadNibNamed:@"CategoryView" owner:self options:nil] objectAtIndex:0];

    [view configureWithTitle:title andImageUrl:imgUrl];

    return view;
}

- (void)configureWithTitle:(NSString *)title andImageUrl:(NSString *)imgUrl {

    [self bringSubviewToFront:_viewBtn];

    self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2;
    self.imageView.clipsToBounds = YES;

    self.categoryTitleLabel.text = title;
    [self.imageView setImageURL:[NSURL URLWithString:imgUrl]];
}

A: As i know you want to access those images downloaded from url will show everytime once it will complete downloading Is it right?
If is like that then i would like to inform you that AsyncImageView only download images into cache asynchronously but it will not store images into disk for long time so you can not able to see images in offline mode into imageView,
for that you need to save all downloaded images into cache memory and need to fetch images from that,
You can use FastImageCache

A: You can try SDWebImage library and it provides an async image downloader with support to caching.
Some of the features listed in the documentation :

Categories for UIImageView, UIButton, MKAnnotationView adding web
  image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache
  expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC


text:
Q: Needing to get an object from an NSDictionary I have an NSDictionary that contains an array. What I am trying to do is get the object inside of the first part of my array photoDictionary:
-(NSString*) getImageAtIndex:(NSInteger *)index andObject:(PhotoPXArray *)photoArray {
    NSDictionary *photosDictionary = [MTLJSONAdapter JSONDictionaryFromModel:photoArray];
    NSArray = [[photosDictionary objectAtIndex:0];
   //NSArray *photoCollection = [MTLJSONAdapter JSONArrayFromModels:self.photoPXArray];

    return @"ff";
}

This should be really simple but I am banging my head against a wall.
My ultimate goal is to get the 'image_url' as shown in this object model:

A: Hot Licks answer was PERFECT!!
NSString* url = photosDictionary[@"photos"][0][@"image_url"];


text:
Q: Arch angle needed. Have, radius, width, rise. I use auto cad everyday, all day. I am trying to create a excel spreadsheet, where you can type in given information and receive missing information, rather than drawing out the arch.
For example, 35.75" wide x 47.75" over all height and a leg height of 41.75".  This would be an arch.
With the given information, the rise is 6", I can do the math and get the radius, radius is 29.625.
Using autocad, I get an "angle" at the top of the leg of 27 degrees.  I am trying to figure out the formula needed to get the 27 degrees
Tried to post a picture but I am to new to do so.
Although it's fine using autocad to do this, I personally would like to know the formula.
And for this life of me I cannot, and I'm sure it's simple enough
Thanks for any and all help