text:
Q: Issues passing array's and calculating the average C++ I have been stuck on this for over a day now. This code is supposed to find the maximum and minimum number of numbers within a text file then output the average of those numbers.  Everything is working fine except for the average.  Its not calculating at all.  I know the issue is that I'm not correctly using my arrays within my find_average function but, for the life of me, I just can't wrap my head around what I'm doing wrong.  Please help.
//  Student:        Tyler Brady
//  Assignment:     5
//  File:           assing5.cpp
//  Input:          Keyboard

#include <iostream>
#include <fstream> // I/O
#include <iomanip> // For setw()
using namespace std;
ofstream outputfile("output.txt");
const int MAX_FILE_NAME = 35;  // Maximum file name length
const int MAX_NUMBER_SCORES = 40;  // Maximum number of values in array
void open_input(ifstream& input, char name[]);                       // Get file name, Open file
void read_values(ifstream& input, double v[], int size, int& used);  // Read values from file
void find_max_min(const double v[], int n, double& max, double& min);// Find max/min in array
void output(const char name[], const double v[], int n,
    double max, double min, double average, ostream &out = cout);            // Print Results

double find_average(const double v[], int n);

int main()
// Parameters: None
// Returns:    Zero
// Calls:      open_input(), read_values(), find_max_min(), output()
{
    char     again;                        // Does user want to go through loop again?
    char     file_name[MAX_FILE_NAME + 1]; // Name of file to be processed
    ifstream input_numbers;                // Input file of doubles
    double   scores[MAX_NUMBER_SCORES];    // Array to hold scores processed
    double   max, min;                     // Maximum and minimum numbers from file
    int      num_scores;                   // Number of scores in file

    double average;

    cout << "This program can find the largest and smallest numbers in a file\n"
        << "of at most " << MAX_NUMBER_SCORES << " floating-point values.\n" << endl;
    system("pause"); // Hold message on screen until key is pressed

    do
    {
        open_input(input_numbers, file_name);    // Get file name & open file
        read_values(input_numbers, scores,
            MAX_NUMBER_SCORES, num_scores);       // Read values
        input_numbers.close();                   // Close file
        if (num_scores > 0)
        {
            find_max_min(scores, num_scores, max, min); // Find max & min values in array
            average = find_average(scores, num_scores);
            output(file_name, scores, num_scores, max, min, average); // Print results on screen
            output(file_name, scores, num_scores, max, min, average, outputfile); // and outputfile
        }
        else
        {
            cout << "\n\n\aNo data in file: " << file_name << endl;
        }

        cout << "\nDo you want to process another file (Y/N)? ";
        cin >> again;
        cin.ignore(256, '\n');  // Remove Enter key from keyboard buffer
    } while (again == 'y' || again == 'Y');

    cout << "\nEnd of Program!" << endl;
    outputfile << "\n\nThanks for using MaxMin!\f";
    outputfile.close();
    return 0;
}  // End of main()

void open_input(ifstream& input, char name[]) //Open file
                                              // Parameters: Variables for input file reference nad input file name
                                              // Returns:    None
                                              // Calls:      None
{
    int count = 0;             // Count number of tries
    do // Continue until we get a valid file name and can open file
    {
        count++;
        if (count != 1)  // Issue error message if we are trying again.
        {
            cout << "\n\aInvalid file name or file does not exist. Please try again."
                << endl;
        }
        cout << "\nEnter the input file name (maximum of " << MAX_FILE_NAME
            << " characters please)\n:> ";
        cin.get(name, MAX_FILE_NAME + 1);// Gets at most MAX_FILE_NAME characters
        cin.ignore(256, '\n');           // Remove Enter key from keyboard buffer
        input.clear();                   // Clear all error flags, if any, from prev try
        input.open(name, ios_base::in); // Open to read only if file exists
    } while (input.fail());            // If can't open file, try again
} // End of open_input()

void read_values(ifstream& input, double v[], int size, int& used) // Read values
                                                                   // Parameters: Variables for file reference, variable for array reference,
                                                                   //             value for array size and variable for number of values in array
                                                                   // Returns:    None
                                                                   // Calls:      None
{
    double value;        // Value from file
    int count = 0;       // Count number of values in file

    while (count < size && input >> value) // Continue as long as there is
                                           // room in the array and we can read
    {
        v[count] = value;                   // a number from file.
        count++;
    }

    used = count;
} // End of read_values()

double find_average(const double v[], int n)
{
    double value;
    double sum = 0;
    int count = 0;

    while (count >> value)
    {
        sum += value;
        count++;
    }
    return sum / count;
}

void find_max_min(const double v[], int n, double& max, double& min) // Find max & min values
                                                                     // Parameters: Variables for array reference, value for number of values
                                                                     //             and variables for max and min values
                                                                     // Returns:    None
                                                                     // Calls:      None
{
    int i;   // Array index and loop counter

    max = min = v[0];

    for (i = 1; i < n; i++) // Start with 1 since max & min initialized to v[0]
    {
        if (v[i] > max) max = v[i];
        if (v[i] < min) min = v[i];
    }
} // End of find_max_min()

void output(const char name[], const double v[], int n,
    double max, double min, double average, ostream& out)
    // Parameters: File name, array reference, number of values and max & min values
    // Returns:    None
    // Calls:      None
{
    int i;  // Array index and loop counter
    out.setf(ios::fixed);
    out.setf(ios::showpoint);
    out.precision(1);
    out << "\n\nInput File Name:         " << name << endl;
    out << "\nFile Contents:" << endl;
    for (i = 0; i < n; )
    {
        out << setw(8) << v[i];
        if (++i % 5 == 0) out << "\n"; // Print only 5 values per line
    }
    if (i % 5 != 0) out << "\n";      // Newline if last line is short
    out << "\nLargest  Number in File:        " << setw(8) << max << endl;
    out << "Smallest Number in File:        " << setw(8) << min << endl;
    out << "Average of Numbers:        " << setw(8) << average << endl;
} // End of output()

A: It is the while loop in the find_average function that is not ok. In the count >> value statement, the variable value is not initialized, so you it's value can be anything (trash), and the shift operator can't be used with double.
You can try this:
while (count < n)
{
    sum += v[count];
    count++;
}
return sum / count;

Or use a for loop:
for (int i = 0; i < n; i++)
{
    sum += v[i];
}
return sum / n;


text:
Q: spring boot suite - independant IDE or is it a plugin for other IDE such as Eclipse I am new to spring boot. One thing that puzzles me is that is spring boot suite a standalone IDE ? i.e. Does it behave like a regular IDE ?
Or is it just an add-on or plugin that must be used in conjunction with an exisiting IDE, e.g eclipse etc ?
Please clarity.
Thank you.

A: The Spring Tools 4 are available as extensions for a number of IDEs, including the Eclipse IDE, Visual Studio Code, and Theia.
For your convenience, we also provide a ready-to-use distribution of the Eclipse IDE with the Spring Tools 4 pre-installed, among a few other useful extensions. This is what most people refer to as the Spring Tool Suite.
So you have the choice to either download one of the mentioned IDEs and install the Spring Tools 4 extensions into them yourself or - in case of Eclipse - download the ready-to-use Spring Tool Suite from https://spring.io/tools (which is the Eclipse IDE + Spring Tools 4 pre-installed and branded).
As a beginner, I would recommend to start with the Spring Tools 4 for Eclipse distribution (aka Spring Tool Suite). As it is a regular Eclipse IDE under the hood, you can instal additional extensions into it in the same way than into a pure Eclipse IDE - in case you want to customize it further at a later point in time.
Hope this explains it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: инициализация int[] по умолчанию Наткнулся на интересную особенность при инициализации массива int.
int arr1[10];
int main() {
    int arr2[10];
    return 0;
}

Все значения arr1 равны 0, а все значения arr2 значениями -858993460 ( мое предположение, что это просто неинициализированная память)
Вопрос такой: почему снаружи main компилятор делает что-то типа этого int arr1[10] = {}; , а внутри не делает ничего?

A: Таковы правила инициализации всех объектов со статическим классом хранения. И в С, и в С++ они подвергаются нулевой инициализации, если вы не предоставили явного инициализатора.
В С++ процесс инициализации существенно более сложен, чем в С, т.к. С++ поддерживает динамическую инициализацию, но к вашему случаю это не относится.
Автоматические переменные тривиальных типов не подвергаются никакой инициализации, если вы явно не укажете инициализатор.


text:
Q: Inverse Laplace Transform with Gamma Function I need to calculate the inverse Laplace transform of $F(s)=\frac{1}{s^\alpha-\lambda}$ where $\lambda$ is a complex number and $\alpha$ is a real numbers.
I know that it is going to envolves the gamma function but I have no idea what to do with that $\lambda$.
Can someone give me any hint?

A: I'll assume $\alpha > 0$, so that we have $\lim\limits_{\operatorname{Re} s \to +\infty} F(s) = 0$, as it should be for the Laplace transform of a function with at most exponential growth. We can expand $F(s)$ into a geometric series,
$$F(s) = \frac{1}{s^{\alpha} - \lambda} = s^{-\alpha}\frac{1}{1 - \lambda s^{-\alpha}} = \sum_{k = 0}^{\infty} \lambda^k s^{-(k+1)\alpha},$$
that converges uniformly on $\mathbb{C}\setminus D_R(0)$ for sufficiently large $R$ (depending on $\lambda$), and apply the inverse Laplace transformation termwise. Since
$$\int_0^{\infty} t^{\beta - 1} e^{-st}\,dt = s^{-\beta}\Gamma(\beta)$$
for $\beta > 0$, we get the series expansion
$$f(t) := \sum_{k = 0}^{\infty} \frac{\lambda^k}{\Gamma((k+1)\alpha)}t^{(k+1)\alpha-1}\tag{$\ast$}$$
for the (potential) inverse Laplace transform of $F$. Now one can verify that the series in $(\ast)$ converges for all $t > 0$ and all $\lambda \in \mathbb{C}$, and that $f(t)e^{-st} \in L^1((0,+\infty))$ for $\operatorname{Re} s$ large enough. The dominated convergence theorem then shows that
$$\mathcal{L}[f](s) = \int_0^{\infty} f(t)e^{-st}\,dt = \sum_{k = 0}^{\infty} \frac{\lambda^k}{\Gamma((k+1)\alpha)} \int_0^{\infty} t^{(k+1)\alpha-1}e^{-st}\,dt = F(s).$$
For $\alpha \in \mathbb{N}\setminus \{0\}$, one can give a closed-form expression of $f$ in terms of $\exp \bigl(\rho_m t\bigr)$, where $\rho_m$ ranges over the possible values of $\lambda^{1/\alpha}$, but for general $\alpha \in (0,+\infty)$ I'm not aware of a nicer expression than $(\ast)$.


