text:
Q: Use MPI gather to get data from tasks into master array I'm learning how to use MPI to calculate the 4 point stencil of a 2d hot plate. But my issue is that when writing my results to an output file, the output file only contains the results of one of the tasks (I believe its the task that finishes first). What I want to do is gather the data after performing all the iterations in the worker tasks back to the master, but I am unsure how to do that. I want to use MPI_Gather, or believe I need to use it, but I don't quite understand how to do it from the tutorials.
Alternatively, am I misallocating how to return data back to the master in my worker threads?
Code here:

#define BEGIN       1                  /* message tag */
#define LTAG        2                  /* message tag */
#define RTAG        3                  /* message tag */
#define NONE        0                  /* indicates no neighbor */
#define DONE        4                  /* message tag */
#define MASTER      0                  /* taskid of first process */
#include <iostream>
#include <math.h>
#include <fstream>
#include <string>
#include <cstring>
#include <iomanip>
#include <chrono>
#include <mpi.h>
#include <chrono>
using namespace std::chrono;
using namespace std;

void update(int start, int end, int ny, double* u1, double* u2)
{
    int ix, iy;
    for (ix = start; ix <= end; ix++)
    {
        for (iy = 1; iy <= ny - 2; iy++)
        {
            //calculate stencil
            *(u2 + ix * ny + iy) = .25 * (
                *(u1 + (ix + 1) * ny + iy) +
                *(u1 + (ix - 1) * ny + iy) +
                *(u1 + ix * ny + (iy + 1)) +
                *(u1 + ix * ny + (iy - 1)));
        }

    }

    //pass into buffer
    for (ix = start; ix <= end; ix++)
        for (iy = 1; iy <= ny - 2; iy++)
            *(u1 + ix * ny + iy) = *(u2 + ix * ny + iy);

}

bool isNumber(char number[])
{
    int i = 0;

    //checking for negative numbers
    if (number[0] == '-')
        return false;
    for (; number[i] != 0; i++)
    {
        //if (number[i] > '9' || number[i] < '0')
        if (!isdigit(number[i]))
            return false;
    }
    return true;
}

int main(int argc, char* argv[])
{
    //variable init
    int N = 0;
    int I = 0;
    int taskid,                     /* this task's unique id */
        numworkers,                 /* number of worker processes */
        numtasks,                   /* number of tasks */
        averow, rows, offset, extra,   /* for sending rows of data */
        dest, source,               /* to - from for message send-receive */
        left, right,        /* neighbor tasks */
        msgtype,                    /* for message types */
        rc, start, end,               /* misc */
        i, ix, iy, iz, it;              /* loop variables */
    MPI_Status status;

    //There should be five arguments, no more no less
    if (argc != 5)
    {
        std::cout << "Invalid parameters, please check your values." << std::endl;
        exit(1);
    }
    if (!isNumber(argv[2]) || !isNumber(argv[4]))
    {
        std::cout << "Invalid parameters, please check your values." << std::endl;
        exit(1);
    }

    //check the n flag in either valid position.
    if (!strcmp(argv[1], "-n"))
    {
        N = atoi(argv[2]);
    }
    else if (!strcmp(argv[3], "-n"))
    {
        N = atoi(argv[4]);
    }
    else
    {
        std::cout << "Invalid flags, please check your values." << std::endl;
        exit(1);
    }

    //check the I flag in either valid position
    if (!strcmp(argv[1], "-I"))
    {
        I = atoi(argv[2]);
    }
    else if (!strcmp(argv[3], "-I"))
    {
        I = atoi(argv[4]);
    }
    else
    {
        std::cout << "Invalid flags, please check your values." << std::endl;
        exit(1);
    }

    if (N == 0 || I == 0)
    {
        std::cout << "Invalid parameters, please check your values." << std::endl;
        exit(1);
    }
    int n_x = N + 2; //Based on the piazza post, increase x and y dimension by two for the edges
    int n_y = N + 2;
    double** phi[2];
    double** resultArray;
    phi[0] = new double* [n_x];
    phi[1] = new double* [n_x];
    resultArray = new double* [n_x];
    for (int i = 0; i < n_x; i++)
    {
        phi[0][i] = new double[n_y];
        phi[1][i] = new double[n_y];
        resultArray[i] = new double[n_y];
    }
    int iterationMax = I;
    //Initialize the plate temperatures
    for (int j = 0; j < n_x; j++)
    {
        for (int i = 0; i < n_x; i++)
        {
            if ((i == 0) || (i == n_x - 1) || (j == 0) || (j == n_y - 1))
            {
                phi[0][i][j] = 20.0;
                phi[1][i][j] = 20.0;
            }
            else
            {
                phi[0][i][j] = 0.0;
                phi[1][i][j] = 0.0;
            }

        }
    }

    for (int j = 0; j < n_x; j++)
    {
        if (j > (int)(0.3 * n_x) && j < (int)(0.7 * n_x))
        {

            phi[0][0][j] = 100.0;
            phi[1][0][j] = 100.0;
        }
    }

    /* First, find out my taskid and how many tasks are running */
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
    MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
    numworkers = numtasks - 1;
    if (taskid == 0) {
        auto start = high_resolution_clock::now();

        /************************* master code *******************************/
        /* Check if numworkers is within range - quit if not */

        //printf("Starting mpi_heat2D with %d worker tasks.\n", numworkers);

        /* Initialize grid */
        //printf("Grid size: X= %d  Y= %d  Time steps= %d\n", n_x, n_y, I);

        /* Distribute work to workers.  Must first figure out how many rows to */
        /* send and what to do with extra rows.  */
        averow = n_x / numworkers;
        extra = n_x % numworkers;
        offset = 0;
        for (i = 1; i <= numworkers; i++)
        {
            rows = (i <= extra) ? averow + 1 : averow;
            /* Tell each worker who its neighbors are, since they must exchange */
            /* data with each other. */
            if (i == 1)
                left = 0;
            else
                left = i - 1;
            if (i == numworkers)
                right = 0;
            else
                right = i + 1;
            /*  Now send startup information to each worker  */
            dest = i;
            MPI_Send(&offset, 1, MPI_INT, dest, 1, MPI_COMM_WORLD);
            MPI_Send(&rows, 1, MPI_INT, dest, 1, MPI_COMM_WORLD);
            MPI_Send(&left, 1, MPI_INT, dest, 1, MPI_COMM_WORLD);
            MPI_Send(&right, 1, MPI_INT, dest, 1, MPI_COMM_WORLD);
            MPI_Send(&phi[0][offset][0], rows * n_y, MPI_DOUBLE, dest, 1,
                MPI_COMM_WORLD);
            /* printf("Sent to task %d: rows= %d offset= %d ", dest, rows, offset);
             printf("left= %d right= %d\n", left, right);*/
            offset = offset + rows;
        }
        /* Now wait for results from all worker tasks */
        for (i = 1; i <= numworkers; i++)
        {
            source = i;
            msgtype = DONE;
            MPI_Recv(&offset, 1, MPI_INT, source, msgtype, MPI_COMM_WORLD,
                &status);
            MPI_Recv(&rows, 1, MPI_INT, source, msgtype, MPI_COMM_WORLD, &status);
            MPI_Recv(&phi[0][offset][0], rows * n_y, MPI_DOUBLE, source,
                msgtype, MPI_COMM_WORLD, &status);
        }

        /* Write final output, call X graph and finalize MPI */

        auto stop = high_resolution_clock::now();
        auto duration = duration_cast<milliseconds>(stop - start);

        std::cout.precision(5);
        // output the time to the console
        std::cout << "Time taken to solve diffusion plate: " << duration.count() << "ms" << std::fixed << std::endl;

    }   /* End of master code */

    /************************* workers code **********************************/
    if (taskid != MASTER)
    {

        /* Receive my offset, rows, neighbors and grid partition from master */
        source = MASTER;
        msgtype = BEGIN;
        MPI_Recv(&offset, 1, MPI_INT, source, msgtype, MPI_COMM_WORLD, &status);
        MPI_Recv(&rows, 1, MPI_INT, source, msgtype, MPI_COMM_WORLD, &status);
        MPI_Recv(&left, 1, MPI_INT, source, msgtype, MPI_COMM_WORLD, &status);
        MPI_Recv(&right, 1, MPI_INT, source, msgtype, MPI_COMM_WORLD, &status);
        MPI_Recv(&phi[0][offset][0], rows * n_y, MPI_DOUBLE, source, msgtype,
            MPI_COMM_WORLD, &status);

        /* Determine border elements.  Need to consider first and last columns. */
        /* Obviously, row 0 can't exchange with row 0-1.  Likewise, the last */
        /* row can't exchange with last+1.  */
        start = offset;
        end = offset + rows - 1;
        if (offset == 0)
            start = 1;
        if ((offset + rows) == n_x)
            end--;
        // printf("task=%d  start=%d  end=%d\n", taskid, start, end);

         /* Begin doing STEPS iterations.  Must communicate border rows with */
         /* neighbors.  If I have the first or last grid row, then I only need */
         /*  to  communicate with one neighbor  */
         //printf("Task %d received work. Beginning time steps...\n", taskid);
        iz = 0;
        for (it = 1; it <= iterationMax; it++)
        {
            if (left != NONE)
            {
                MPI_Send(&phi[iz][offset][0], n_y, MPI_DOUBLE, left,
                    RTAG, MPI_COMM_WORLD);
                source = left;
                msgtype = LTAG;
                MPI_Recv(&phi[iz][offset - 1][0], n_y, MPI_DOUBLE, source,
                    msgtype, MPI_COMM_WORLD, &status);
            }
            if (right != NONE)
            {
                MPI_Send(&phi[iz][offset + rows - 1][0], n_y, MPI_DOUBLE, right,
                    LTAG, MPI_COMM_WORLD);
                source = right;
                msgtype = RTAG;
                MPI_Recv(&phi[iz][offset + rows][0], n_y, MPI_DOUBLE, source, msgtype,
                    MPI_COMM_WORLD, &status);
            }
            /* Now call update to update the value of grid points */
            update(start, end, n_y, &phi[iz][0][0], &phi[1-iz][0][0]);
            iz = 1 - iz;
        }
        /* Finally, send my portion of final results back to master */
        MPI_Send(&offset, 1, MPI_INT, MASTER, DONE, MPI_COMM_WORLD);
        MPI_Send(&rows, 1, MPI_INT, MASTER, DONE, MPI_COMM_WORLD);
        MPI_Send(&phi[iz][offset][0], rows * n_y, MPI_DOUBLE, MASTER, DONE,
            MPI_COMM_WORLD);
        //printf("Task %d finished work...\n", taskid);
        MPI_Finalize();
    }

    //This is probably not correct
    /*double gsize;
    int root, myrank;
    double* mybuf;

    MPI_Gather(&mybuf, 1, MPI_DOUBLE, phi, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);*/

    std::ofstream outJob;
    outJob.open("finalTemperatures.csv");
    std::cout.precision(15);
    double* printAddr = &phi[0][0][0];
    for (int j = 0; j < n_y; j++) //file IO
    {
        for (int i = 0; i < n_x; i++)
        {
            outJob << phi[0][j][i] << "," << std::fixed;
        }
        outJob << std::endl;
    }
    outJob.close();

    return 0;
}
}


text:
Q: Concurrent database creation My web app requires some initial database scripts to be executed during installation. These are just some CREATE TABLE scripts that need to be run. I'm working on dockerizing it.
I've been trying to use the Docker 1.12's swarm mode to create multiple container replicas of my web app which use a shared database. (An Oracle 12c or MySQL instance).
The problem is that when I start multiple copies of the container, they all try to run the SQL scripts simultaneously and fail. I tried using Flyway to handle the database migrations but to no avail.
What should be the way to handle such a situation?

A: Generally, DB migration jobs should be versioned with every new script executing only after all the earlier ones are done. With this as a precondition one can either design a tool that runs those jobs one after another if not already run or one lets the jobs run always, but designs them in a way to check that they have not been done before.
Otherwise, all application data are at risk of being wiped off at next deployment. You should be able to deploy any time keeping and reusing the existing data (with docker or without).
In your "simple" case a DB check of the following sort would help:
create table IF NOT EXISTS thing (col1 int not null, col2 int not null, age int not null );

Thanks @Drew for prompting me to put my comment into an answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How many function parameters is too many?
Possible Duplicate:
How many parameters are too many?

I was just writing a function that took in several values and it got me thinking.  When is the number number of arguments to a function / method too many?  When (if) does it signal a flawed design?  Do you design / refactor the function to take in structs, arrays, pointers, etc to decrease the amount of arguments?  Do you refactor the data coming in just to decrease the number of arguments?  It seems that this could be a little less applicable in OOP designs, though.  Just curious to see how others view the issue.
EDIT:  For reference the function I just wrote took in 5 parameters.  I use the definition of several that my AP Econ teacher gave me. More than 2; less than 7.

A: If you have to ask then that's probably too many.

A: I generally believe that if the parameters are functionally related (e.g., coordinates or color components), they should be encapsulated as a class for good measures.
Not that I always follow this myself ;)

A: Robert C. Martin (Uncle Bob) recommends 3 as a maximum in Clean Code: A Handbook of Agile Software Craftsmanship
I don't have the book with me at the moment but his reasoning has to do with one, two and, to a lesser extent, three argument functions reading well and clearly showing the purpose of the function.
This of course goes hand in hand with his recommendation of very short, well named functions that adhere to the Single Responsibility Principal.

A: I don't know, but I know it when I see it.

A: According to Steve McConnell in Code Complete, you should

Limit the number of a routine's
  parameters to about seven

A: Quick answer: When you have to stop and ask that question, you've got too many.
Personally I like to keep the number under six.  If more is needed, then the solution depends on the problem.  One approach is to use "setter" functions to give the values to an object that will eventually perform the function you desire.  Another option is to use a struct, as you mentioned.  Either way, you can't really go wrong.

A: Well it would most certainly depend on what your function is doing as far as how many would be considered "too many".  Having said that, it is certainly possible to have a function with a lot of different parameters that are options on how to handle certain cases inside the function, and having overloads to those functions with sane default values for those options.
With the pervasiveness of Intellisense (or equivalent in other IDEs) and tooltips showing the comments from the XML Documentation in Visual Studio, I don't really think that there's a firm answer to this question.

A: Too much parameter is a "Code Smell".
You can divide into multiple methods or use class to regroup variable that have something in common.
To put a number for the "Too much" is something very subjective and depend of your organization and the language you use, A rule of thumb is that if you can't read the signature of your method and have an idea of what is it doing than you might have too much information. Personnaly, I try not to go over 5 parameters.

A: For me is 5.
It is hard to manage ( remember name, order, etc  ) beyond that. Plus If I come that far I have versions with default values that call this one.

A: Depends on the Function as well, if your function requires heavy user intervention or variables, I wouldn't go past 7-8 range. As far as average number of parameters to go with, 5-6 is the sweet spot in my opinion. If you are using more than that you might want to consider class objects as parameters or other smaller functions.

A: It varies from person to person. Personally, when I have trouble immediately understanding what a function call is doing by reading the invocation in code, it is time to refactor to take the strain off of my gray cells.

A: I've heard that 7 figure as well, but I somehow feel that it stems from a time when all you could pass where primitive values.
Nowadays you can pass a reference to an object that encapsulates some complex state (and behaviour). Using 7 of those would definitely be too much.
My personal goal is to avoid using more than 4.

A: It depends strongly on the types of the arguments.  If they are all integers then 2 can be too many. (how do I remember which order?)  If any argument accepts null, then the number drops drastically.
The real answer comes from asking yourself:

*

*how easy is it to understand calls when I'm reading code?

*how easy is it to remember the correct arguments and argument order when writing code?

A: And it depends of the programming language.. In C, it's really not rare to see functions with 7 parameters.. However, in C#, I have rarely seen more than 5 parameters and I personally use less than 3 usually.
// In C
 draw_dot(x, y, size, red, green, blue, alpha)

// In C#
 Point point(x,y);
 Color color(red,green,blue,alpha);

 Tool.DrawDot(point, color);

A: I would say maximum 4 . Anything above , I think should be placed within a class .


text:
Q: Unknown gap between table td's Quite simply, I have a black line showing between two td elements and I'm not sure why.
I've tried valign="bottom" and valign="top" accordingly in an attempt to move the td in the gap but then the td sizes vary.

                Faceate volorunt uta quo moditas

 et labo. Comnima iorehent hit est

 am vit elit volores cimpossime

 serchit, oditiis rehenis volor

 sequisqui ut late cus. Faceate

 volorunt uta quo moditas et labo.

 Comnima ioreh.

                Faceate volorunt uta quo moditas

 et labo. Comnima iorehent hit est

 am vit elit volores cimpossime

 serchit, oditiis rehenis volor

 sequisqui ut late cus.

                   Read more

The gap is in column 2, why is this happening?

A: It's because of the image height which you specified as 286. But the table on the left side have height of 288px. Make image also 288

A: One work around could be to give the Image-2 (woman in the field) the following css to shift it up. I checked the image by itself and it doesn't seem to have any weird invisible black line. And I tried turning off all the padding on the parent td element. This is not ideal but does achieve visually what you are looking for.
position: relative;
top: -2px;

A: Not really the solution to your table layout problem, but rather how to do it without tables.
See on Codepen

.layout {
  width: 692px;
  background: #2c2d2d;
  font-family: Arial;
}