text:
Q: Randomly split a given number M into N parts So, the idea that I have, is to be able to divide $2.00 into 10 person, and each of them will receive $x.xx amount of money randomly. (N and M will always be limited to 2 decimals and > 0)
Ex: {0.12, 0.24, 1.03, 0.01, 0.2, 0.04, 0.11, 0.18, 0.05, 0.02}
Currently I have tried:
private static BigDecimal[] randSum(int n, double m)
{
    Random rand = new Random();
    BigDecimal randNums[] = new BigDecimal[n], sum = new BigDecimal(0).setScale(2);

    for (int i = 0; i < randNums.length; i++)
    {
        randNums[i] = new BigDecimal(rand.nextDouble()).setScale(2, RoundingMode.HALF_EVEN);
        sum = sum.add(randNums[i]);
    }

    for (int i = 0; i < randNums.length; i++)
    {
        BigDecimal temp1 = randNums[i].divide(sum, 2, RoundingMode.HALF_EVEN);
        BigDecimal temp2 = temp1.multiply(new BigDecimal(m).setScale(2));
        randNums[i] = temp2;
    }

    return randNums;
}

public static void main(String[] args)
{
    BigDecimal d[] = randSum(5, 2);

    double sum = 0;
    for (BigDecimal n : d)
    {
        sum += n.doubleValue();
        System.out.println(n);
    }
    System.out.println("total: " + sum);
}

But BigDecimals are too confusing and they don't add up. Sometimes the total is 1.98 or 2.01. Doubles doesn't work because of the Double-precision floating-point.
The code was taken from:
Getting N random numbers that the sum is M

A: Let's suppose you need a fixed precision (passed as prec argument):
static public BigDecimal[] split(BigDecimal sum, int prec, int count) {
    int s = sum.scaleByPowerOfTen(prec).intValue();
    Random r = new Random();
    BigDecimal[] result = new BigDecimal[count];
    int[] v = new int[count];

    for (int i = 0; i < count - 1; i++)
       v[i] = r.nextInt(s);
    v[count - 1] = s;

    Arrays.sort(v);
    result[0] = BigDecimal.valueOf(v[0]).scaleByPowerOfTen(-prec);
    for (int i = 1; i < count; i++)
       result[i] = BigDecimal.valueOf(v[i] - v[i - 1]).scaleByPowerOfTen(-prec);
    return result;
}

This approach uses property that Random.nextInt() is uniformly distributed. After sorting, values of v[] array are points by which the whole amount is split, so you generate result using differences between neighboring elements:
[   2,    5,   10,   11, ...,  197,  200]  // v[]
[0.02, 0.03, 0.05, 0.01, ...,  ..., 0.03]  // result[]

Here you operate with integer values, so rounding issues don't bother anymore.

A: I suggest to multiply all the numbers by 100 and rephrase your problem: generate the n random non-negative integer numbers which sum equals to the given m integer number. Later you can divide all the generated numbers by 100 to get what you want. Here's my implementation (similar to @SashaSalauyou version):
private static int[] randSum(int n, int min, int m) {
    Random rand = new Random();
    int[] nums = new int[n];
    int max = m - min*n;
    if(max <= 0)
        throw new IllegalArgumentException();
    for(int i=1; i<nums.length; i++) {
        nums[i] = rand.nextInt(max);
    }
    Arrays.sort(nums, 1, nums.length);
    for(int i=1; i<nums.length; i++) {
        nums[i-1] = nums[i]-nums[i-1]+min;
    }
    nums[nums.length-1] = max-nums[nums.length-1]+min;
    return nums;
}

I also added one more parameter, min which is the minimal wanted number. Set it to 0 if you accept zeros in the answer. Otherwise you may set it to 1 (then after division by 100 the lowest possible number will be 0.01).

A: You can treat this problem as integers, and instead of summing to M, make it sum to 100M.
Do the algorithm, and you will end up with non-integers number, such as 10.345, Now - basically what you would like to do is take the floor value of each number (10 in the above example), and to increase the number to 11 with probability proportional to 0.345.
That can be done by creating the reminder array: rem[i] = value[i] - ceil(value[i]), and choose M - sum{ceil(value[i])} values with replacements, according to the weighted probability of rem array.
Code:
public static BigDecimal[] createRandomSumsTo(BigDecimal M, int n) {
    int m = M.multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).intValue();
    double[] rands = new double[n];
    double sum = 0;
    for (int i = 0; i < n; i++) {
        rands[i] = rand.nextDouble();
        sum += rands[i];
    }
    for (int i = 0; i < n; i++) rands[i] = (rands[i] / sum) * m;
    int[] intVals = new int[n];
    double[] rem = new double[n];
    //create base and reminder array:
    for (int i =0 ; i < n; i++) {
        intVals[i] = (int) Math.floor(rands[i]);
        rem[i] = rands[i] - intVals[i];
    }
    //for efficiently chosing a random value by weight
    double[] aux = new double[n+1];
    for (int i = 1 ; i < n+1; i++) {
        aux[i] = aux[i-1] + rem[i-1];
    }
    //normalize to sum to one.
    for (int i = 0 ; i < n+1; i++) {
        aux[i] = aux[i] / aux[n];
    }
    int intsSum = 0;
    for (int x : intVals) {
        intsSum += x;
    }
    for (; intsSum < m; intsSum++) {
        intVals[chooseWeighted(aux)]++;
    }
    //and create the BigDecimal array:
    BigDecimal[] res = new BigDecimal[n];
    for (int i = 0; i < n; i++) {
        res[i] = new BigDecimal(intVals[i]).divide(BigDecimal.TEN).divide(BigDecimal.TEN);
    }

    return res;

}

private static int chooseWeighted(double[] probabilities) {
    double r = rand.nextDouble();
    int idx = Arrays.binarySearch(probabilities, r);
    if (idx >= 0) return idx-1;
    return (-1*idx) -2;
}


text:
Q: Is there a way to pass multiple 2D arrays to a function in C? I'm implementing the resource allocation algorithm and in that I want computation of the safety sequence to occur in a function outside the main(). So am guessing that I need to pass the Need, Available and MAX matrix to the function.
I've surfed the internet and I can't find a way to pass multiple two-dimensional arrays to a function.
Is it even possible to do so?

A: void function_accepting_2d_array (size_t x, size_t y, int arr [x][y]);

void function_accepting_2_2d_arrays (size_t x1, size_t y1, int arr1 [x1][y1],
                                     size_t x2, size_t y2, int arr2 [x2][y2]);

void function_accepting_n_2d_arrays (size_t n, size_t x, size_t y, int arr[n][x][y]);

Alternatively, in case you don't need to know how many arrays there are:
void function_accepting_n_2d_arrays (size_t x, size_t y, int arr[][x][y]);


text:
Q: Is there a bluetooth camera that works with an iMac? I want to put a webcam in a far corner of my office and use it for Skype.
Do you know of a bluetooth or other wireless camera that will show up on a Mac like a regular camera?

A: What exactly are looking for? A Security Camera? Take a look at BestBuy's, Amazon or the AppleStores camera section. Most USB, Bluetooth or Ethernet cameras should be supported out-of-the-box.
Here are some ideas:
Withings Home HD WLAN  Video Camera

Arlo Netgear Wire-Free

NetCam Wi-Fi Camera with Night Vision


text:
Q: Powershell script to Install SW on VM or host using Application from SCCM 2012..? I am using Orchestrator runbook in which there is a ".net run script" which even runs Powershell script, i have to write a Powershellscript which Query the SCCM 2012 for the SW(given as parameter) and install it on the VM (given as parameter). i have already list of Softwares as an application in the Software Library of SCCM 2012.

A: If you're using Orchestrator a much simpler solution (more in keeping with Orchestrator) would be to install the "System Center Integration Pack for System Center 2012 Configuration Manager" and use the activities defined there:
http://technet.microsoft.com/en-us/library/hh967537.aspxhttp://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=28725
You can either:

*

*Add the machine to an existing collection that already has deployments active for the software you want installing - Use the "Add Collection Rule" activity to add the machine to the correct collection: http://technet.microsoft.com/en-us/library/hh967533

*Create a new collection specifically for the machine and deploy applications to the collection using the "Create Collection" and "Deploy Application" activities: http://technet.microsoft.com/en-us/library/hh967526 and http://technet.microsoft.com/en-us/library/hh967531


text:
Q: How to disable an SVG from duplicating on hover For reference, trying to recreate this portfolio for practice: https://brittanychiang.com/
I'm working with React and I'm trying to make this SVG change color and move up a few pixels. So far, it works. However, when I hover over the SVG, it ends up duplicating. Leaving behind the original svg while also changing the duplicates color and moving it up a few pixels.
I have tried adding a background color but no luck, doesn't seem to show.
hover effect
.effect {
    transition: transform 1s ease,  stroke .5s ease;
}

.effect:hover {
    stroke: #64FFDA;
    transform:translateY(-10px);
}

SVG animation
const SocialIcons = (props) => {
    return (
        <Icons>
            <motion.div
            initial={{transform:"scale(0)"}}
            animate={{scale:[0,1]}}
            transition={{type:'spring', duration:1, delay:1}}
            >
                <NavLink style={{color:'inherit'}}  target="_blank"   to={{pathname:"https://github.com/SiriusVisuals"}}>
                    <Github class="effect" width={20} height={20} />
                </NavLink>
            </motion.div>
            <motion.div
            initial={{transform:"scale(0)"}}
            animate={{scale:[0,1]}}
            transition={{type:'spring', duration:1, delay:1.4}}
            >
                <NavLink style={{color:'inherit'}}  target="_blank"   to={{pathname:"https://www.linkedin.com/in/taylenschmaltz/"}}>
                    <LinkedIn class="effect" width={20} height={20} />
                </NavLink>
            </motion.div>

            <Line color={props.theme}

initial={
    {
        height:0
    }
}
animate={{
    height: '8rem'
}}
transition={{
    type:'spring', duration:1, delay:0.8
}}
            />
        </Icons>
    )
}

export default SocialIcons

SVG data
export const LinkedIn = (props) => {
  return (
    <svg
      aria-hidden="true"
      data-prefix="fas"
      data-icon="link"
      className="feather feather-linkedin"
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      stroke-width="2"
      fill="none"
      role="img"
      stroke="currentColor"
      stroke-linecap="round"

      {...props}
    >
      <path
        d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"
      />
      <rect x="2" y="9" width="4" height="12"></rect>
      <circle cx="4" cy="4" r="2"></circle>
    </svg>
  );
};

Here you can see my SVG duplicating.
I added more info, honestly, nothing outside of this is relevant. SVG data shows what contents belong to "LinkedIn". SVG animation refers to the icons loading into the webpage on initial load. Also shows the dedicated path, and defined width/height. Finally, the hover effect shows what I applied to have this SVG change colors and move up a few pixels.


text:
Q: FileMaker Missing Function Set Variable [$var1; Value: Get(ScriptParameter) & " "]
Set Variable [$Clip; Value: <Function Missing>(1;$SP)]

I realize that a plug in that is no longer installed with my version of Filemaker is causing this function to be missing. Could someone direct me to any potential plugins or functions that would replace this <Function Missing>
The script above is the entire script. There is no documentation. The $SP variable is probably the data within a certain column and row in my layout, and the goal of the script is to copy data from that column/row to the clipboard