.layout .row {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

.layout .row>div {
  flex-basis: 50%;
  height: 286px;
  padding: 0 30px;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  text-align: center;
  background-position: center center;
  background-size: cover;
}

.layout .row>div.bg-blue {
  background: #00acf2;
}

.layout .row>div img.bigQuote {
  margin-top: -15px;
}

.layout .row>div p {
  margin: 0;
}

.layout .row>div span.caret {
  display: block;
  height: 5px;
  width: 30px;
  background: #fff;
}

.layout .row>div span.button {
  display: inline-block;
  padding: 10px;
  border: #fff solid 1px;
  border-radius: 5px;
}

Faceate volorunt uta quo moditas et labo. Comnima iorehent hit est am vit elit volores cimpossime serchit, oditiis rehenis volor sequisqui ut late cus. Faceate volorunt uta quo moditas et labo. Comnima ioreh.

Faceate volorunt uta quo moditas et labo. Comnima iorehent hit est am vit elit volores cimpossime serchit, oditiis rehenis volor sequisqui ut late cus.
Read more

A: Change height to 286px for the table inside the tdfollowing the  comment, and change valign to top in the last table (which contains the image and follows after the  comment line )

                Faceate volorunt uta quo moditas

 et labo. Comnima iorehent hit est

 am vit elit volores cimpossime

 serchit, oditiis rehenis volor

 sequisqui ut late cus. Faceate

 volorunt uta quo moditas et labo.

 Comnima ioreh.

                Faceate volorunt uta quo moditas

 et labo. Comnima iorehent hit est

 am vit elit volores cimpossime

 serchit, oditiis rehenis volor

 sequisqui ut late cus.

                   Read more

P.S.: Try not to use inline styles, it's extremely tedious to work with.


text:
Q: The method fillColor() is undefined? CircleOptions circleOptions = new CircleOptions()
            .center(new LatLng(latitude, longitude))
            .radius(1000); // In meters
            .fillColor(Color.RED)
            .strokeColor(Color.BLACK)
            .strokeWidth(2);

I keep getting the same error at fillColor, strokeColor and strokeWidth
Eclipse doesn't give me any options to import anything. Any idea what could be wrong please?
The method fillColor(int) is undefined for the type MainActivity

A: Move the location of the semicolon to the end of your chain. You're ending your statement prematurely, which is why the compiler attempts to find fillColor() in MainActivity rather than CircleOptions.
CircleOptions circleOptions = new CircleOptions()
            .center(new LatLng(latitude, longitude))
            .radius(1000) // In meters
            .fillColor(Color.RED)
            .strokeColor(Color.BLACK)
            .strokeWidth(2);


text:
Q: GAE: Unable to update app: Bad authentication response: 404 Not Found Unable to deploy to GAE (java) today. I was able to deploy until yesterday evening. Anyone else has the same problem? how did you solve?
09-Mar-2016 11:15:04
java.lang.RuntimeException: Bad authentication response: 404 Not Found
09-Mar-2016 11:15:04
Unable to update app: Bad authentication response: 404 Not Found
thanks

A: I was having this same issue. As it turns out the authentication method (ClientLogin) I was using to deploy to appengine was deprecated (I was deploying using mvn gae:deploy). Google now wants us to use their new OAuth 2.0 authentication for deploying to appengine: https://cloud.google.com/appengine/docs/deprecations/clientlogin
To fix this issue I had to update my appengine maven plugin to use the latest version so I could deploy.
I added this to my pom.xml:
<plugin>
   <groupId>com.google.appengine</groupId>
   <artifactId>appengine-maven-plugin</artifactId>
   <version>1.9.34</version>
</plugin>

Then I used this command to deploy (instead of mvn gae:deploy):
mvn appengine:update

For more info you can check out this info on how to deploy to appengine: https://cloud.google.com/appengine/docs/java/gettingstarted/uploading

A: I had opened multiple google accounts. So, I did close all and deployed it again. It did deploy. It was my mistake.

A: *

*Install Google Plugin for Eclipse.

*Open your project in eclipse. Once you install the plugin successed, you will see a new button of "G" on eclipse buttons bar.

*Click the "G" button and then click "Deploy to App Engine".

*Done.


text:
Q: ping with packet size larger than 25152 failing? When I am trying to ping with packet size > 25152 I am getting 100% packet loss. can anyone please help me out on why is it happening ???
ping -c 1 -s 25153 time.nist.gov
--- ntp.glb.nist.gov ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms
ping -c 1 -s 25152 time.nist.gov
PING ntp.glb.nist.gov (64.236.96.53) 25152(25180) bytes of data.
25160 bytes from dtc-nist01.ntp.aol.com (64.236.96.53): icmp_req=1 ttl=45 time=76.8 ms
--- ntp.glb.nist.gov ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 76.887/76.887/76.887/0.000 ms

A: As very quick google shows you are exceeding amount of fragments (data) that fits into one packet. In order to support that you would have to change configuration on your machine (and possibly the remote) to utilize it.

A: No, it's not because of hardware, it's because of IP restriction or it could be because the data choking happening in the router that you were pinging. It will consider large packets as data packets and drops it. If you try small packets, it never shows you any drop because the device will prioratized the input as voice or video.


text:
Q: IIS Redirect rule based on multiple (but not all) conditions I have a rewrite that is set up to handle multiple different user agents, and I want to be able to match my rule on any of them. However, any url that matches one of these must also match another rule (an IP address). However, I can't find any documentation on how to do this. Can anyone make any suggestions on how I can do this?
Below is an example of what I'm trying to achieve. I know that this will fail because the conditions node has already been declared more than once.
So, in essence it's a redirect when any of the {HTTP_USER_AGENT} rules and any of the {REMOTE_ADDR} rules are matched.
<rule name="Mobile UA redirect" stopProcessing="true">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAny">
    <!-- Any of these can be matched -->
    <add input="{HTTP_USER_AGENT}" pattern="Android" />
    <add input="{HTTP_USER_AGENT}" pattern="BlackBerry" />
    <!-- ... more user agents... -->
  </conditions>
  <!-- Here, similarly, any one of these rules can be matched, but one of the rules above must also match one of the rules below. -->
  <conditions logicalGrouping="MatchAny">
    <add input="{REMOTE_ADDR}" pattern="127.0.0.1" />
    <add input="{REMOTE_ADDR}" pattern="192.168.0.1" />
  </conditions>
  <action type="Redirect" url="http://mob.mydomain.com/{R:0}" appendQueryString="true" />
</rule>

Any help on how I can do this would be greatly appreciated!

A: What about smth like the following, placed at the bottom:
<rule name="MobileRestricted" stopProcessing="true">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll">
    <add input="{REMOTE_ADDR}" pattern="127.0.0.1" negate="true" />
    <add input="{REMOTE_ADDR}" pattern="192.168.0.1" negate="true" />
  </conditions>
  <action type="None"/>
</rule>
<rule name="Mobile UA redirect" stopProcessing="true">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAny">
    <!-- Any of these can be matched -->
    <add input="{HTTP_USER_AGENT}" pattern="Android" />
    <add input="{HTTP_USER_AGENT}" pattern="BlackBerry" />
    <!-- ... more user agents... -->
  </conditions>
  <action type="Redirect" url="http://mob.mydomain.com/{R:0}" appendQueryString="true" />
</rule>

Not a single rule, but no more than two )


text:
Q: Do I need a keyring password on a luks encrypted single user machine? The title says it all but let me expand a bit more:
I'm wondering how the keyring password is protecting my keys. Sure, it encrypts the container file, so no one else can access it. But it is also decrypted after I have provided my keyring password. So in fact, while I'm logged in, the keys could be stolen by some malicious app (at least an app with root permissions should be able to).
Of course, I know, the key file itself is not replaced with a decrypted version after entering the password but it must be decrypted in memory.
The question is: Can malicious apps access data in my keyring while it is decrypted? If so, do I even need a password for my keyring when my disk is already luks encrypted and I'm the only one using my computer?
And, if a password would be more secure, is it possible to have it unlocked automatically, using my account password (or so) after I login?
(I'm not using a login manager, I'm automatically starting i3wm after logging in via TTY, so would be automatic unlocking possible for this setup too?)

A:
Can malicious apps access data in my keyring while it is decrypted?

In practice (currently), yes, they can. The current design (or lack thereof) of user sessions in Linux makes it difficult for gnome-keyring-daemon to determine what program is trying to access it; that's doable to some extent for compiled programs, but e.g. any app written in Python is indistinguishable from any other app written in Python. So although gnome-keyring did at first have an application whitelist, current versions no longer do.
Eventually this should be improved by app container projects such as Snap or Flatpak.

If so, do I even need a password for my keyring when my disk is already luks encrypted and I'm the only one using my computer?

I'd say yes.
As mentioned above, any program can just send a D-Bus message and ask gnome-keyring-daemon for any secret. (In some cases it even works as a feature.)
However, there have been quite a few security holes in which a vulnerable program (e.g. a web browser) could be used to steal your files, although still having no possibility of running commands or sending D-Bus messages. Malware has been known to steal people's unencrypted SSH keys (~/.ssh/id_rsa) or Bitcoin Core wallets.
In the same way, if it is not encrypted, you're leaving ~/.local/share/keyrings/login.keyring at risk of being stolen through web browser exploits and such.

(I'm not using a login manager, I'm automatically starting i3wm after logging in via TTY, so would be automatic unlocking possible for this setup too?)

Automatic unlocking of gnome-keyring is in all cases done through PAM. A module named pam_gnome_keyring.so receives your password as part of the login process, and starts the initial keyring daemon.
The PAM module should be added to /etc/pam.d, wherever your Linux distribution normally adds common modules, or just to the login file (which is specifically for console and telnet logins).
In the auth group (in the "Additional" block in Debian-style common-auth; as the last module otherwise) it will store the password in memory:
[...]
auth optional pam_gnome_keyring.so only_if=login

In the session group (again, "Additional" block for Debian, last module otherwise) it uses the stored password to start gnome-keyring-daemon:
[...]
session optional pam_gnome_keyring.so only_if=login auto_start


text:
Q: How to display the first line that contains a certain string in a text file unix? Was hoping someone can help out with this. I am trying to figure out how to display the first line that contains a certain string i.e. "computer" (first occurrence of "computer" in a txt file).  I would prefer to do this using grep.
I know grep "computer" somefile.txt
would display all of the lines including "computer".
I am eager to learn and if anyone has alternative ways I would like to hear!
Thx everyone

A: Use the match count option of grep
grep -m 1 "computer" somefile.txt

Note that grep is non standard across un*x's so while http://www.gnu.org/software/grep/ supports this, if your distro or unix does not this will not work.

A: Pipes are your friend:
grep "computer" somefile.txt | head -n1

A: Is this homework?
grep -v "computer" somefile.txt | head -n 1

Comes to mind the quickest.


text:
Q: Setting the result of a function to a variable in twig I have a function that generates an array containing menu items:
Item 1
  SubItem 1a
  SubItem 1b

Item2
  SubItem 2a
  ...

I have a twig extension that can return this as an array. I need to be able to set this array to a variable in twig, so that I can use it through out my template.
I have tried doing {% set myArray = {{ myFunction('menuname') }} %}
I also tried:
{% set myArray %}
  {{ myFunction('menuname') }}
{% endset %}

However, that did not work either. Is there a way to do this?

A: Got it!
Use {% set myArray = myFunction('menuname') %}


text:
Q: Catch cgi-like parameters within a servlet? I have a @WebServlet("/myServ"). How can I retrieve the browser path if I enter /myapp/myServ?param=123? Can I get the "query" like string somehow?

A: Unless I am missing something, HttpServletRequest#getQueryString should do that.


text:
Q: Can't get my HTML Canvas to fit 90% of the screen. Tried multiple scripts Please help. I am a bit of a dinosaur when it comes to coding. I used to mostly do HTML and a little bit of Java years back, but I recently started making a site for my comedy group, and have had some issue. First, I made an interactive imagemap using flash, which I know decently well, only to discover I am out of touch and flash doesn't work on a lot of smartphones and i-pads. So then I converted the .fla to HTML5 using Adobe Animate CC.
It seems to work fine, but I can't get the height and width to fit the screen (I want 85% width, and 90% height). I've looked on this site and seen a few different answers, that I have tried, but each time I can't get it to work. Please help.
Here is a link to my testpage:
www.standupseoul.com/test1.html
you should be able to the source, as well as the javascript.
 (yes, the height and width are specified right now, but when I alter, i can't get the image to change size):

A: Add this to your CSS style file
.mycanvas {
    width: 90%;
    height: 85%;
}

and class="mycanvas" to your canvas element.
The image looks a bit stretched, you might want to find a higher-quality replacement.


text:
Q: BuyItem method from Samsung Checkout SDK returns an error callback inside .NET application I'm having a problem with Samsung Checkout integration in out existing .NET TizenFX (TV) application.
I followed the instructions here: https://developer.samsung.com/smarttv/develop/tizen-net-tv/guides/samsung-checkout/implementing-the-purchase-process.html
First step where I request a product for sale goes through successfully. I get the product, parse its data and prepare all parameters to call the BuyItem method. Unfortunately the method returns an error callback, and no purchase GUI is shown in the application.
Error callback I get is:
 {
  "result": "FAIL",
  "optionalData": "{\n  \"OrderTotal\": \"7.45\",\n  \"OrderItemID\": \"myitemid\",\n  \"OrderTitle\": \"My Item Title\",\n  \"OrderCurrencyID\": \"USD\",\n  \"OrderCustomID\": \"123456789\"\n}"
 }

I also found that the error callback was returned somewhere in the process of preparing possible payments (according to stack trace):
Tizen.TV.Service.Billing.BillingPlugin.PaymentCallback()

Has anyone already integrated the Samsung checkout SDK and had similar problems?


text:
Q: How can I access calendars on my Mac with Java? I want to read data stored locally by the Apple Calendar app on my Mac (12.1 Monterey).
The data is stored in subdirectories of ~/Library/Calendars/ with one subdirectory per calendar.
The problem: When I try to get a list of files from there, Java returns null:
String userHomeDir = System.getProperty("user.home");
File calendarRoot = new File(userHomeDir + "/Library/Calendars/");
File[] calendars = calendarRoot.listFiles();
System.out.println("Number of files: " + calendars.length); // NPE thrown here

File permissions are as follows:

*

*~/Library: drwx------+ (owner: my user)

*~/Library/Calendars: drwxr-xr-x@ (owner: my user)

Listing files in Library works fine.
How can I access that folder?

A: Short answer
Give it up. Apple has made it next to impossible to elegantly get a Java app to read calendar data.
Long answer
Since some versions (Catalina?) the directory ~/Library/Calendars/ and all subdirectories (and files therein) are protected by MacOS using extended attributes, namely com.apple.quarantine.
It used to be possible to grant applications the specific right to access calendar data using System Settings - Security and Privacy - Privacy - Calendar. However, the manual +-Button has gone now.
What I will do is use some zsh script to export the desired calendar events to another directory and remove the com.apple.quarantine attribute from there, too.
This is not elegant and leaves the Java world, but for my case, having a Java command line application being started from a designated shell script, it works rather nicely.
Here's what I came up with:
#!/bin/zsh

calendars="/Users/yourUserName/Library/Calendars"
target="/Users/yourUserName/some/other/directory/Calendar_Export"

cd ${calendars}

calsource=""
for f in *.calendar
do
    linesFound=`grep -c '<string>Your Calendar Name</string>' ${f}/Info.plist`
    if [[ ${linesFound} -eq 1 ]]
    then
        echo "The relevant calendar resides at " ${f}", copying all events"
        calsource=${calendars}/${f}/Events
    fi
done

if [[ ${calsource} != "" ]]
then
    rm ${target}/*
    cp ${calsource}/* ${target}/
    xattr -d com.apple.quarantine ${target}/*
fi


text:
Q: How can I separate widgets on flutter without losing their properties? For now I have this

I want to achieve this desing

This is my code:
HomePageTimerUI .dart
class HomePageTimerUI extends StatefulWidget {
  const HomePageTimerUI({Key? key}) : super(key: key);

  @override
  State<HomePageTimerUI> createState() => _HomePageTimerUIState();
}

class _HomePageTimerUIState extends State<HomePageTimerUI>
    with TickerProviderStateMixin {
  late TabController _tabController;

  late Timer timer;
  late AnimationController controller;

  String get countText {
    Duration count = controller.duration! * controller.value;
    return controller.isDismissed
        ? '${controller.duration!.inHours.toString().padLeft(2, '0')}:${(controller.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(controller.duration!.inSeconds % 60).toString().padLeft(2, '0')}'
        : '${count.inHours.toString().padLeft(2, '0')}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void notify() {
    if (countText == '00:00:00') {
      _tabController.animateTo(1, duration: const Duration(milliseconds: 300));
    }
  }

  @override

  Widget build(BuildContext context) {
    return Container(
        height: 600,
        width: double.infinity,
        child: DefaultTabController(
            length: 3,
            child: Scaffold(
              appBar: AppBar(
                elevation: 0,
                backgroundColor: Colors.transparent,
                bottom: PreferredSize(
                  preferredSize: Size.fromHeight(55),
                  child: Container(
                    color: Colors.transparent,
                    child: SafeArea(
                      child: Column(
                        children: <Widget>[
                          TabBar(
                              controller: _tabController,
                              indicator: UnderlineTabIndicator(
                                  borderSide: BorderSide(
                                      color: Color(0xff3B3B3B), width: 4.0),
                                  insets: EdgeInsets.fromLTRB(
                                      12.0, 12.0, 12.0, 11.0)),
                              indicatorWeight: 15,
                              indicatorSize: TabBarIndicatorSize.label,
                              labelColor: Color(0xff3B3B3B),
                              labelStyle: TextStyle(
                                  fontSize: 12,
                                  letterSpacing: 1.3,
                                  fontWeight: FontWeight.w500),
                              unselectedLabelColor: Color(0xffD7D7D7),
                              tabs: [
                                Tab(
                                  text: "POMODORO",
                                  icon: Icon(Icons.work_history, size: 40),
                                ),
                                Tab(
                                  text: "SHORT BREAK",
                                  icon: Icon(Icons.ramen_dining, size: 40),
                                ),
                                Tab(
                                  text: "LONG BREAK",
                                  icon: Icon(
                                      Icons.battery_charging_full_rounded,
                                      size: 40),
                                ),
                              ])
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              body: TabBarView(
                controller: _tabController,
                children: <Widget>[
                  Center(
                    child: StartPomodoro(),
                  ),
                  // Center(
                  //   child: ShortBreak(),
                  // ),
                  // Center(child: LongBreak()),
                ],
              ),
              bottomNavigationBar: Container(
                height: 110,
                color: Color(0xffFAFAFA),
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 20),
                  child: GNav(
                    iconSize: 40,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    backgroundColor: Color(0xffFAFAFA),
                    color: Color(0xffD7D7D7),
                    activeColor: Color(0xff3B3B3B),
                    tabBackgroundColor: Color(0xffF0F0F0),
                    gap: 8,
                    onTabChange: (index) {
                      print(index);
                    },
                    padding: EdgeInsets.all(15),
                    tabs: [
                      GButton(
                        icon: Icons.settings,
                        text: 'Settings',
                      ),
                      GButton(
                        icon: Icons.person,
                        text: "Profile",
                      ),
                      GButton(
                        icon: Icons.task,
                        text: "Tasks",
                      ),
                      GButton(
                        icon: Icons.show_chart,
                        text: "Performance",
                      ),
                    ],
                  ),
                ),
              ),
            )));
  }
}

startpomodoro.dart
class StartPomodoro extends StatefulWidget {
  const StartPomodoro({Key? key}) : super(key: key);

  @override
  State<StartPomodoro> createState() => _StartPomodoroState();
}

class _StartPomodoroState extends State<StartPomodoro>
    with TickerProviderStateMixin {

  List<bool> isSelected = [true, false];
  late Timer timer;
  late AnimationController controller;

  String get countText {
    Duration count = controller.duration! * controller.value;
    return controller.isDismissed
        ? '${controller.duration!.inHours.toString().padLeft(2, '0')}:${(controller.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(controller.duration!.inSeconds % 60).toString().padLeft(2, '0')}'
        : '${count.inHours.toString().padLeft(2, '0')}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  double progress = 1.0;
  bool LongBreak = true;

  void notify() {
    if (countText == '00:00:00') {}
  }

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 0),
    );
    controller.addListener(() {
      notify();
      if (controller.isAnimating) {
        setState(() {
          progress = controller.value;
        });
      } else {
        setState(() {
          progress = 1.0;
          LongBreak = true;
        });
      }
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override

  Widget build(BuildContext context) {

    ThemeData themeData = Theme.of(context);
    return Scaffold(
              backgroundColor:
                  LongBreak ? const Color(0xffD94530) : const Color(0xff6351c5),
              body: GestureDetector(
                onTap: () {
                  if (controller.isDismissed) {
                    showModalBottomSheet(
                      context: context,
                      builder: (context) => Container(
                        height: 300,
                        child: CupertinoTimerPicker(
                          initialTimerDuration: controller.duration!,
                          onTimerDurationChanged: (time) {
                            setState(() {
                              controller.duration = time;
                            });
                          },
                        ),
                      ),
                    );
                  }
                },
                child: AnimatedBuilder(
                    animation: controller,
                    builder: (context, child) {
                      return Stack(
                        children: <Widget>[
                          Align(
                            alignment: Alignment.bottomCenter,
                            child: Container(
                              color: const Color(0xffD94530),
                              height: controller.value *
                                  MediaQuery.of(context).size.height *
                                  0.640,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Expanded(
                                  child: Align(
                                    alignment: Alignment.bottomCenter,
                                    child: Align(
                                      alignment: FractionalOffset.bottomCenter,
                                      child: SingleChildScrollView(
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.end,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: <Widget>[
                                            Text(
                                              countText,
                                              style: const TextStyle(
                                                fontSize: 90.0,
                                                color: Color(0xffFAFAFA),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Column(

                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.stretch,
                                    children: [
                                      AnimatedBuilder(
                                          animation: controller,
                                          builder: (context, child) {
                                            return const Padding(
                                              padding: EdgeInsets.symmetric(
                                                  vertical: 2.0,
                                                  horizontal: 15.0),
                                            );
                                          }),
                                      AnimatedBuilder(
                                          animation: controller,
                                          builder: (context, child) {
                                            return Padding(
                                              padding: const EdgeInsets.symmetric(
                                                  vertical: 2.0,
                                                  horizontal: 15.0),
                                              child:
                                                  FloatingActionButton.extended(
                                                      backgroundColor:
                                                          const Color(0xffFAFAFA),
                                                      onPressed: () {
                                                        if (controller
                                                            .isAnimating) {
                                                          controller.stop();
                                                          setState(() {
                                                            LongBreak = false;
                                                          });
                                                        } else {
                                                          controller.reverse(
                                                              from: controller
                                                                          .value ==
                                                                      0
                                                                  ? 1.0
                                                                  : controller
                                                                      .value);
                                                          setState(() {
                                                            LongBreak = false;
                                                          });
                                                        }
                                                      },
                                                      icon: Icon(
                                                        controller.isAnimating
                                                            ? Icons.pause
                                                            : Icons.play_arrow,
                                                        color:
                                                            const Color(0xff3B3B3B),
                                                      ),
                                                      label: Text(
                                                        controller.isAnimating
                                                            ? "Pause"
                                                            : "Start",
                                                        style: const TextStyle(
                                                            color: Color(
                                                                0xff3B3B3B)),
                                                      )),
                                            );
                                          }),
                                      const SizedBox(width: 20, height: 100),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      );
                    }),
              ),
            );}

}

class CustomTimerPainter extends CustomPainter {
  CustomTimerPainter({
    required this.animation,
    required this.backgroundColor,
    required this.color,
  }) : super(repaint: animation);

  final Animation<double> animation;
  final Color backgroundColor, color;

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = backgroundColor
      ..strokeWidth = 10.0
      ..strokeCap = StrokeCap.butt
      ..style = PaintingStyle.stroke;

    canvas.drawCircle(size.center(Offset.zero), size.width / 2.0, paint);
    paint.color = color;
    double progress = (1.0 - animation.value) * 2 * math.pi;
    canvas.drawArc(Offset.zero & size, math.pi * 1.5, -progress, false, paint);
  }

  @override
  bool shouldRepaint(CustomTimerPainter old) {
    return animation.value != old.animation.value ||
        color != old.color ||
        backgroundColor != old.backgroundColor;
  }

If I cut and paste the start widget to the HomePageTimerUI I cant do it well because the startpomodoro page has all the controllers to control the timer and animations, so how can I replace the start / pause button to the gnav widget maintaining its height and also initialize the timer?
Thank you for any help you can offer

A: It's difficult to precisely figure out from the code produced. Because of too many widgets and wrong indentations. I would give suggestions based on rough insights.
If you want to seperate two elements use Spacer that will do the job for you, Otherwise try the following approach.
Present approach (roughly)
Column
 |_ Timer Container
 |_ Floating button

to
Correct appraoch
Column
 |_ Expanded
   |_ Center
     |_ Timer Container
 |_ Floating Button


text:
Q: Amavis crashing for unknown reason Amavis is crashing for an unknown reason. Luckily, we have Monit installed and it restarts the service within a minute, but that's just a bandaid on the issue. We need to fix the real problem.
Right before crashing, the following log entries exist in /var/log/syslog:
Feb 22 17:02:20 hoa systemd[1]: Stopping LSB: Starts amavisd-new mailfilter...
Feb 22 17:02:20 hoa amavis[23039]: (23039-01) (!)TempDir removal: tempdir is to be PRESERVED: /var/lib/amavis/tmp/amavis-20170222T170218-23039-CLjT8mUN
Feb 22 17:02:20 hoa amavis[22755]: (22755-08) (!)TempDir removal: tempdir is to be PRESERVED: /var/lib/amavis/tmp/amavis-20170222T170035-22755-v7F3P0kr
Feb 22 17:02:20 hoa amavis[21924]: (21924-20) (!)TempDir removal: tempdir is to be PRESERVED: /var/lib/amavis/tmp/amavis-20170222T165050-21924-Vi1AOnu5
Feb 22 17:02:20 hoa amavis[22053]: (22053-14) (!)TempDir removal: tempdir is to be PRESERVED: /var/lib/amavis/tmp/amavis-20170222T165124-22053-V_dDmOmV
Feb 22 17:02:20 hoa postfix/10025/smtpd[22719]: disconnect from localhost[127.0.0.1]
Feb 22 17:02:20 hoa postfix/10025/smtpd[22759]: disconnect from localhost[127.0.0.1]
Feb 22 17:02:20 hoa postfix/10025/smtpd[22718]: disconnect from localhost[127.0.0.1]
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22710]: B07E111FD54: to=<user1@example.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=17, delays=0.23/14/0.31/2.3, dsn=4.3.2, status=deferred (host 127.0.0.1[127.0.0.1] said: 421 4.3.2 Service shutting down, closing channel (in reply to end of DATA command))
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22710]: connect to 127.0.0.1[127.0.0.1]:10024: Connection refused
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22709]: B07E111FD54: to=<user2@example.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=17, delays=0.23/14/0.08/2.6, dsn=4.3.2, status=deferred (host 127.0.0.1[127.0.0.1] said: 421 4.3.2 Service shutting down, closing channel (in reply to end of DATA command))
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22709]: connect to 127.0.0.1[127.0.0.1]:10024: Connection refused
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22708]: BFF1D11FD58: to=<user3@example.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=17, delays=0.23/15/0.03/2.2, dsn=4.3.2, status=deferred (host 127.0.0.1[127.0.0.1] said: 421 4.3.2 Service shutting down, closing channel (in reply to end of DATA command))
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22708]: connect to 127.0.0.1[127.0.0.1]:10024: Connection refused
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22707]: 8CDCC11FCF4: to=<user4@example.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=17, delays=0.38/14/0.11/2.6, dsn=4.3.2, status=deferred (host 127.0.0.1[127.0.0.1] said: 421 4.3.2 Service shutting down, closing channel (in reply to end of DATA command))
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22707]: connect to 127.0.0.1[127.0.0.1]:10024: Connection refused
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22710]: BFF1D11FD58: to=<user5@example.com>, relay=none, delay=17, delays=0.23/17/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22707]: 16B531207A6: to=<user6@example.com>, relay=none, delay=17, delays=0.42/17/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22710]: 16B531207A6: to=<user7@example.com>, relay=none, delay=17, delays=0.42/17/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22709]: E9CA411F8BA: to=<user8@example.com>, relay=none, delay=4.9, delays=0.53/4.4/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)
Feb 22 17:02:20 hoa postfix/smtp-amavis/smtp[22708]: E9CA411F8BA: to=<user9@example.com>, relay=none, delay=4.9, delays=0.53/4.4/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)
Feb 22 17:02:20 hoa amavis[23084]: Stopping amavisd: amavisd-new.
Feb 22 17:02:20 hoa systemd[1]: Stopped LSB: Starts amavisd-new mailfilter.
Feb 22 17:02:21 hoa systemd[1]: Starting LSB: Starts amavisd-new mailfilter...

At this point, Monit kicks in and Amavis restarts.
I've done quite a bit of searching, but can't seem to find the issue. It's possible that the server is running low on memory, but there doesn't appear to be any errors logged about being unable to allocate memory. Therefore I'm not sure if that is truly the problem or not.
Any help would be appreciated.

A: To follow up with this question, I believe that the issue was indeed a shortage of memory. We doubled the memory for our server and the issue has yet to arise again. I'm surprised, however, that none of the log messages indicated that memory was the culprit.


text:
Q: Event subscription without addEventListener() There is an jsfiddle example of the Observer pattern in Javascript.
How Event object handles event dispatching? Where is the magic. Want to learn this but don't where to start reading. It would be great to write simple example with button and input or any other 2 plain html elements. I always used to add event listeners.


text:
Q: Why can't Node.js server read CSS if it is located on the higher lever than HTML? For some reason, I can only access my CSS files in my Node.js app if they are located in the same folder or deeper than HTML.
Folder structure that works:

I can assess CSS here using the css/style.css path as it is located in the sub-folder of the HTML folder. It also works for the nested sub-folders.
Folder structure that doesn't work:

But when I try to move CSS on the level higher, it can't be accesses using ../css/style.css, an error message about the incorrect MIME type (text/html) appears and the style doesn't apply.
Am I missing something or this is intended?

A: The issue might be with path, it must be
<link rel="stylesheet" type="text/css" href="../css/style.css">


text:
Q: Multiple payment gateways/processor options for multiple Vendors I am using a WordPress plugin to create a multi-vendor marketplace.  However, I would like the Vendors to be able to configure any payment gateway of their choosing (eg: PayPal, Authorize.net, etc) into their store for payment processing.
Thanks


text:
Q: iot edge best practise
*

*We have around 9000 devices in field.

*This devices are at groups of 1-100 at customers on prem.

*The devices are not capable of azure-iot-sdk integration.

*The devices have a webservice API.

*The devices should appear as first-class devices in azure.

We like the iot edge module provisiong feature.
We want to evaluate if modules could gather data from the devices and send them to IoTHub for further processing.
We found this feature overview of IoTEdge: https://learn.microsoft.com/de-de/azure/iot-edge/iot-edge-as-gateway
Pattern Transparent and Protocol translation are out of scope due to above facts. Pattern Identity translation seems to fit.
We want a 1 to 1 relationship between module and real device.
Therefor we assume the following POC with the hope of clarification and best practise:

*

*we implement a iot edge module (azure-iot-sdk-java)

*we open module connection to iotedge and suscribe to desired properties

*the module identity gets as desired property the ip of the real device and the azure device identitiy connection string.

*we open device connection to iotedge by adding GatewayHostName to the device connection string as described here https://learn.microsoft.com/de-de/azure/iot-edge/iot-edge-as-gateway

*we request data from the real device and send them via azure device identity.

This somewho mixes up two patterns and seems kind of odd to us.
Can you point out best practises and risks with this approach?

A: Yes, I agree with that Pattern Identity translation could fit your scenario.
There are three patterns for using an IoT Edge device as a gateway: transparent, protocol translation, and identity translation, you can refer to this link to get more introduction about these three pattern.


text:
Q: How to turn off xscreensaver automatically while watching Flash video? Can I configure Flash to automatically disable xscreensaver while it's playing video? Or, conversely, configure xscreensaver not to trigger while Flash is playing video?
 I've seen this question on disabling the screensaver manually.

A: I don't think you can do this in the settings for either flash or xscreensaver.  However, is it possible that you are streaming video from another site?  You could write a script that ran netstat and looked for established connections on a certain port or maybe site and then xset s off; xset -dpms ; sleep XXX, then reenable.  Then just background the script.

A: You'll find different scripts in order to do that on ubuntu forum. It's quite hacky and it does not seem that a clean way exist.


text:
Q: Trouble with a button that calls a subroutine that uses a function I am currently coding in VBA and have run into an issue.
I have created a button that calls in a number of subroutines. It runs perfectly until it reaches a subroutine that uses a function. When I run the sub in the developer tab, it runs fine; however, when I call the subroutine using a button I get this error:
"Compile Error:
Method or data member not found."
Do you know how to fix this?
Below is the subroutine and function being used:
Sub DiscountRate()

    'Set Dimensions
    Dim ws As Worksheet
    Dim i As Integer
    Dim Counter As Integer
    Dim Value As Integer
    Dim tempcount As Double

    'Set parameters
    Set SummarySheet = Sheets("Summary & Inputs")
    Set ExpectedCompSheet = Sheets("Expected Compensation")
    Set WorkYears = SummarySheet.Range("C40")
    Set DiscountSheet = Sheets("Treasury Rates")
    Set DiscountRateRange = DiscountSheet.Range("B7:L7")

    'Clear column
    ExpectedCompSheet.Range("H13:I113").Clear
    'Clear color
    ExpectedCompSheet.Range("H13:I113").Interior.Color = xlNone

    'If prejudgment interest is filled, count and fill discount rate cells
    i = 1
    For Counter = 1 To WorkYears
        If IsEmpty(ExpectedCompSheet.Cells(12 + Counter, 7)) = False Then
            ExpectedCompSheet.Cells(12 + Counter, 8).Interior.ColorIndex = 16
            ExpectedCompSheet.Cells(12 + Counter, 9).Interior.ColorIndex = 16
            i = i + 1
        End If
    Next Counter

    'Create increasing range to sum fractions of years
    IncreasingRange = ExpectedCompSheet.Range(ExpectedCompSheet.Cells(12 + i, 5), _
                                              ExpectedCompSheet.Cells(11 + i + Counter, 5))

    'Find discount rate associated with increasing years
    For Counter = 1 To (WorkYears + 2 - i)
        IncreasingRange = ExpectedCompSheet.Range(ExpectedCompSheet.Cells(12 + i, 5), _
                                                  ExpectedCompSheet.Cells(11 + i + Counter, 5))
        tempcount = Application.WorksheetFunction.Sum(IncreasingRange)
        ExpectedCompSheet.Cells(11 + i + Counter, 8) = getclosest(DiscountRateRange, tempcount)
    Next Counter

    For Counter = 1 To (WorkYears + 2 - i)
        If ExpectedCompSheet.Cells(11 + i + Counter, 8) = 0.08 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "1 Month"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("B9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 0.25 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "3 Month"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("C9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 0.5 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "6 Month"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("D9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 1 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "1 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("E9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 2 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "2 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("F9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 3 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "3 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("G9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 5 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "5 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("H9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 7 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "7 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("I9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 10 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "10 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("J9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 20 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "20 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("K9") / 100
        ElseIf ExpectedCompSheet.Cells(11 + i + Counter, 8) = 30 Then
            ExpectedCompSheet.Cells(11 + i + Counter, 8) = "30 Year"
            ExpectedCompSheet.Cells(11 + i + Counter, 9) = DiscountSheet.Range("L9") / 100
        End If
    Next Counter

End Sub

Function getclosest(ByVal rng As Range, tgt As Double) As Double
    t = WorksheetFunction.Max(rng)
    For Each r In rng
        u = Abs(r - tgt)
        If u < t Then
            t = u
            getclosest = r
        End If
    Next
End Function

I am using a button with code:
Sub CalculateExpectedComp()

Call Module1.ExpectedCompYear
Call Module1.ExpectedCompPeriod
Call Module1.ExpectedCompAge
Call Module1.ExpectedCompPaymentAnnual
Call Module1.ExpectedCompYearFrac
Call Module1.ExpectedCompPartialYearComp
Call Module1.PrejudgmentInterest
Call Module1.DiscountRate
Call Module1.PresentValueFactor
Call Module1.PV
Call Module1.CumulativeValue
Call Module1.Formatting

End Sub

The issue occurs when "Call Module1.DiscountRate" runs.


text:
Q: FileNotFoundException when ussing FileReader to find a resource in a java ee6 dynamic project I am getting the all well known FileNotFoundException when i try to call a .txt file that holds some text. I used various path convinations, but i dont get the right one.
Here is how i call it:
private String generateActivationLinkTemplate() {
    String htmlText = "";
    try {
        Scanner scanner = new Scanner(new FileReader(
                "/web/emailActivationTemplate.txt"));
        while (scanner.hasNextLine()) {
            htmlText += scanner.nextLine();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return htmlText;
}

The full path to the file looks like this:
 C:\jee6workspace\BBS\WebContent\web\emailActivationTemplate.txt

How should i tell my program to find this file in the most flexible way?

A: One way - access to file through servlet context, f.e. i'm use in my Wicket project
final ServletContext ctx = ((WebApplication) getApplication()).getServletContext();
final File reportFile = new File(ctx.getRealPath("/reports/pivotTable.jasper"));

in your case
Scanner scanner = new Scanner(new FileReader(
            new File(ctx.getRealPath("/web/emailActivationTemplate.txt"))));

so you only need to get your servlet context in proper place
Other way - try to access to file through classpath.


text:
Q: Adding lots of decimals when value is inside a key: (array) object Edit: this is in python 2.7.7
Has anyone come across this? I need to serialise an key-value pair object into a string, in which each key contains a float.
There can be any number of entries (I demonstrate just one, "Test", in this example).
It seems that when evaluating the whole object, Python can add decimals to the value, whereas when we look at those exact same values independantly (outside of the object), they appear "normal".
I need a way to make the final, serialised object contain the original values (0.08 in this case) ; or a means to force them to 2DPs.
userConstraints = {
        "test": 0.08
    }

print userConstraints["test"] # Appears ok here
print str(userConstraints) # Has extra DPs here. Why? How to fix?

Output:
0.8
{'test': 0.080000000000000002}

Serialisation logic (on the other side)
obj=ast.literal_eval(theSerialisedString)

Output of serialised obj
{'test': 0.080000000000000002}

A: So, all in all, your version and implementation of Python has a very precise repr() for floating-point numbers. (We can tell it's not a vanilla CPython 2.7.7, since the shorter floating-point repr() from Python 3.1 has been backported into CPython 2.7.0, and that version doesn't do reprs like you say it does.)
Your wire format for serialization is Python repr(), and you want to round off some of those lengthy floats, because reasons.
That's no problem, since Python comes with reprlib - a module for customizing repr (confusingly repr in Python 2).
Et voilà:
import repr as reprlib  # Python 2
import reprlib          # Python 3

class TruncatedFloatRepr(reprlib.Repr):
    def repr_float(self, x, level):
        v = repr(x)
        if "." in v:
            decimals_after_dot = len(v.partition(".")[-1])
            if decimals_after_dot > 5:  # Too many decimals? Truncate!
                return "%.2f" % x
        # Otherwise, use the vanilla `repr`.
        return v

userConstraints = {
    "test": 0.08000000004,
    "hello": ["world", "beep", 3.0, "boop"],
    "one": ("two", 1.1),
}

print(TruncatedFloatRepr().repr(userConstraints))

The output is
{'hello': ['world', 'beep', 3.0, 'boop'], 'one': ('two', 1.1), 'test': 0.08}

and of course you might want to consider changing that 5 to something else, or maybe count the number of zeroes in the decimal part, or whatever suits your business logic fancy. As it is, this implementation will just always truncate numbers with too much decimal precision, and that's likely not what you really want.


text:
Q: parsing a masive csv file having a problem with bad version number of the software how do i format quickly 5 million rows Here's a sample of my data:
from io import StringIO

data = StringIO("""software,version
Visual C++ Minimum Runtime,11.0.61030
Visual C++ Minimum Runtime,11.0.61030
Visual C++ Minimum Runtime,11.0.61030.0.0.0.0""")

Notice that the last record the version number has 0.0.0.0 in it .
How can I get to xx.yy.zz first front 3 characters and clean up the remaining data?
As an example: Visual C++ Minimum Runtime,11.0.61030.0.0.0.0 should be truncated to:
"Visual C++ Minimum Runtime,11.0.61030"

Is there an efficient way to accomplish this?

A: You could use generators to load the file row by row and then write the truncated rows to a backup file.
eg.
import csv

filename = "foo.csv"

def get_row(filename):
    with open(filename, "rb") as csvfile:
        data = csv.reader(csvfile)
        yield next(data)

with open('truncated.csv','wb') as truncatedcsv:
    writer = csv.writer(truncatedcsv, delimiter=',')
    for row in get_row(filename):
        truncated_row = # your truncation logic
        writer.writerow(truncated_row)

Don't forget to rename the new file and delete the old one.


text:
Q: How to create PKCS #12 on ios -> more generally speaking how to transport rsa private/public key pair cross platform I have the following use case: user is syncing some data that a server used in exchange(sync) should not be trusted with.
The data is AES encrypted as following with 32 random bytes
the very same 32 bytes are encrypted with RSA public key and prefix that aes blob
now on the receiving end the user is supposed to enter his master password
to unlock the RSA private key to decode that 256 byte prefix to get the 32 byte
aes password. In a house that was built by Jack
Soooo, given the (idiotic imho) requirement that this should work cross
platform (how many folks do you know who have both vedroid and ios phones
or folk who transition from ios to android?)
I need some way to transport the private and public key to the
sync recipient device. Private key obviously needs to be well protected.
Thoughts on how to do handle all of this?
Android guy denies knowledge on how to make use of the binary public
key (happens to be 270 bytes extracted using
 - (NSData *)getPublicKey {

NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];

// Set the public key query dictionary.
[queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass];
[queryPublicKey setObject:self.publicTag forKey:(id)kSecAttrApplicationTag];
[queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData];

CFTypeRef inTypeRef = NULL;
// Get the key bits.
OSStatus sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, &inTypeRef);

NSData * publicKeyBits = nil;
if (sanityCheck == errSecSuccess)
{
    publicKeyBits = (__bridge NSData *)inTypeRef;
}
return publicKeyBits;
}

and private key that somehow comes out at odd 1200 bytes using this
NSString *md5digest(NSString *masterpassword)
{
const char * pointer = [masterpassword UTF8String];
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];

CC_MD5(pointer, (CC_LONG)strlen(pointer), md5Buffer);

NSMutableString *string = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    [string appendFormat:@"%02x",md5Buffer[i]];

return string;
}

- (NSData *)getPrivatekey:(NSString*)md5digest
{
NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];

// Set the public key query dictionary.
[queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass];
[queryPublicKey setObject:self.privateTag forKey:(id)kSecAttrApplicationTag];
[queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData];

CFTypeRef inTypeRef = NULL;
// Get the key bits.
OSStatus sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, &inTypeRef);

NSData * publicKeyBits = nil;
if (sanityCheck == errSecSuccess)
{
    publicKeyBits = (__bridge NSData *)inTypeRef;

    NSData *key = [md5digest dataUsingEncoding:NSUTF8StringEncoding];
    NSData *aes = [IDBAES256 AES256EncryptWithKey:key data:publicKeyBits];
    return aes;
}
return publicKeyBits;
}

claims his libraries on android need modulus and exponent to create RSA keypair
and he has no way to create them out of an array of uchars.
Thoughts?
I can obviously read .p12 just fine per
https://developer.apple.com/library/ios/documentation/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html
but I see no API to pack two keys into a ceritificate on iOS
sorry about long winded question.
I've tried to keep the amount of code to the minimum.

A: I've ended up using openssl to close gaps that security framework has in the functionality outlined in the OP


text:
Q: python context menu: edit with IDLE работает некорректно Выбираю файл1.py. Жмякаю edit with IDLE и вместо ожидаемого - крутится курсор и скрыто запускается совсем другой файл2.py(не вирус и т.д.), в процессах появляется python. И работает в фоне этот файл2.py распрекрасно. Невзирая на то, что его файла уже нет. Файл2 работал с async и await - telegrambot.
Если просто запускать IDLE - все ок.
В чем может быть проблема?


text:
Q: Python version >= 3.4 do not deliver a working PIP utility. It seems impossible to add it afterward Python3.6 installs PIP but it is unreachable as it is installed. There is no code which will invoke in the state that it is installed. I have read every advice possible on this issue without success!
Not even the upgrade will work...
user@loco:~/devstack$ pip install --upgrade pip

A: Yes, Python3.6 installs PIP but it is unreachable as it is installed.  if there is a way to trigger the installed PIP it is a mystery to me!  After much agony, I have found a way to update that installed version, which is PIP version 9.xxx. Here is what worked for me.
root@bx:/usr/local/lib/python3.6/site-packages # python -m pip install --upgrade pip

That command created a PIP which now works properly from any location on my FreeBSD server!  Delivered by the Python 3.6 install the PIP only works by invoking Python first.  Once invoked that way it updates to version 9 with the latest.  In my case, it was version 19.xxx.  What is interesting is that it immediately became global and accessible from everywhere, so no need to play with the ports etc.
Clearly, the tools installed simply do not work properly, as installed with Python3.6. The only way to run them is to invoke Python and the desired python files as you can see in the command issued.  Once the update is called, however, the new PIP works globally without having to invoke Python3.6 explicitly...
P.S.  Keep in mind that if your command "python" invokes python2.7 you will not be able to complete your upgrade.  For that you will have to mess with your ports or invoke the command I supplied with Python3.6 or whatever invokes your version 3.x python.


text:
Q: Create a function which takes in a float as input and returns a string containing a number Create a function called format_currency which takes in a float as input and returns a string containing the number with a $ in front of it, with 2 decimal places.
i got no idea what i have done
def format_currency()
format("format_currency")
format_currency = float(input("Enter amount"))
print ("$" , format_currency)

A: Here you go
pi = 3.1415926535
def format_currency(f):
    return '$%.2f' % f

print(format_currency(pi)) # $3.14

A: You can do that something like this
def formatCurrency(amount):
    return "${0:.2f}".format(amount)

amount = float(input())
print(formatCurrency(amount))

A: It's important that you validate whether the number is a float or not. Expanding on E. Dogan's answer:
def format_currency(amount):
    try:
        float(amount)
        return '$%.2f' % float(amount)
    except ValueError:
        return "Not a number"

print(format_currency(3)) # $3.00
print(format_currency(3.123)) # $3.12
print(format_currency("not a number")) # Not a number
print(format_currency("3")) # $3.00

Also check: How do I check if a string is a number (float)?

A: when i understand your question correct you need  this
def format_currency(amount): # input argmuents are in the braces ()
    if type(amount) is float
        return f'${amount:.2f} # with return we can return values from a function
    else:
        raise ValueError("Amount must be a float")

# to use the function
money = format_currency(3.1234) # input arguments are passed in the braces ()
print("i have", money)

the f''  part is called f strings and is special syntax for format strings in Python 3.x.
The thing in curly braces {} is evaluated after the double dot : you can give a format specification so here its .2f which means only 2 decimal places


text:
Q: Best and Secure way to upload file using php This is my first Question on Stackoverflow.
I spend my many hour on google to find what is the most secure way to upload file in PHP. there i found some techniques like check file extension, rename file or many other, so kindly tell me if there are any other options for same.

A: This question is already asked here.
but you can use my own code for same it is simple and secure.
function hc_upload($f,$username='',$verify_type=1,$size=2048)
{
    $f=$_FILES[$f];
    $file_name=strtolower($f['name']);
    $file_type=strtolower($f['type']);
    $file_size=strtolower($f['size']);
    $file_extenstion =end(explode('.',$file_name));
    $file_extenstion2=strtolower(pathinfo(basename($file_name),PATHINFO_EXTENSION));

    if($file_extenstion2!=$file_extenstion){
        $err["error"]=true;
        $err["message"]="Invalid file extension.";
        return $err;
    }
    if($file_size > $size*1000){
        $err["error"]=true;
        $err["message"]="File is too large.";
        return $err;
    }

    $ext_verify=0;
    if(gettype($verify_type)!='array')
    {
        $verify_type=(string)$verify_type;
        if((strpos($verify_type,"1") > -1 || $verify_type=="*") &&  $ext_verify==0)
        {
            $mimes['ext']=array("jpg","jpeg","gif","png");
            $mimes['mime']=array("image/jpg","image/jpeg","image/gif","image/png");
            if(in_array($file_extenstion,$mimes['ext']) && in_array($file_type,$mimes['mime'])){$ext_verify=1;}
        }
        if((strpos($verify_type,"2") > -1 || $verify_type=="*") &&  $ext_verify==0)
        {
            $mimes['ext']=array("doc","docx","pdf","xls","xlsx","ppt","pptx");
            if(in_array($file_extenstion,$mimes['ext'])){$ext_verify=1;}
        }

        if((strpos($verify_type,"3") > -1 || $verify_type=="*") &&  $ext_verify==0)
        {
            $mimes['ext']=array("mp3","wav","weba","3gp","mp4","mov","mpeg","avi");
            $mimes['mime']=array("audio/mpeg","audio/wav","audio/webm","audio/3gpp","video/3gpp","video/mp4","video/quicktime","video/mpeg","video/x-msvideo");
            if(in_array($file_extenstion,$mimes['ext']) && in_array($file_type,$mimes['mime'])){$ext_verify=1;}
        }
    }
    else
    {
        if(array_key_exists("mime",$verify_type) && array_key_exists("ext",$verify_type)){
            if(in_array($file_extenstion,$verify_type['ext']) && in_array($file_type,$verify_type['mime'])){$ext_verify=1;}
        }
        elseif(array_key_exists("ext",$verify_type)){
            if(in_array($file_extenstion,$verify_type['ext'])){$ext_verify=1;}
        }
        elseif(array_key_exists("mime",$verify_type)){
            if(in_array($file_type,$verify_type['mime'])){$ext_verify=1;}
        }
        else{
            if(in_array($file_extenstion,$verify_type)){$ext_verify=1;}
        }
    }

    if($ext_verify==0){
        $err["error"]=true;
        $err["message"]="Seems your file is not valid";
        return $err;
    }

    $upload_dir='upload/'.$username.'/';
    if(!is_dir($upload_dir)){
        if(!mkdir($upload_dir,0777,true)){
            $err["error"]=true;
            $err["message"]="Unknown error, kindly contact admin";
            return $err;
        }
    }

    $upload_file=$upload_dir.sha1_file($f['tmp_name']);
    if(!file_exists($upload_file)){
        if(!move_uploaded_file($f['tmp_name'], $upload_file)){
            $err["error"]=true;
            $err["message"]="Unknown error, kindly contact admin";
            return $err;
        }
    }

    $err["error"]=true;
    $err["message"]="SUCCESS";
    $err["dir"]=$upload_file;
    return $err;
}

And HTML Sample Code is
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

So simply call this function in php
hc_upload('fileToUpload','',123)
you can create folder for each username by giving value two second parameter
and third parameter two check for file is image or document or audio/video media and also can pass array of extensions for manually check


text:
Q: Como habilitar e desabilitar um um input do tipo text após um valor selecionado no combobox Meu jQuery

 < script >
   $(document).ready(function() {

     var tipo = $("#idTipoParticipante option:selected").text();

     if (tipo == 'Personagem') {

       $("#enable").click(function() {
         // habilitando o campo
         $('#personagem').attr("disabled", '');
         // retornando a cor padrao
         $('#personagem').css("background-color", "#FFF");

       });

     } else if (tipo == 'Tecnico') {
       // campo desabilitado
       $('#personagem').attr("disabled", true);
       // cor de fundo para o campo
       $('#personagem').css("background-color", "#cccccc");

     }

   }); < /script>

Meu Select

<select class="form-control" name="idTipoParticipante" id="idTipoParticipante">
  <% List<TipoParticipante>listTipoParticipante = tipoParticipanteController.retornarListaTipoParticipante(); for (int i = 0; i
    < listTipoParticipante.size(); i++) { %>
      <option value="<%=listTipoParticipante.get(i).getIdTipoParticipante()%>">
        <%=listTipoParticipante.get(i).getDescricaoTipoParticipante()%>
      </option>

      <% } %>
</select>

Meu input

<input type="text" class="form-control" id="personagem" name="personagem" placeholder="informe a personagem...">

A: Faça a verificação no evento change no campo select:

$('#idTipoParticipante').on('change', function() {
  var tipo = $(this).find('option:selected').text().trim();
  if(tipo == 'Personagem') {
   $('#personagem').prop("disabled", false);
  }
  else if(tipo == 'Tecnico') {
   $('#personagem').prop("disabled", true);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="form-control" id="personagem" name="personagem" placeholder="informe a personagem...">
<select id="idTipoParticipante">
  <option></option>
  <option value="">
    Personagem
  </option>
  <option value="">
    Tecnico
  </option>
</select>

EXEMPLO no jsfiddle

A: Banguela,
um exemplo mais simples do que você publicou seria:
<select class="form-control" name="idTipoParticipante" id="idTipoParticipante">
  <option value="0">Personagem</option>
  <option value="1">Tecnico</option>
</select>

<input type="text" class="form-control" id="personagem" name="personagem" placeholder="informe a personagem...">

JavaScript:
$(document).ready(function() {
    $('#idTipoParticipante').change(function(){
        var tipo = $("#idTipoParticipante option:selected").text();
        if (tipo == 'Personagem') {
            $('#personagem').attr('disabled', false);
        }else if (tipo == 'Tecnico') {
            $('#personagem').attr('disabled', true);
        }
    });
});

Aqui está JSFiddle.
Basicamente o que você deve fazer além do ponto que você já foi é: adicionar uma ação para o evento change do $('idTipoParticipante'). Assim toda vez que o seu idTipoParticipante for modificado você poderá comparar os valores novamente.


text:
Q: how to make javascript draggable work on mobile I have 3 item which is item 1, item 2, and item 3
item1 with <data-price="10">, item1 with <data-price="20">, item1 with <data-price="30">
These items are draggable and when these items drag and drop on the red area, it will sum up the total
It works successfully on a desktop browser but the item is not draggable on the mobile browser.
I tried using Draggin.js. It's draggable on mobile browser but the javascript function(the calculation) is not working.
Is there another way to make it draggable on a mobile browser?

var price = 20, math = '', items = [], state = 'outside';
$(function() {
    function calcPrice(math) {
        var value = 0;
        price = 20;

    console.log("Item array: " + items);
        $.each( items, function( key, value ) {
        price+= $(".draggable[data-item='" + value + "']").data('price');
  });

    $("#test2").html(price)
}

$(".draggable").draggable({
    containment: "#container",
    scroll: false
});

 $("#droppable").droppable({
        drop: function(e, u) {
        if(u.draggable.data('state') == 'outside') {
            items.push(u.draggable.data('item'));
            u.draggable.data('state', 'inside');
            calcPrice('add');
        }
  },
   out: function(e, u) {
     if(u.draggable.data('state') == 'inside') {
       u.draggable.data('state', 'outside');
       var myIndex = $.inArray(u.draggable.data('item'), items);
       items.splice(myIndex, 1);
       price = $("#droppable").text();
       calcPrice('remove');
     }
   }
 });
 });
#container {
    width: 500px;
    height: 350px;
    background: #ccc;
}

#droppable {
    height: 100px;
    width: 100%;;
    background: #ff0000;
}

.draggable {
    width: 100px;
    height: 50px;
    border: 1px solid black;
}

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

<meta charset=utf-8 />

Drag and drop here

SUGAR: 20

Item 1 = [Price 10]

Item 2 = [Price 20]

Item 3 = [Price 30]


text:
Q: Azure table query failing with bad request error I am querying my azure table storage for some output. I can do it in Azure Storage Explorer, and to me the query generated in my code LOOKS like it should work as it does in Azure Storage Explorer. It fails and returns bad request, and I just don't see what is wrong with it.
The code that generates the query:
public QueryOutputResult GetOutputFromQueryResult(EquityDataEntity queryRecord, int outputPeriod)
{
    var resultDates = Helpers.GetValidOutputDates(queryRecord.RowKey, outputPeriod);
    var partitionFilter =  TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, queryRecord.PartitionKey);
    var startDateFilter =
        TableQuery.GenerateFilterConditionForDate("RowKey", QueryComparisons.GreaterThanOrEqual, resultDates[0].Date);
    var endDateFilter =
        TableQuery.GenerateFilterConditionForDate("TradeDate", QueryComparisons.LessThanOrEqual, resultDates[^1].Date);

    var filter = TableQuery.CombineFilters(
        TableQuery.CombineFilters(
            partitionFilter,
            TableOperators.And,
            startDateFilter),
        TableOperators.And, endDateFilter);

    var query = new TableQuery<EquityDataEntity>().Where(filter);
    var results = HistoricalDataTable.ExecuteQuery(query).ToList();

    return OutputHelpers.CreateOutputResultsFromQueryTriggers(queryRecord, results);

}

produces this:

((PartitionKey eq 'SPY') and (RowKey ge datetime'2022-01-24T05:00:00.0000000Z')) and (RowKey le datetime'2022-01-27T05:00:00.0000000Z')

Here is it working in ASE:

The error message doesn't help much (at least it doesn't help me)

  Message "The remote server returned an error: (400) Bad Request."   string

A: Have you tried just using the Date portion of the DateTime fields (resultDates[0].Date and resultDates[1].Date). The library is most likely having trouble with the time portion of the request.


text:
Q: Huge Whitespace exists to right after drawing image. Want to get rid of it I'm using the following codeproject to build an asp.net website and so far everything is good. My only problem is after the barcode is generated, a huge whitespace exist to the right of the barcode. I've been playing with this and am unable to resolve it.
Details below:
Link to Code Project Article: http://www.codeproject.com/KB/aspnet/AspBarCodes.aspx?msg=3543809
Copy of the Font is here: http://trussvillemethodist.web01.appliedi-labs.net/IDAutomationHC39M.ttf
          //Working Path
        string sWorkPath = "";
        sWorkPath = this.Context.Server.MapPath("");

        //Fonts
        PrivateFontCollection fnts = new PrivateFontCollection();
        fnts.AddFontFile(sWorkPath + @"\IDAutomationHC39M.ttf");
        FontFamily fntfam = new FontFamily("IDAutomationHC39M", fnts);
        Font oFont = new Font(fntfam, 18);

        // Get the Requested code sent from the previous page.
        string strCode = Request["code"].ToString();

        //Graphics
        //I don't know what to set the width to as I can't call the MeasureString without creating the Graphics object.
        Bitmap oBitmaptemp = new Bitmap(40, 100);
        Graphics oGraphicstemp = Graphics.FromImage(oBitmaptemp);
        int w = (int)oGraphicstemp.MeasureString(strCode, oFont).Width + 4;

        // Create a bitmap object of the width that we calculated and height of 100
        Bitmap oBitmap = new Bitmap(w, 100);

        // then create a Graphic object for the bitmap we just created.
        Graphics oGraphics = Graphics.FromImage(oBitmap);

        // Let's create the Point and Brushes for the barcode
        PointF oPoint = new PointF(2f, 2f);
        SolidBrush oBrushWrite = new SolidBrush(Color.Black);
        SolidBrush oBrush = new SolidBrush(Color.White);

        // Now lets create the actual barcode image
        // with a rectangle filled with white color
        oGraphics.FillRectangle(oBrush, 0, 0, w, 100);

        // We have to put prefix and sufix of an asterisk (*),
        // in order to be a valid barcode
        oGraphics.DrawString("*" + strCode + "*", oFont, oBrushWrite, oPoint);

        // Then we send the Graphics with the actual barcode
        Response.ContentType = "image/gif";
        oBitmap.Save(Response.OutputStream, ImageFormat.Gif);

        oBitmap.Dispose();
        oGraphics.Dispose();
        oBrush.Dispose();
        oFont.Dispose();

A: The code just assumes 40 pixels per character, which is why you get a lot of image left on the right of the text. You can use the MeasureString method to measure the size of the text, and use that to create an image of the correct size:
int w = (int)oGraphics.MeasureString("*123$10.00*", oFont).Width + 4;

I noticed that you don't dispose any of the objects that you are using. The Graphics, Bitmap, SolidBrush and Font objects need to be disposed.
You might also want to consider using a GIF image instead of JPEG, it's more suited for this kind of graphics.


text:
Q: Opening a file from .netrw in a specified split This is  the same question as on SuperUser, but I feel it has a better chance of being answered here, so ...
In Vim, I have four splits - two by two - and in the upper left one netrw is open. Is there a way to open a file from netrw in the lower right split, lower left, etc.?

A: You can set the g:netrw_chgwin variable to make netrw open the files in a specific window. See:
:h netrw-C

So to make the current window the target of netrw type this while you're in that window:
:let g:netrw_chgwin = winnr()

Another way is to launch netrw in the target window (:E), hit C to select it for editing and close netrw with <c-o>.

A: To bring above answers together some inspirations: I use the following window configuration together with netrw (together with :let g:netrw_liststyle = 2):

    -------------------------------- ...
    Netrw-split: topleft spilt
    -------------------------------- ...
             |          |          |
    working  | working  | working  |
    window 1 | window 2 | window 3 | ...
             |          |          |

Thus I can go directly to Netrw-split from every other window. Then I put to my .vimrc:

    augroup netrw
        autocmd!
        autocmd WinLeave * if &ft !=# "netrw" | let g:netrw_chgwin = winnr() | endif
        autocmd filetype netrw call Netrw_mappings()
    augroup END

The WinLeave command sets the global g:netrw_chgwin variable to the window just left (except if we are in the netrw-window).  Thus netrw will open any file in the window from which I accessed it and due to the window layout I can access netrw from any other window.
The autocmd 'filetype' is used to also create a new file in the window from which I accessed netrw.  For this netrw's '%' command has to be overwritten:

    function! Netrw_mappings()
        noremap <buffer>% :call CreateInLastWindow()<cr>
    endfunction

With a function creating the new file in window g:netrw_chgwin:

    function! CreateInLastWindow()
        let l:filename = input("new file's name: ")
        let l:netrwdir = b:netrw_curdir
        execute g:netrw_chgwin . "wincmd w"
        execute 'edit ' . l:netrwdir.'/'.l:filename
    endfunction

A: there're some hints here https://superuser.com/questions/377501/keep-cursor-in-netrw-window-when-browsing-files-in-vim
Put this in your .vimrc,
let g:netrw_preview = 1

to configure vertical preview splits, then when the cursor is over the desired file, type p to open a preview window. To close the window, type CtrlWz.
The term used in vim for a window that's opened without the cursor moving to it is a "preview window". To find out more about this, see
:help netrw-preview
:help CTRL-W_z

or just
:help netrw

and browse the table of contents for other browsing commands and other netrw features.


text:
Q: ValueError: Dimension 0 in both shapes must be equal, but are 3 and 10 I try run this NN but return this error:
ValueError: Dimension 0 in both shapes must be equal, but are 3 and 10. Shapes are [3] and [10]. for '{{node AssignAddVariableOp_2}} = AssignAddVariableOp[dtype=DT_FLOAT](AssignAddVariableOp_2/resource, Sum_2)' with input shapes: [], [10].
def build_model(hp):

    model=Sequential()
    dropout = 0.2
    hp_units = hp.Int('units', min_value=32, max_value=512, step=32)
    hp_learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])

    model.add(LSTM(units=hp_units,input_shape=(X_train.shape[1:])
                   ,return_sequences=True))
    model.add(Dropout(dropout))
    model.add(BatchNormalization())

    model.add(LSTM(units=hp_units, return_sequences=False))
    model.add(Dropout(dropout))
    model.add(BatchNormalization())

    model.add(Dense(units=hp_units, activation='sigmoid'))
    model.add(Dropout(rate=dropout))
    model.add(Dense(10))

    model.compile(optimizer=keras.optimizers.Adam(learning_rate=hp_learning_rate),
                loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=[tfa.metrics.F1Score(num_classes=3)])

    return model

tuner = kt.Hyperband(build_model,
                    objective=kt.Objective('val_tfa.metrics.F1Score', direction='max'),
                    max_epochs = 10,
                    factor = 3,
                    directory = 'model2',
                    project_name= 'Hyper tuning')

stop_early = EarlyStopping(monitor='val_tfa.metrics.F1Score', patience=3)

tuner.search(X_train, y_train, epochs=50, validation_split=0.2, callbacks=[stop_early])