A:
Could someone direct me to any potential plugins or functions that
  would replace this
There is no documentation. The $SP variable is probably the data
  within a certain column and row in my layout, and the goal of the
  script is to copy data from that column/row to the clipboard.

If by that you mean copy the contents of a given field to the clipboard, this can be done natively by using the Copy script step, e.g.:
Copy [Select; YourTable::SomeField]

Note that this requires the target field to be placed on the current layout. The data copied will come from the current record (or from the first related record in the YourTable table, depending on the context of the current layout).
Alternatively, there are several plugins that offer a similar functionality with less restrictions (i.e. they can place data directly onto the clipboard). It would be helpful if you explained what your limitations are here - since you obviously used one of these and now you don't.

A: The function is SetClipboardData and the plugin for it is ScriptMaster. Make sure to install the SetClipboardData Module in your customized scriptmaster plugin.


text:
Q: Ubuntu Server 20.04 network-manager not starting VPN automatically I am getting desperate here. I need to connect a Ubuntu Server Machine on a VPS to a network to monitor several machines. I can only connect to the network with L2TP over IPsec.
I have tried installing the GUI on the Ubuntu Server, changing Netplan to use Network Manager as renderer, but this way I can't manage to get the VPN connection starting automatically on boot. I cannot start the GUI tool sudo nmcli-connection-editorfrom VNC because it fails to start a GUI applet with privileges.
The only option I have found is to use nmcli editor over ssh with sudo nmcli c edit netplan-01-eth0 and trying to set the connection.secondaries value to the UUID of the "myvpn" connection.
This doesn't work as rebooting the VPS just removes the value of connection.secondaries back to an empty value.
I need a solution to keep the VPN always up, regardless of disconnections from the VPN Server (similar to DPD in Strongswan) and to reboot.
I would love to use strongswan, but I cannot make swanctl to work.


text:
Q: Error using IF statement in MySQL I'm trying to create a mySQL Script file, so i can easily execute my changes in differente databases, but I'm having problems with a IF statement. (I'm using MySQL Workbench).
CREATE TABLE IF NOT EXISTS `build` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `Version` varchar(20) NOT NULL,
    `Date` datetime DEFAULT NULL,
    PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

IF EXISTS(select 1 from build where Versao = '1.1') THEN select "yes";

The create table sentence is executed correctly, but the "IF Exists(select..."  statement is giving the following error:
SYNTAX ERROR: IF (if) is not a valid input at this position
The select "Yes" command will actually be replaced by an insert command. I'm just trying to test if the IF command will work.
I've also tried to put the IF EXISTS(select line in a separated query, but had the same result.
What am I doing wrong?

A: The SQL IF function as I imagine you want to use should be used inside a function, which you never declared.
If you want a standalone query which will behave the way you expect, then you can try this:
SELECT CASE WHEN EXISTS (SELECT 1 FROM build WHERE Versao = '1.1')
            THEN "yes"
            ELSE "no"
       END
LIMIT 1

A: SQL functions can only be used inside a statement or inside a stored procedure/routine.
This SELECT statement should work for you:
SELECT IF(EXISTS(SELECT 1 FROM build WHERE Versao = '1.1'), 'yes', 'no') AS test;


text:
Q: SDL - Can't close program even using the task manager The program compiles 'correctly'(.exe file appears) but it can't be closed even when I shutdown my laptop(task manager doesn't work too). The only way to close it is turning off. What's wrong? Also, Code::Blocks displays this when I compile project:
Running project post-build steps
XCOPY (invalid)\bin\*.dll bin\Debug\ /D /Y
ЌҐ  ©¤Ґ д ©«: *.dll
'Є®ЇЁа®ў ® д ©«®ў: 0.
Process terminated with status 4

A: Given that no information, I'm guessing you have the main loop in your program  but you didn't use the SDL_Quit enumerator in your main loop to check if you try to quit your program (alt + f4 and 'X' etc.) Basically a simple SDL application should look like this:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <SDL.h>

int main (int argc, char* args[] )
{

 SDL_Event event;
 bool exit = false;

 SDL_Window *window = SDL_CreateWindow ("title",
                                        SDL_WINDOWPOS_CENTERED,
                                        SDL_WINDOWPOS_CENTERED,
                                        1000,
                                        500,
                                        SDL_WINDOW_SHOWN)

 while(exit == false)
 {
  while(SDL_PollEvent(&event) >= 0)
  {
     if(event.type == SDL_Quit)
     {
      exit = true; // when this becomes true, the program terminates
     }
     //other events goes here
   }
 }
  SDL_DestroyWindow(window);
  SDL_Quit();
}

see if this code works in your computer.


text:
Q: Timeout on an execfile call function for windows? (Signal Alternative?) Pretty much as the title says, I'm trying to run some execfile calls but I am looking for a timeout option so that if my called script takes over ten seconds to run then it will kill the called script and continue...
The signal library/package is only for UNIX, I'm on windows so I'm a little stuck.
# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

# Semi-Sequential (Don't wait for it to finish before moving onto the third script)
subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True)

# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TEST.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

Any ideas?

A: Something like this should work:
# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

# Semi-Sequential (Don't wait for it to finish before moving onto the third script)
p1 = subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True)

# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TEST.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

#Do you want to kill the "pythonw", "SUBSCRIPTS/TEST.py", "0" command after the "SUBSCRIPTS/TEST.py" call or do you want to allow the pythonw command to continue running until after the "SUBSCRIPTS/TESTSCRIPT.py"

#you need to put this code depending on where the subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True) #script needs to be killed
currentStatus = p1.poll()
if currentStatus is None: #then it is still running
  try:
    p1.kill() #maybe try os.kill(p1.pid,2) if p1.kill does not work
  except:
    #do something else if process is done running - maybe do nothing?
    pass

# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

#or put the code snippet here if you want to allow the pythonw command to continue running until after the SUBSCRIPTS/TESTSCRIPT.py command

s


text:
Q: \end{enumerate} error \documentclass[14pt]{extarticle}
\usepackage{lineno}
\linenumbers
\usepackage[utf8]{inputenc}
\usepackage{lipsum}
\usepackage{enumitem}
\usepackage{enumerate}
\usepackage{sectsty}
\usepackage{titlesec}
\titleformat*{\section}{\Large\bfseries}
\sectionfont{\fontsize{}{15}\selectfont}
\setlist[enumerate]{itemsep=0mm}
\usepackage[danish]{babel}
\begin{document}
\author{TEXT}
\title{TEXT}

\maketitle
    \section*{TEXT}
\begin{enumerate}[{1.}1]
    \item \textbf{TEXT}
    \begin{enumerate}[{1.1.}1]
        \item TEXT
        \item TEXT
        \item TEXT
        \item TEXT
        \begin{itemize}
            \item TEXT
            \item TEXT
            \item TEXT
        \end{itemize}
        \item TEXT
    \end{enumerate}
        \item \textbf{TEXT}
                \begin{enumerate}[{1.2.}1]
                    \item TEXT
                \end{enumerate}
        \item \textbf{TEXT}
                \begin{enumerate}[{1.3.}1]
                    \item TEXT
                \end{enumerate}
\end{enumerate}

Hi I have this text writen but TeXstudio Gives me the following errors:
- Undefined control sequence. \end{enumerate} OR
- Missing number, treated as zero. \end{enumerate} for the lines with the \end{enumerate} code
- Package sectsty Error: The sectsty package doesn't work with(sectsty) this document class. scrartcl, scrbook, and scrreprt.}

A: You shouldn't mix the use of enumitem and enumerate since their interfaces differ and are conflicting.
Perhaps you're after this type of layout:

\documentclass{extarticle}
\usepackage{enumitem}
\setlist[enumerate]{itemsep=0mm}
\begin{document}

\section{TEXT}

\begin{enumerate}[label=\thesection.\arabic*]
  \item \textbf{TEXT}
  \begin{enumerate}[label*=.\arabic*]
    \item TEXT
    \item TEXT
    \item TEXT
    \item TEXT
    \begin{itemize}
      \item TEXT
      \item TEXT
      \item TEXT
    \end{itemize}
    \item TEXT
  \end{enumerate}
  \item \textbf{TEXT}
  \begin{enumerate}[label*=.\arabic*]
    \item TEXT
  \end{enumerate}
  \item \textbf{TEXT}
  \begin{enumerate}[label*=.\arabic*]
    \item TEXT
  \end{enumerate}
\end{enumerate}

\end{document}

The label* key uses the higher level label as part of its label.


text:
Q: AssertionError caused by pyinstaller when creating an executable I'm trying to create a .exe file from a .pyw python file using PyInstaller.
I am using the command pyinstaller --onefile sysTray.pyw but I am always getting an AssertionError I read around to try and debug the error but couldn't arrive at a conclusion. These are the last few lines before the error.
File "c:\users\elkha\anaconda2-32\lib\site-packages\PyInstaller\archive\writers.py", line 370, in add
code = get_code_object(nm, pathnm)
File "c:\users\elkha\anaconda2-32\lib\site-packages\PyInstaller\building\utils.py", line 545, in get_code_object
co = _load_code(modname, filename)
File "c:\users\elkha\anaconda2-32\lib\site-packages\PyInstaller\building\utils.py", line 521, in _load_code
assert loader and hasattr(loader, 'get_code')
AssertionError

My ultimate goal is to then use innosetup to create an installer for the application. I was using py2exe before the complete this task but I also ran into problems so I decided to switch to pyinstaller but it seems that there are issues with pyinstaller as well.
Any help would be appreciated.
I have Anaconda Python 2.7 (32-bit) and I installed PyInstaller 3.2 from their website


text:
Q: SQL INSERT or UPDATE in statements I'm new to SQL and I want to create an INSERT or Update query for my webpage. I have two buttons, Status and Shipped, next to every item. If the user presses one of these buttons, it calls a php file with a query. But I really dont know how to put together these 2 queries into 1.

Items
STATUS
SHIPPED

Item1
STATUS
SHIPPED

Item2
STATUS
SHIPPED

Item3
STATUS
SHIPPED

Status Button
   IF status NOT EXIST WHERE user_id = 17 AND item_id = 5
    THEN INSERT INTO table1 VALUE (status = 1) WHERE user_id = 17 AND item_id = 5
    BUT, IF shipped = 1 AND status = 0 WHERE user_id = 17 AND item_id = 5
        THEN UPDATE table1 SET status = 1

Shipped Button
 IF shipped NOT EXIST WHERE user_id = 17 AND item_id = 5
    THEN INSERT INTO table1 VALUE (shipped = 1) WHERE user_id = 17 AND item_id = 5
BUT, IF staus = 1 AND shipped = 0 WHERE user_id = 17 AND item_id = 5
    THEN UPDATE table1 SET shipped = 1

Query to filter out non essecial rows
IF status = 0 AND shipped = 0 WHERE user_id = 17 AND item_id = 5
    THEN DELETE row WHERE user_id = 17 AND item_id = 5

Thank you!


text:
Q: Allow Multiple JARs to Access Same Classes I am working on a game which has three components: A launcher (to keep everything up to date and authenticate players), the game itself, and a server (which allows for multiplayer). All three of these use a few common classes (utilities, GUI themes, an XML library I wrote). The server and game are both started from the launcher, so can I put these classes in only the launcher and have the game and server be able to access them?
Right now, I'm loading the server and game by using a Process with java -jar.

A: You can specify the classpath for every JVM you launch.  In your case, I would separate common functionality (if you have not done so yet) into a single jar (say utils.jar) and make sure to include it in the classpath of every process.  For example:
-- Start the server
java -cp server.jar;utils.jar game.Server

-- Start the launcher
java -cp client.jar;launcher.jar;utils.jar game.Launcher

Does it fit your needs?


text:
Q: Unable to Change Scopes in UWP Sample Microsoft Graph I am using this UWP sample:  https://github.com/microsoftgraph/msgraph-training-uwp
It demonstrates Microsoft Graph, A service for allowing useres to login to apps with their microsoft account so that the app can access the users granted data. By default, the sample requests the calandar's scope, to veiw calandar data, but I would like to edit the sample to access the scope of the user. This is because my app uses in app purchases, and is on a public machine, and I want what users do to be tied to their accounts.
However whenever I try to change the scope of the sample, the app doesnt work correctly, or it crashes. Is there something I'm missing? or is there some way to change the scope?

A: You can add User.Read scope to your application in the app registration in portal.azure.com. Next time you run the app and sign in , it should ask you to consent this new permission.
Then in your code you can change it to call /me rather than /me/events. It will return the users profile data like shown in Graph Explorer here https://developer.microsoft.com/en-us/graph/graph-explorer?request=me/&method=GET&version=v1.0&GraphUrl=https://graph.microsoft.com
The tutorial is also easier to follow here https://learn.microsoft.com/en-us/graph/tutorials/uwp


text:
Q: Generic Map with Lists of Comparable I want a Map with several lists, each of them composed of Comparable objects, but not always the same, so there might be a List of Doubles and a List of Strings, etc...
Map<String, List<Comparable<?>>>
Unfortunately the Map as defined above will not be useful because the elements in each List can't be compared. Therefore I had to cheat and introduce a type parameter to the class:
class MyClass<T extends Comparable<? super T>> {
    Map<String, List<T>> myMap;
}

This is not totally correct because not all lists are of the same type. But it works, the only thing I have to do is to do a type cast to T when I add a Double to a list of doubles or a String to a list of strings. I make sure that each type gets added only to lists of the correct type.
Is there a better way to solve this problem?
The alternative is to have one Map for every type of List. But this just would make the code uglier and the only thing I do with the lists is to sort them and insert them into a DB as String values, therefore I only call toString on the comparables.

A: You can use List<Object> to make it generic and this purpose.
You might want to do instance of checks for some specific datatypes inside list.
Map<String, List<Object>> map = new HashMap<>();

List<Object> list;

list = new ArrayList<>(Arrays.asList(new Object[] { 1, 2, 3.45, "dev", 'A', true, false }));
map.put("key1", list);

list = new ArrayList<>(Arrays.asList(new Object[] { false, 100, 5.1234f, "user", 'Z', true }));
map.put("key2", list);

for (Map.Entry<String, List<Object>> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

Output:
key1 => [1, 2, 3.45, dev, A, true, false]
key2 => [false, 100, 5.1234, user, Z, true]

A: From the docs of java generic wildcard it says:

In generic code, the question mark (?), called the wildcard, represents an unknown type.

And also:

The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

So if you have the following declaration:
List<?> list = new ArrayList<>();

Then you can't add anything to list, because you just told compiler that "I don't know the type of objects which are going to be put in list"
So your code List<Comparable<?>> means that "I want a list to contains comparable objects, but I don't know its type", which is not OK for compiler, because the compiler do need to know the type info for its work.
To use list contains any Comparable objects, you can use upper bounded wildcards like:
Map<String, List<? extends Comparable>> map = new HashMap<>();

Then you're fine to put any comparable list as value for this map:
public static void main(String[] args) {
    Map<String, List<? extends Comparable>> map = new HashMap<>();
    List<Integer> as = new ArrayList<>();
    as.add(1);
    as.add(5);
    as.add(3);

    map.put("as", as);

    List<String> bs = new ArrayList<>();
    bs.add("hello");
    bs.add("world");
    bs.add("generics");

    map.put("bs", bs);
}

Finally I guess you'll be interested in inheritance and subtypes in generics, hope this could be helpful to you.

A: This is looking a bit like a heterogeneous map. What are you actually going to do with your list of comparables other than compare them?
However, if you want the lists to be of different types, then the indirection should be around the List.
public final class SortableList<T extends Comparable<? super T>> {
    private final List<T> elements;
    public SortableList(List<T> elements) {
        this.elements = elements;
    }
    public List<T> elements() {
        return elements;
    }
}

...

Map<String,SortableList<?>> sortables;
...
Comparable<?> colaMax = Collections.max(sortables.get("shirley").elements());


text:
Q: Python scikit-learn: How do I convert decision tree leaves to dummy variables? I am using scikit-learn DecisionTreeClassifier to build a decision tree.  Assume that a given decision tree has 6 leaf/terminal nodes (A, B, C, D, E and F).  I now want to assign the original records coded as to which leaf/terminal node they would belong to (think of it as a form of feature engineering).
I would prefer not to score the records directly, but instead to build a collection of dummy variables from a variety of trees into a feature engineering pipeline.
Does anyone know of any easy approach for doing this?

A: Something similar is implemented under ensemble.RandomTreesEmbedding. Note that n_estimators denotes the number of decision trees.
See docs here.


text:
Q: Use Stoke's Theorem to evaluate the line integral. Use Stoke's Theorem to evaluate the line integral
$$\oint_C (y + 2z) dx + (x + 2z) dy + (x + 2y) dz$$
where $C$ is the curve formed by intersection of the sphere $x^2+y^2+z^2=1$ and plane $x+2y+2z=0$.
I have done it this way...
z=-x/2-y
So n=(-gx(x,y),-gy(x,y),1)
   n=(1/2,1,1)
CurlF=(0,1,0)
so  CurlF.n=1
For evaluating surface integral I have used polar coordinates and answer turned out to be pi which is not correct answer.
I want to know what is wrong in my steps.

A: You need to be sure to use a unit normal. Since $\text{curl }F\cdot n$ is constant, you'll just get a constant times the area of the disk. No parametrization or explicit integration needed.
By the way, it's easier to get the normal directly from the linear equation $a\cdot x=0$: We get $a=(1,2,2)$, and so $n=(1,2,2)/3$.


text:
Q: Set include path with environment variable value We are trying to use the MITK library with Qt on Linux.
Unfortunately MITK has no install functionality and it also depends on ITK and VTK. So we end up with header files scattered in many directories.
We would like to specify the list of directories to add in the include path in an environment variable like this : INCPATH+=$MITK_INCLUDE_PATH. But this doesn't seem to work.
How could we achieve this? Is there a better way?

A: Have you tried adding:
INCLUDEPATH += <the path to the MITK headers>
in your project's .pro file ?
And possibly you'll also need to edit LIBS and DEPENDPATH.
See QMake Manual

A: I think there's a cleaner way to do this, but I can't remember.  Anyway, you could use the system directive:
INCLUDEPATH += $$system( echo $MITK_INCLUDE_PATH )

You may also want to add it to depend path:
DEPENDPATH += $$system( echo $MITK_INCLUDE_PATH )

A: Just found out the solution myself. Though I granted a point to Aidos and cjhuitt for their answers that put me on the right track and saved me valuable time. A special thanks for the link to the qmake documentation.
The first point is that I should modify the .pro file and not fiddle with the extended build arguments.
To get the content of an environment variable when qmake is processed one should use the following syntax
INCLUDEPATH += $$(MITK_INCLUDE_PATH)
Note that to get the content of an environment variable when make is processed one should use the following syntax
INCLUDEPATH += $(MITK_INCLUDE_PATH)
But this won't have the same effect if the environment variable contains multiple paths. The first form is then preferable.
Paths in the environment variable must be separated by spaces because the ; is not recognized.
If a path contain spaces, put quotes around it. Spaces appearing between the quotes will be replaced by '\ '.

A: i dont know but maybe you can try to write like
INCPATH+=%MITK_INCLUDE_PATH%
in windows, generally it is like that..
but i did not try.


text:
Q: How to convert a char to a boolean in Java? I would like to display on the screen a question with two options (Are you married: y/n). The user would have to press or "y" or "n". After that I would like to print on the screen "married" or "not-married".
I've thought in using a char to get the input thorough the Scanner class (System.in) and after cast this char to a boolean type in order to display two options with an if statement. The problem is that I don´t know how to cast this char to a boolean type. Does it make sense? Is there other way to do this example in a different way?
Many thanks

A: Yes, the way you trying to do is doesn't make scenes. You can do as following
Scanner sc=new Scanner(System.in);
String st=sc.nextLine();
if("y".equalsIgnoreCase(st)){
  // married
}else if("n".equalsIgnoreCase(st)){
 // not married
}

A: I think an enum would be a good way to go.  Encapsulate the rules inside your objects.
Binding user responses to objects is a view responsibility.  Is the input a dropdown or text box?
Marital status is an interesting one.  There are more flavors than "yes/no": single, married, divorced, separated, Kardashian, etc.
public class MaritalStatus {
    MARRIED, NOT_MARRIED;
}

A: Very simple:
boolean isYes = (inputChar=='y' || inputChar=='Y');

You could also convert the char to upper/lower case so you would not need ||. Depends on how many tests you have, if it's worth it.
And those parenthesis are not really needed in this case, as || has a higher precedence than assignment, but I personally find it clearer when "condition" like that is enclosed in parenthesis.

A: You cannot simply cast char to boolean, but you can compare it to 'y' and 'n'
public static boolean charToBool(char c) {
    // c = Character.toLowerCase(c);
    switch (c) {
        case 'y':
            return true;
        case 'n':
            return false;
        default:
            throw new IllegalArgumentException("Must be either 'y' or 'n'.");
    }
}

A: You can't cast a character into a boolean value, because how should the program know that 'y' means true and 'n' means false?
Use an if statement
bool married = false;
if(input.equalsIgnoreCase("y"))
    married = true;

I bet a simple google search would have helped you with your homework.


text:
Q: Discord vs bot 13 not able to assign roles giving error Cannot read properties of undefined (reading 'guild') I am using discord js v13.6. I have written in my code where after using a slash command user is assigned many roles which are stored in a array named rolenumber. The problem is I am getting this error every time
 await client.users.fetch(memberId).then((user,interaction) => {
            user.send("Give me a few moments while I verify your details");
            (async function(user){

            let RoleArray = rolenumber.split(",");
            //let guild = client.guilds.cache.get(guildNumber);
            //let member = await client.users.fetch(msg);

            for(let num of RoleArray) {
                //console.log("Roles Inside a for loop",num);
                let role = interaction.guild.roles.cache.get(num);
                let data = await user.roles.add(role).catch(console.error);
                //user.roles.add(num).catch(console.error);
            }

            let welcomeMessage = 'Welcome <@'+ user.id +'>, you are now officially part of channel.';
            const channelMessage = await client.channels.cache.get(channelNumber);
            channelMessage.send(welcomeMessage);
        })();

here the guildNumber is a guild Number which is hidden for security reason from the question.  I am getting this as error message:

let role = interaction.guild.roles.cache.get(num);
                                       ^

TypeError: Cannot read properties of undefined (reading 'guild')

at E:\OutscalGit\DiscordBot\index.js:200:44
at processTicksAndRejections (node:internal/process/task_queues:96:5)

A: interaction is undefined
Are you sure, interaction is passed to here?
you can use it but it not perfect
let role = interaction?.guild?.roles?.cache?.get(num);

A: Promise.prototype.then's fulfillment callback only takes 1 argument.
await client.users.fetch(memberId).then((user) => {
            user.send("Give me a few moments while I verify your details")
            // ...
})

Assuming interaction is already defined above, it should work


text:
Q: Startup program stuck windows loading I've made an application which needs to run a certain process at Windows startup. I've created a method which does it by receiving the path to the program and adding it to the registry. This is the method:
private void AddPathToStartUpPrograms(string path)
{
  string startUpPosition1 = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
  string startUpPosition2 = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  RegistryKey k = Registry.LocalMachine.OpenSubKey(startUpPosition1, true);
  if (k != null)
  {
    k.SetValue("service", path);
  }
  k = Registry.LocalMachine.OpenSubKey(startUpPosition2, true);
  if (k != null)
  {
    k.SetValue("service", path);
  }

}

This code is working but the problem is that it seems that the process I'm adding make the desktop loading get stuck. When the desktop is loading it loads the background wall paper but the icons won't load. I can get to the task manager and when I close the process I've added to the start up programs, the desktop "unfreeze" and finishes loading everything.
What is strange that even though I close the process, after the desktop finish loading, my process runs again and then everything is ok, meaning it for some reason run itself twice.
So my question is how do I set the process to run only AFTER the desktop finished loading?

A: It runs twice because you're setting the registry key in both Run and RunOnce. If you want it to run each time, just set it in the Run key. The RunOnce key is just for programs that you want to (as the name implies) run only once. The registry entry is automatically removed from RunOnce after the OS starts.
If you want to delay the program until the shell has started up, the easiest way (although a bit hacky) is to just put a Thread.Sleep(60000) at the very start of the the program.
If you want a more sophisticated solution, have a look here: C# - How to know when Windows is "settled" after startup?

A: What was told about the RunOnce is true and the solution was to simply remove the addition to that registry key. After I've removed it and left the path only in the "Run" key, it was fixed.


text:
Q: Magento 2 Functional Testing using Phantom JS (or other headless) Curious as to if there is a way to configure the functional testing xml, in order to allow for other web-drivers such as Phatomjs? I already know of the way to change them to Chome and Firefox, but looking for a headless solution if at all possible in this scenario.

A: I attempted this for a few hours, with limited success. I did successfully run the tests, though the first handful failed, so I just terminated the test. I followed this guide: Dev Docs - Introduction to the Functional Testing Framework.
You will notice that the functional tests use a combination of Selenium and PHPUnit. So, I found that the wealth of advice pertaining to Selenium also applied to the M2 functional tests. For instance, this thread seems relevant. Selenium also offers a guide on their site.
I would recommend trying to configure the tests for "normal" execution first - that is, not headless, just in your desktop environment. Once that is working, then I would set my sights on the headless execution. Yeah, phantom.js could potentially apply. The method I found was using Xvcb (X virtual frame buffer). You can initialize this from the command line, but my understanding is you are creating a separate X display, so it's as if Firefox actually is running with a GUI. However, you can't see it, though theoretically I suppose you could "connect" to that X display.
Good luck. I found the documentation pretty thorough, even though I couldn't ultimately get the tests to pass.


text:
Q: How to hide the menu bar under the editor window in PyCharm I'm not sure what's it called, but there is a bar window underneath the editor window, above the Debug/Terminal/Console windows, which shows on what indent / frame / layer you are currently at (with the cursor).
It's pretty redundant to me and catching up a full wide-screen line for me..

See that line:
Level1 > Level2() > Level3() > for Level4 in range(5)

How do I get rid of it?

A: The breadcrumbs in the editor can be enabled or disabled, per language, checking the box at File > Settings > Editor > General > Breadcrumbs > Show breadcrumbs.
Placing the breadcrumbs at the top or bottom of the editor can be adjusted on the same page choosing Placement option with Top or Bottom.
This is shown in the below screenshot, see also the PyCharm documentation Breadcrumbs


text:
Q: simplest cell addition formula on column in libreoffice 5 sharing as an example. I have data starting from column b2 to b8 where I want to add the values (sum) and get the output in another cell, say b10.
The most logical way should have been =SUM(B2,B8) but using that formula I get the output as 0. I tried various other options, ways but get different error numbers. I used to do similar in Excel way back and that used to work. What am I doing wrong ?
Update: Doing =SUM(B2:B8) also gives 0 (zero), same as before.
Update 2 :- It seems (for some reason) libreoffice is thinking/seeing the number as text values. I had put the same query in libreoffice mailing list and one of the private mails said to use View > Value Highlighting and sure enough all were in black which means libreoffice thinks that the numbers are text values. I didn't get any answer as to how to change from text values to 'true numbers'. The numbers are like 3,94,700 and so on and so forth.

A: You need to specify the range:
=SUM(B2:B8)

(in B10).
As explained by Mark Stewart, SUM(B2,B8) is equivalent to B2+B8 — you'd use that form of SUM() if you had a specific list of disjoint cells to add (or disjoint cell ranges).

A: Try this:

*

*In cell C2 enter 2 and in cell C3 enter 3.

*In cell C4 enter =SUM(C2:C3).

The result (which I tested to make sure) should show as 5.
If this worked, then check what is in B2 through B8 to make sure that they are all numbers and that they add up to an integer other than zero.
For example, one way to end up with 0 is by summing 0.1 and 0.2 and then formatting the result as an integer.  It will be rounded down to zero.  To see if this may be the problem, go to Format -> Cells and see what format is being used.
Also, make sure that the values in the cells are numbers, not strings.  In contrast to a language like Perl, summing '1' and '2' results in 0 in Calc.
EDIT:
Since it sounds like the numbers have somehow been entered as text, you can get their numeric values by using INT().  For example:

*

*In cell D2 enter ="5", which results in a string.  (Typing simply '5 should be a text value as well, but this did not seem to work on my version of LibreOffice.)

*In cell D3 enter =INT(D2) to get the numeric value.

You can then use D3 in sums.

A: Try switching the commas , in your numbers to dots ..
LibreOffice probably expects to see dots because the information from your pc is telling it that in the chosen country, dots are used to separate the thousands and commas define the decimal point, so it thinks your numbers have multiple decimal points and since this is not possible it sees them as text.
In most of europe (I think) numbers are formatted like this 578.120,5.
I am in europe and had pretty much the same problem as you.
P.S You can see what libre office thinks the value of a cell is be going to View and enabling Value Highlighting. The values shown in black are text whereas blue means the value is a number.


text:
Q: how to fix the SQL Error [1093] and Error [1064]? I am getting this error
SQL Error [1093] [HY000]: You can't specify target table 'id_card' for update in FROM clause

for my this query
update id_card set id_card_status= 'ACTIVE' where code in (select code from ID_CARD ic
left join PROJECT p on p.PROJECT_code=ic.project   and ic.VERSION =p.current_id_card_version
where ic.project_type in (670 ,671 ,672 ,673) and ic.id_card_status ='DRAFT')

After searching here I rewrite the query like this
update id_card as table_1, (select code from ID_CARD ic
left join PROJECT p on p.PROJECT_code=ic.project   and ic.VERSION =p.current_id_card_version
 ) as table_2
where table_1.code = table_2.code
and table_1.project_type in (670 ,671 ,672 ,673)
and table_1.id_card_status ='DRAFT'
Set table_1.id_card_status = 'ACTIVE'

But I got another error
 SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL
    server version for the right syntax to use near 'where table_1.code = table_2.code
        and table_1.project_type in (670 ,671 ,672 ,' at line 4

How can I re-write this  ?

A: Check the syntax for multi-table UPDATE in MySQL. This syntax is non-standard, so different vendors implement it differently.
https://dev.mysql.com/doc/refman/8.0/en/update.html says:

Multiple-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET assignment_list
    [WHERE where_condition]

So the SET clause goes before the WHERE clause.

It's not an error, but I encourage you to use ANSI SQL 92 JOIN syntax consistently, not comma-join syntax. It will help you avoid some weird surprises with respect to operator precedence.


text:
Q: How to plost the elements of a list - Python I want to count the most 10 most frequent amenities from my dataframe thus I executed this command
x = collections.Counter(listings_amsterdam['amenities'].str.split(',').explode('amenities')).most_common(10)

As output I am getting this:
[(' "Wifi"', 18122),
 (' "Essentials"', 17698),
 (' "Heating"', 17067),
 (' "Kitchen"', 15022),
 (' "Washer"', 13487),
 (' "Hangers"', 13375),
 (' "Smoke alarm"', 12836),
 (' "Iron"', 12544),
 (' "Shampoo"', 12443),
 (' "TV"', 10846)]

I want to plot this but I don't know how. I tried the command x.plt.bar() or plt.bar(x.keys(),x.values()) but nothing of this worked.

A: import matplotlib.pyplot as plt
plt.bar( [i[0] for i in x], [i[1] for i in x])
plt.show()

produces

A: Try the below code:
import matplotlib.pyplot as plt

x = [(' "Wifi"', 18122),
 (' "Essentials"', 17698),
 (' "Heating"', 17067),
 (' "Kitchen"', 15022),
 (' "Washer"', 13487),
 (' "Hangers"', 13375),
 (' "Smoke alarm"', 12836),
 (' "Iron"', 12544),
 (' "Shampoo"', 12443),
 (' "TV"', 10846)]

x_val = [x[0] for x in data]
y_val = [x[1] for x in data]

plt.bar(x_val,y_val)
plt.show()

x is a list and not a pyplot object. So you should pass the values of x in plt object.


text:
Q: How can i execute a job properly with rails? The routes are like this:  get:'/hi', to: 'tables#execute'
I have this controller but I don't know how can I execute it
class TableController < ApplicationController
  def execute
    CurrentJob.set(wait: 2.minutes).perform_later(self)
    render plain: 'OK'
  end
end

I am getting the below error:
ActiveJob::SerializationError in TableController#execute

Unsupported argument type: TableController

Note: I have modified my controller like this:
def execute
    CurrentJob.perform_later params[:name]
    render plain: 'OK'
end

Let me know how to execute it.

A: perform_later takes what you want to pass along to the job. These are passed to the job's perform method. It only takes certain types which it knows how to serialize.

By default the arguments must be either String, Integer, Float, NilClass, TrueClass, FalseClass, BigDecimal, Symbol, Date, Time, DateTime, ActiveSupport::TimeWithZone, ActiveSupport::Duration, Hash, ActiveSupport::HashWithIndifferentAccess, Array, Range, or GlobalID::Identification instances, although this can be extended by adding custom serializers.

A Controller object is not allowed, and also doesn't make much sense to pass to a background job. It's the controller's job to decide what to pass to the job, probably something from params.
See Creating A Job in Active Job Basics for more.


text:
Q: Unable to install DBD::mysql on Ubuntu 20.04 I am unable to get DBD::mysql installed on Ubuntu 20.04. I get the following error:
Warning: No success on command[/usr/bin/perl Makefile.PL LIB=/home/htm/Lib]
DVEEDEN/DBD-mysql-4.050.tar.gz
/usr/bin/perl Makefile.PL LIB=/home/htm/Lib -- NOT OK
Failed during this command:
DVEEDEN/DBD-mysql-4.050.tar.gz               : writemakefile NO '/usr/bin/perl Makefile.PL LIB=/home/htm/Lib' returned status 512
As an aside, I'm trying to setup a beta server to mimmic a paid web server running Ubuntu 20.04.  They only allow installing Perl modules in the user directory so I did the following:
cpan> o conf makepl_arg LIB=/home/htm/Lib
makepl_arg LIB=/home/htm/Lib
I have also tried to reset CPAN with o conf init but that doesn't work either.

A: I found the answer by accident.  I had to do this first:
sudo apt-get install libmysqlclient-dev
After that I was able to get DBD::mysql installed.


text:
Q: Clear range selected in Excel listbox and delete range name Suppose I have a listbox in a userform module. When shown, it contains three range names. Let's call them Range1, Range2, and Range3. When the user clicks on one, I want the corresponding range to be cleared and the range name to be deleted.
Thanks to anyone who can advise me on the code to do this.

A: Sorry I can't comment.But I think this link will help you.
http://www.ozgrid.com/forum/showthread.php?t=83396

A: I actually deleted the range.  Alternatively, you could use Range(.Value).ClearContents to clear only the data or Range(.Value).Clear to clear the data and formatting from the range.

Private Sub ListBox1_Click()
    With ListBox1
        If Not IsNull(.Value) Then
            On Error Resume Next
            Range(.Value).Delete
            ThisWorkbook.Names(.Value).Delete
            On Error GoTo 0
        End If
    End With
    RefreshRangeList
End Sub

Sub RefreshRangeList()
    Dim n As Name
    ListBox1.Clear
    For Each n In ThisWorkbook.Names
        ListBox1.AddItem n.Name
    Next
End Sub

Private Sub UserForm_Initialize()
    RefreshRangeList
End Sub


text:
Q: Is there a tooltip library which lets me add tooltips to SVG elements? I want to add dynamic text and style to tooltips for elements of an SVG. I can do this by adding a div and styling it (red rectangle below). I would prefer to let a library handle it but they all seem to use the title attribute of elements which SVGs do not support (black rectangle below).
Can anyone suggest such a library?

$(document).ready(function() {
  $("rect#2").mouseover(function(e) {
    var myText = "'jQuery' tooltip.";
    $("
" + myText + "
").appendTo("body");
    $("div.tooltip").css({
      top: e.clientY,
      left: e.clientX
    });
  });
  $("rect#2").mouseout(function() {
    $("div.tooltip").remove();
  });
});
.tooltip {
  padding: 8px;
  border: 1px solid black;
  background-color: rgb(200, 200, 200);
  position: absolute;
  z-index: 2;
}

  <svg width="200" height="100">
    <rect id="1" x="30" y="30" width="50" height="50" title="myText" style="fill:black"/>
    <rect id="2" x="130" y="30" width="50" height="50" style="fill:red"/>
    Sorry, your browser does not support inline SVG.
    </svg>

div

A: I am not sure if you need a library for a simple case. I would do your snippet a bit differently:

*

*make div a display: none, pointer-events: none element of your DOM

*once mouseover happens - update its position and visibility

*handle dynamic messages by updating innerHTML parameter of tooltip DIV

$(document).ready(function() {
  $("rect#2").mouseover(function(e) {
    var myText = "'jQuery' tooltip.";
    $("div#tooltip").html(myText);
    $("div#tooltip").css({
      display: "inline-block",
      top: e.clientY,
      left: e.clientX
    });
  });
  $("rect#2").mouseout(function() {
    $("div#tooltip").css({
      top: 0,
      left: 0,
      display: "none",
    });
  });
});
.tooltip {
  padding: 8px;
  border: 1px solid black;
  background-color: rgb(200, 200, 200);
  position: absolute;
  z-index: 2;
  pointer-events: none;
  display: none;
}

  <svg width="200" height="100">
    <rect id="1" x="30" y="30" width="50" height="50" title="myText" style="fill:black"/>
    <rect id="2" x="130" y="30" width="50" height="50" style="fill:red"/>
    Sorry, your browser does not support inline SVG.
    </svg>

tooltip text


text:
Q: How to correctly wait for fetch in a react class I have a class where I have to check for existence of item to display in one html form(say hyperlink) or normal text.
I get the object as a prop. I am finding it hard to use fetch to correctly recognise if the item exists based on return code
    this.props.item.map(function(item) {
          fetch(url+item)(). then (
              if(statusCode === 200)
                 //display hyperlink
                 return {item.a:item.b}
              else
                 //normal text
                 return <disp>{item.a:item.b}</disp>
          )
         // But its expecting a return here!
         //return <disp>{item.a:item.b}</disp>
    })

A: The problem is this is asynchronous code.
You have a couple of problems:
Firstly, (if I'm right in assuming that's an Array.prototype.map function) the  .map function needs to return something. The map function converts one array, into another array of the same size.
Secondly, and more importantly, fetch returns a Promise.
So even if you changed your code to:
this.props.item.map(function(item) {
     return fetch(url+item)(). then (
          if(statusCode === 200)
             //display hyperlink
             return {item.a:item.b}
          else
             //normal text
             return <disp>{item.a:item.b}</disp>
      )
})

All you would get is an array of promises.
What I recommend you do, is start using react-redux, and personally I recommend using redux-saga.
The basic concept with redux and other state management solutions, is that your React components are responsible for displaying data and responding to user interaction (usually by dispatching a redux action) only. They shouldn't be responsible for actually fetching or manipulating the data. That's what your state management middleware (such as redux-saga) is for.
I won't go into it here, but that should put you in the right direction.


text:
Q: assertEquals(string, string) comparisonFailure expected:  but was:  I reversed a string using StringTokenizer and written this code under reverseToken(str) method. I was testing using junit4
@Test
public void testReverseToken(){

    assertEquals(new String("rev this"), Calculation.reverseWord("ver siht"));
}

Why I am getting junit.comaprisonFailure as:
comparisonFailure expected: <str[]> but was: <str[ ]>

What is this str[] and str[ ] (having space)

A: The message is not produced by the test code you posted. It simply says that the test expected the string "str", but got "str " instead (i.e. there is an additional space at the end of the string that should not be there).


text:
Q: TCP Server C++/Unix commandline I am programming a TCP server in C++, and this is my first time doing it.  The problem I am running into seems to be toward the bottom with the strcmp function. I have established the server, then I fork my processes and run the request from the child process. This works fine. For some reason, when I input GET /stuff/ it won't accept GET and automatically prints the error message "Invalid first argument". I have no space problems, so what's the deal? Any ideas are very much appreciated.
void processClientRequest(int connSock, struct sockaddr_in echoclient) //char *argv[] )
{
    char buffer[256];
    unsigned int recieved, count = 0;

    if ((recieved = read(connSock, buffer, 256)) < 0) { //read a message from the client
            perror ("Failed to recieve message");
            exit (EXIT_FAILURE);
    }

    buffer[recieved] = '\0'; //ensure string is terminated
    chomp(buffer); //remove trailing \r and \n

    if (write(connSock, buffer, recieved) != recieved) {
            perror ("Mismatch in number of echo'd bytes");
            exit(EXIT_FAILURE);
    }

    // prepare argv array of strings
    char *argv[] = { (char*)0, (char*)0, (char*)0, (char*)0, (char*)0, (char*)0, (char*)0 };

    // parse command into words
    for (char *p = strtok(buffer, " "); p; p = strtok(NULL, " "))
            {   argv[count] = p;
                    count++;
            }

    cout << "THIS IS ARGV[0]" << argv[0] << endl; //debugging, for some reason will not print

    if (strcmp (argv[0], "GET") == 0)
            GET(connSock, argv[1]);

    else if (strcmp(argv[0], "INFO") == 0)
            INFO();

    else
    {
            perror("Invalid first argument!");
            exit(EXIT_FAILURE);
    }

    // run command and its arguments via execvp
    /*      if (execvp(argv[0], argv) < 0) {
            perror("exec in child after fork");
            exit(EXIT_FAILURE);
            }*/

    cerr << "Client(" << inet_ntoa(echoclient.sin_addr) << ") sent: " << buffer << endl;

}

A: The read function doesn't receive messages, it receives bytes. If you want to receive messages, and you do, you have to write a function to receive them. That requires following the rules of the HTTP protocol to keep receiving bytes until you have the entire messsage, whether that's a line, the entire header, or whatever.
This has probably been said thousands of times, "TCP is a reliable byte-stream protocol that does not preserve application message boundaries." Until you 100% understand what TCP is, don't write code that uses TCP. It will never work correctly.


text: Q: How to use zcat | head on large file in s3 bucket Have large fastq.gz files in an s3 bucket and want to look at a few lines and check that their format is correct. Working locally I use zcat <filepath> | head -n 8 which works fine, but on AWS to get the relevant filename I use aws s3 ls s3://bucket_name/filepath/ and get something like 2022-04-01 3244653538 filename.fastq.gz. Attempting to feed this filepath to zcat - with or without the datestamp and keycode - returns No such file or directory. I am an AWS noob and would greatly appreciate your input.


text:
Q: How to send encrypted email through sendgrid using tls and vb.net API post call? I created a console program on visual basic asp.net that sends a generated email through a post API call. I was successful in sending an email to any recipient email using a godaddy domain through sendgrid. On this domain godaddy, I set up a proofpoint encryption attachment that should create encrypted emails through a trigger of putting "[encrypt]" in the subject line. However, it did not trigger because for the encryption to be automatically attached to the email it has to pass through the office 365 server. Since I am using sendgrid according to the workflow it doesn't go through outlook whatsoever:
https://sendgrid.com/docs/ui/sending-email/email-flow/
I have been doing research and I see send sendgrid supports end-to-end encryption with TLS. However, I cannot find anywhere how to establish this encryption with sendgrid and visual basic API calls. This program is for a medical diagnostic company, who will be sending patient information via email, to maintain HIPPA compliance the emails must be encrypted in some way. Here is the code:
Private Sub SendEmail(PARAMETERS_FOR_AUTOMATING_EMAIL)
        Try

            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

            Dim uri As String = "https://api.sendgrid.com/v3/mail/send"
            Dim Request As WebRequest = WebRequest.CreateHttp(uri)
            Request.Method = "POST"
            Request.PreAuthenticate = True
            Request.Headers.Add("Authorization", "Bearer API_KEY")
            Dim json_data As String = "{""personalizations"": [{""To"": [{""email"": ""TO_EMAIL""}]}],""from"": {""email"": ""FROM_EMAIL""},""subject"":""[Encrypt]This is a automated report"",""content"": [{""type"": ""text/html"",""value"": ""Hello!,<br>Please find attachment.""}], ""attachments"": [{""content"": ""File_translated_to_64_encoded"", ""type"": ""EXCEL_MIME"", ""filename"": ""FILE_NAME_FOR_ATTACHMENT""}]}}"

            Request.ContentType = "application/json"
            Dim json_bytes() As Byte = Encoding.UTF8.GetBytes(json_data)
            Request.ContentLength = json_bytes.Length

            Using requeststream = Request.GetRequestStream
                requeststream.Write(json_bytes, 0, json_bytes.Length)
            End Using

            Dim responsecontent As String = Nothing
            Using Response = DirectCast(Request.GetResponse, HttpWebResponse),
                    responseStream = Response.GetResponseStream()
                Using reader = New StreamReader(responseStream)
                    responsecontent = reader.ReadToEnd()
                End Using
            End Using

        Catch ex As Exception
            ErrLog(ex, currentLocID)
        End Try
    End Sub

If you guys have any ideas to give me a solution please share! thank you in advance.


text:
Q: Redirect non existing link with htaccess We have a static site example.com built with custom php. When we type example.com/asdadada it redirects to the custom 404 page. But when we type example.com/about-us/asdadada, it stays on the same url, i.e. example.com/about-us/asdadada and content of about-us page is shown. We need a 404 or 301 redirection under such circumstances. We have used the below code in htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]

RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]

#get rid of trailing slashes
RewriteCond %{HTTP_HOST} ^(www.)?example\.com$ [NC]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

#redirect to https
RewriteCond %{HTTP_HOST} ^example\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteCond %{SERVER_PORT} 80
#RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

ErrorDocument 404 /404.php

RewriteCond %{QUERY_STRING} view [NC]
RewriteRule .* https://example.com? [R=404,L]
</IfModule>


text:
Q: Database Design - Best way to manage these relationships I am working on a project (based in Django although that's not really relevant to my question) and I am struggling to work out the best way to represent the data models.
I have the four following models:
User,
Client,
Meeting,
Location
User and Client have a many-to-many relationship through the Meeting model.  The Meeting model has a one-to-one relationship with the Location model.
Meetings will take place at either:

*

*The address defined in the User (or UserProfile) model

*The address defined in the Client model.

*Some other location which has to be defined at a later date.

I'm struggling to work out the best way to store the Location data in order to make it as clean and reusable as possible.

*

*I considered making Location as a field in the Meetings model rather than a model in its own right - although this could also lead to redundant data if lots of Meetings are created at the same location, so this is probably a non-starter.

*I could automatically create Location records for each User and Client that gets created and use a generic relationship between the relevant records, however, I understand that this can lead to inefficient database performance.  Also, not every Client / User would be able to hold meetings at their Location.
Can anyone see an tidier alternative?
Any advice appreciated.
Thanks.

A:
I considered making Location as a field in the Meetings model rather
  than a model in its own right - although this could also lead to
  redundant data if lots of Meetings are created at the same location,
  so this is probably a non-starter.

No, that's a really good thought, because it points you straight at the real problem.
The real problem is that there's a difference between a meeting and the parties that attend a meeting. A meeting has some attributes that have nothing to do with the attendees: it has at the very least a time and a place.
So I think you should change your thinking about the Meeting model.
Instead of users having a M:N relationship with clients through the Meeting model, they should have a M:N relationship through, say, an Attendance model. (A Registration or Reservation or MightAttend model might be more appropriate for you.) And the Meeting model should change to reflect the unique attributes of a real-world meeting: time and place.

A: I would expect Meetings and Locations to have a many-to-one relationship.  Can't a location be used for more than one meeting? (at different times, of course)
It seems to me that a location has attributes that persist beyond its use for a single meeting.  Example: seating capacity.


text:
Q: postgres how to insert values with 2 selects I'm trying to do a query on Postgres but it's not working. I'd like to create an insert query with 2 select:
Example :
INSERT INTO table1 (id_1, id_2)
SELECT id from table_2 where code='01',
SELECT id from table_2 where code='02';

I don't find the good syntax for this.

A: I believe below query will works for your use case
INSERT INTO stats(totalProduct, totalCustomer, totalOrder)
VALUES(
    (SELECT COUNT(*) FROM products),
    (SELECT COUNT(*) FROM customers),
    (SELECT COUNT(*) FROM orders)
);

you can changes query accordingly

A: You can add one more SELECT to achieve this
INSERT INTO table_1 (id_1, id_2)
SELECT
    (SELECT id FROM table_2 WHERE code = '01') AS Id_1,
    (SELECT id FROM table_2 WHERE code = '02') AS Id_2;

Or you may try with CASE expression:
INSERT INTO table1 (id_1, id_2)
SELECT MAX(CASE WHEN code = '01' THEN id ELSE 0 END) AS Id_1,
       MAX(CASE WHEN code = '02' THEN id ELSE 0 END) AS Id_2
FROM table_2

Please refer to the working fiddle on db<>fiddle


text:
Q: Prove that number is a primitive root for all $k$ in range Let $a$ be a primitive root for $p > 2$ where $p$ is prime. Show that $a^p+kp$ for $k = 1,\dots,p-1$ are $p-1$ distinct primitive roots modulo $p^2$.
What I have done:
First of all it is easy to see that by Fermat' Little Theorem $a^p+kp \equiv a + kp \equiv a$ (mod $p$), so all of these are primitive roots modulo $p$. Next we would need to see that these are primitive roots modulo $p^2$ as well. For this we would need to see that $(a^p+kp)^{p-1} \not\equiv 1$ (mod $p^2$). I have tried to do this using Newton binomial but I haven't been able to do so. Also we would somehow need to show that for all $k$ the primitive root is distinct so $a^p + k_1p \not\equiv a^p + k_2p$ (mod $p^2$). Any suggestions on how to proceed?

A: Claim: $(a^p+kp)^{p-1} \not \equiv 1 \pmod {p^2}$,  when $a$ is primitive root$\mod p$ and $k \in \{1,2,\ldots,p-1\}$.
Let's denote $u= a^p+kp$ and $v = a^p$. Then, by Euler's theorem $v^{p-1}\equiv 1 \pmod{p^2}$ so the claim is equivalent to $p^2\nmid u^{p-1}- v^{p-1}$. However, we also have that:
\begin{equation}
 u^{p-1}- v^{p-1} = (u-v)(u^{p-2}+u^{p-3}v^1+\ldots+u^{1}v^{p-3}+v^{p-2}) \label{a}
\end{equation}
Moreover $u-v=pk$, so $u\equiv v\pmod p$, this implies that the second factor in
right hand side of the above equality is coprime with $p$. This is so because:
\begin{equation}
u^{p-2}+u^{p-3}v^1+\ldots+u^{1}v^{p-3}+v^{p-2}\equiv (p-1)u^{p-2}\mod p
\end{equation}
 Then if $p^2| u^{p-1}- v^{p-1}$, as that second term is coprime with $p$, we would have that $p^2|u-v = kp$ which is impossible. Then $p^2\nmid u^{p-1}- v^{p-1}$. Which implies the claim and what you want (The order of $u$ would have to be divided by $p$ and $p-1$).
About the second part, you just need to note that $p^2 | (a^p+k_1p) - (a^p+k_2p)$ implies that $p^2|(k_1-k_2)p$ and that if $p|k_1-k_2$ this implies $k_1 = k_2$.
Apologies for all the mistakes, I just saw that you could just do it with Newton's Binomial, I didn't realize that at the time I wrote this xD.
You should still check out LTE(Lifting the exponent Lemma), it is a popular trick in high school olympiads that gives you more information than what I just used http://services.artofproblemsolving.com/download.php?id=YXR0YWNobWVudHMvYy82LzdjNTI1OGIyMmNjYmZkZGY4MDhhY2ViZTc3MGE1NDRmMzFhMTEzLnBkZg==&rn=TGlmdGluZyBUaGUgRXhwb25lbnQgTGVtbWEgLSBBbWlyIEhvc3NlaW4gUGFydmFyZGkgLSBWZXJzaW9uIDMucGRm.


text:
Q: How to set the fix time for the pop up window in php I have written code like this
setTimeout('newWindow.close();',1000);

But this code does not work.
It does not give any errors but the pop-up is not destroyed.
Can anybody help me ?

A: Try this within script tags in your php code
setTimeout('window.close()', 2000);


text:
Q: Loading Historical Google Satellite Imagery with QGIS QuickMapServices plugin? Loading older google satellite image with OpenLayers plugin in QGIS? is a similar question that was asked 4 years ago.
Is QGIS QuickMapServices able to load Google Earth's (aka Google Satellite's) historical imagery?

A: It doesn't look like the historical data is available through this method.
You can add more mapping services in the Quick Map Services plugin by going to Settings and then More Services. If you add the whole pack you get many more services, but not the Google one you want.


text:
Q: How do I connect from a MVC3 .net application to a MySQL database through a SSH tunnel I am building a .net MVC3 application using Entity Framework 4.  One of the databases I would like to connect with has to be accessed through a SSH tunnel.  Is there a way to do this through the web.config?  If not, what approaches should I consider?
Thanks,
Afrieze

A: Yes you can do this
http://www.howtogeek.com/howto/ubuntu/access-your-mysql-server-remotely-over-ssh/


text:
Q: Determine DDL value for dynamic column creation in oninit event Greetings, hopefully there is a simple solution for this complex problem.  Please correct any misconceptions I have along the way.
 A while ago I wrote a GrivView with dynamic column capability.  The columns are added in the OnInit page event so that they are added BEFORE the viewstate is applied.  They are reapplied on every posting in this section of the page so that when the viewstate is applied changes that the user has made and not committed to the database are maintained.  It also is required if you don't want your viewstate control tree to get out of synch and blow everything up.
My current  problem is that I am now tasked with doing essentially the same thing where the columns will be different based on a Drop Down List (I will recreate the GridView if the ddl changes, and the users will lose all work with a warning).  How can I get the ID that is selected in the Drop Down List in the OnInit Event?  My understanding is that when the user changes the value of the ddl on the client side a JavaScript "__doPostBack" call is fired.  The page request is then sent to the server but by the time the new value is present in the event handler I am past the point where I need to add the columns.
I saw something I thought was promising when people were trying to determine what control caused a post back but that code relies on page.Request.Params.Get("__EVENTTARGET"); and page.Request.Form which are empty.
Should I look at the session state, try to 'send' the ID using client side manipulation, or some other method (Perhaps a sneaky way to look in the viewstate I am missing)?
Thanks for any ideas!!!

A: A control's submitted value is available from the Request[] collection even if it appears that your form has not been reconstructed yet.
You should simply be able to get the selected value during Init() using the following:
string value = Request["myDropDownID"];


text:
Q: Ionic InAppPurchase2 (cordova-plugin-purchase) refund event does not trigger while testing inAppPurchase2 with their latest version as cordova-plugin-purchase I notice that the refund event for consumables is never trigger (this in Android).
Did any of you have successfully trigger this event? I asked in github and I got a comment about setting a revoke option that is not documented anywhere and no further answers for more than two weeks. I do not know how to proceed. I do the event listener as I do the other event states:
this.iap2.when(productId).refunded((product: IAPProduct) => {
  this.logger.log('refunded', product);
  alert('refunded');
});

A: As I understand it, refund events are only ever fired via a web-hook you configure in the apple/google store.


text:
Q: What are PostgreSQL RULEs good for? Question
I often see it stated that rules should be avoided and triggers used instead. I can see the danger in the rule system, but certainly there are valid uses for rules, right? What are they?
I'm asking this out of general interest; I'm not very seasoned with databases.
Example of what might be a valid use
For instance, in the past I've needed to lock down certain data, so I've done something like this:
CREATE OR REPLACE RULE protect_data AS
  ON UPDATE TO exampletable             -- another similar rule for DELETE
  WHERE OLD.type = 'protected'
  DO INSTEAD NOTHING;

Then if I want to edit the protected data:
START TRANSACTION;
  ALTER TABLE exampletable DISABLE RULE protect_data;
  -- edit data as I like
  ALTER TABLE exampletable ENABLE RULE protect_data;
COMMIT;

I agree this is hacky, but I couldn't change the application(s) accessing the database in this case (or even throw errors at it). So bonus points for finding a reason why this is a dangerous/invalid use of the rule system, but not for why this is bad design.

A: How about this: You have a table that needs to be changed into a view. In order to support legacy applications that insert into said table, a rule is created that maps "inserts" to the new view to the underlying table(s).

A: One of the use cases for RULES are updateable views (although that changes in 9.1 as that version introduces INSTEAD OF triggers for views)
Another good explanation can be found in the manual:

For the things that can be implemented by both, which is best depends on the usage of the database. A trigger is fired for any affected row once. A rule manipulates the query or generates an additional query. So if many rows are affected in one statement, a rule issuing one extra command is likely to be faster than a trigger that is called for every single row and must execute its operations many times. However, the trigger approach is conceptually far simpler than the rule approach, and is easier for novices to get right.

(Taken from: http://www.postgresql.org/docs/current/static/rules-triggers.html)

A: Some problems with rules are shown here: http://www.depesz.com/index.php/2010/06/15/to-rule-or-not-to-rule-that-is-the-question/ (for instance, if a random() is included in a query, it might get executed twice and return different values).
The biggest drawback of rules is that people don't understand them.
For example, one might think that having the rule:
CREATE OR REPLACE RULE protect_data AS
  ON UPDATE TO exampletable             -- another similar rule for DELETE
  WHERE OLD.type = 'protected'
  DO INSTEAD NOTHING;

Will mean that if I'll issue:
update exampletable set whatever = whatever + 1 where type = 'protected'

No query will be ran. Which is not true. The query will be run, but it will be ran in modified version - with added condition.
What's more - rules break very useful thing, that is returning clause:
$ update exampletable set whatever = whatever + 1 where type = 'normal' returning *;
ERROR:  cannot perform UPDATE RETURNING on relation "exampletable"
HINT:  You need an unconditional ON UPDATE DO INSTEAD rule with a RETURNING clause.

To wrap it - if you really, really, positively have to use writable views, and you're using pre 9.1 PostgreSQL - you might have a valid reason to use rules.
In all other cases - you're most likely shooting yourself in a foot, even if you don't immediately see it.

A: I've had a few bitter experiences with rules when dealing with volatile functions (if memory serves, depesz' blog post highlights some of them).
I've also broken referential integrity when using them because of the timing in which fkey triggers get fired:
CREATE OR REPLACE RULE protected_example AS
  ON DELETE TO example
  WHERE OLD.protected
  DO INSTEAD NOTHING;

... then add another table, and make example reference that table with an on delete cascade foreign key. Then, delete * from that table... and recoil in horror.
I reported the above issue as a bug, which got dismissed as a feature/necessary edge case. It's only months later that I made sense of why that might be, i.e. the fkey trigger does its job, and the rule then kicks in and does its own, but the fkey trigger won't check that its job was done properly for performance reasons.
The practical use-case where I still use rules is when a BEFORE trigger that pre-manipulates data (the SQL standard says is not allowed, but Postgres will happily oblige) can result in pre-manipulating the affected rows and thus changing their ctid (i.e. it gets updated twice, or doesn't get deleted because an update invalidated the delete).
This results in Postgres returning an incorrect number of affected rows, which is no big deal until you monitor that number before issuing subsequent statements.
In this case, I've found that using a strategically placed rule or two can allow to pre-emptively execute the offending statement(s), resulting in Postgres returning the correct number of affected rows.


text:
Q: Double sqrt solution in Matlab? I would like to know how can I get both the positive and the negative solution from a sqrt in Matlab.
For example if I have:
sin(a) = sqrt(1-cos(a)^2);

A: The docs don't say anything specific about always only providing the positive square root but it does seem like a fair assumption in which case you can get the negative square  pretty easily like this:
p = sqrt(1-cos(a)^2);
n = -sqrt(1-cos(a)^2);

btw assigning to sin(a) like that is going to create a variable called sin which will hide the sin function leading to many possible errors, so I would highly recommend choosing a different variable name.

A: sqrt does not solve equations, only gives numerical output. You will need to formulate your equation as you need it, and then you can use sqrt(...) -1*sqrt(...) to give your positive and negative outputs.

A: MATLAB (and every other programming language that I know of) only returns the principal square root of x when calling sqrt(x) or equivalent.
How you'd write the square root of x mathematically, is
s = ±√x

which is just a shorthand for writing the whole solution set
s = {+√x -√x}

In MATLAB, you'd write it the same as this last case, but with slightly different syntax,
s = [+sqrt(x) -sqrt(x)]

which can be computed more efficiently if you "factor out" the sqrt:
s = sqrt(x) * [1 -1]

So, for your case,
s = sqrt(1-cos(a)^2) * [1 -1]

or, if you so desire,
s = sin(acos(a)) * [1 -1]

which is a tad slower, but perhaps more readable (and actually a bit more accurate as well).
Now of course, if you can somehow find the components whose quotient results in the value of your cosine, then you wouldn't have to deal with all this messy business of course....


text: Q: Prior for Variance Covariance Matrix Why in Bayesian Hierarchical Modelling the prior corresponding to a Variance Covariance Matrix is taken to be Inverse Wishart Distribution not Wishart Distribution?


text:
Q: Cannot send json to server, an ajax error occurs I tried this code on my site, then on other site, then on jquery.com via console:
jQuery.ajax({
url: '/',
type: 'POST',
data: '{"test":"test"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});

$(document).ajaxError(function(e, jqXHR, ajaxSettings, thrownError){
    console.log(thrownError);
});

So the console logs this:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I don't understand why. It looks that everything is correct in my code.

A: You are passing a string literal rather than an object:
data: { test: 'test' },

A: I think you have a typo in Line 4
Try:
data: {test:"test"},

And it should work - I hope :)
Sorry, i had the 3 Minutes 1 Post Problem here and wasn't able to see the comment from Victory


text:
Q: How can I detect if there is a piece on chess square or not? I have to detect a chess board and I do that as shown in this picture:

I divided this image in 64 sub-images which represent the black and white chess squares, like:

How can I check whether these sub-images (each square) contains a chess piece?

A: First you need to refine your squares detection, because you have some white region in the black and vice-versa. To do this quickly you can just crop a smaller ROI in the center of the square, assuming most of the piece will be in the center.
For the actual detection there are all kinds of simple options, which I guess will work perfectly fine in your case. Don't need to go to sophisticated feature detection and machine learning.
Options:

*

*If you know the color of the square, use some threshold to find the piece.

*You can look on the standard deviation of the gray level in the square. Without a piece it would be quite low, so you could use some threshold here.

*You can do background subtraction with an empty square.

Either way, there will be some noise, so you will have to play with it a bit to find the best threshold/parameters.
Most of the time it is also better to do some pre-processing blur to get smoother results.

A: There are a lot of things that you need to consider:

*

*Is necessary to have that perspective of the chess?. A top perspective can help you to make your process easier, by doing this you are avoiding an invasion of a piece in other square.

*then you can check if there is a piece of chess in a square by checking the histogram of it. If the square doesn't have a piece you can appreciate a single peak in the curve, if there is a piece in that square you will appreciate more than one peak. You can use a threshold in the histogram to find if there is a single peak or not (by finding the max points in the histogram)


text:
Q: Faster dump load in Progress 9.1E How the dump load can be done faster in Progress?
I need to automate the process of dump load,so that I can have dump load on weekly basis?

A: Generally one wouldn't need to do a weekly D&L as the server engine does a decent job of managing is data. A D&L should only be done when there's an evident concern about performance, when changing versions, or making a significant organizational change in the data extents.
Having said that, a binary D&L is usually the fastest, particularly if you can make it multi-threaded.

A: Ok, dumping and loading to cross platforms to build a training system is probably a legitimate use-case.  (If it were Linux to Linux you could just backup and restore -- you may be able to do that Linux to UNIX if the byte ordering is the same...)
The binary format is portable across platforms and versions of Progress.  You can binary dump a Progress version 8 HPUX database and load it into a Windows OpenEdge 11 db if you'd like.
To do a binary dump use:
proutil dbname -C dump tablename

That will create tablename.bd.  You can then load that table with:
proutil dbname -C load tablename

Once all of the data has been loaded you need to remember to rebuild the indexes:
proutil dbname -C idxbuild all

You can run many simultaneous proutil commands.  There is no need to go one table at a time.  You just need to have the db up and running in  multi-user mode.  Take a look at this for a longer explanation: http://www.greenfieldtech.com/downloads/files/DB-20_Bascom%20D+L.ppt
It is helpful to split your database up into multiple storage areas (and they should be type 2 areas) for best results.  Check out: http://dbappraise.com/ppt/sos.pptx for some ideas on that.
There are a lot of tuning options available for binary dump & load.  Details depend on what version of Progress you are running.  Many of them probably aren't really useful anyway but you should look at the presentations above and the documentation and ask questions.