text:
Q: Use sum function in where clause I'm working with oracle fusion and one of the apps I'm working with (value-sets) does not allow me to use functions in the select statement and the from section has a 200 character limit.
This query gives me what I want but I cant use the sum with the select-
SELECT SUM(d.ABS_UNITS) from PER_ALL_PEOPLE_F b, ANC_ABSENCE_PLANS_F_TL c,
ANC_PER_ABS_PLAN_ENTRIES d
WHERE
d.PERSON_ID = b.PERSON_ID
AND c.ABSENCE_PLAN_ID = d.ABSENCE_PLAN_ID
AND c.name = 'FMLA LWOP'
and d.start_date between '2017-04-02' and '2017-04-15'
AND b.PERSON_NUMBER = p_num

I also tried this but had the character limit issue -
Select aa.bb from
(SELECT SUM(d.ABS_UNITS) as bb from PER_ALL_PEOPLE_F b,
ANC_ABSENCE_PLANS_F_TL c, ANC_PER_ABS_PLAN_ENTRIES d
WHERE
d.PERSON_ID = b.PERSON_ID
AND c.ABSENCE_PLAN_ID = d.ABSENCE_PLAN_ID
AND c.name = 'FMLA LWOP'
and d.start_date between '2017-04-02' and '2017-04-15'
AND b.PERSON_NUMBER = p_num
) aa

This approach is what I've been trying to work with putting the sum in the where clause but it's not returning anything.
Select
d.ABS_UNITS
FROM
PER_ALL_PEOPLE_F b, ANC_ABSENCE_PLANS_F_TL c, ANC_PER_ABS_PLAN_ENTRIES d
WHERE
d.PERSON_ID = b.PERSON_ID
AND c.ABSENCE_PLAN_ID = d.ABSENCE_PLAN_ID
AND c.name = 'FMLA LWOP'
AND b.PERSON_NUMBER = pnum
and d.start_date between '2017-04-02' and '2017-04-15'
AND d.ABS_UNITS = (SELECT SUM(d.ABS_UNITS) from PER_ALL_PEOPLE_F b,
ANC_ABSENCE_PLANS_F_TL c, ANC_PER_ABS_PLAN_ENTRIES d
WHERE
d.PERSON_ID = b.PERSON_ID
AND c.ABSENCE_PLAN_ID = d.ABSENCE_PLAN_ID
AND c.name = 'FMLA LWOP'
and d.start_date between '2017-04-02' and '2017-04-15'
AND b.PERSON_NUMBER = pnum
)

Any input and advice would be greatly appreciated.

A: I have not work with fusion apps.
If I don't understand wrong you have limits for character limit and functions in select.
Your 'where' clause is long considering your character limit. You can shorten it using ALIAS for columns and tables in database level. Then customize your query.

A: Thanks for all the input I really appreciate it. I found a work around, Oracle Fusion has hidden functions in the script language I was working with that are not documented but can be found through sql. Very frustrating, but thanks for all the feed back

A: You can't use aggregate functions (such as SUM) in WHERE clause, because WHERE limits rows physically. You shall aggregate in GROUP BY clause to logically limit output.


text:
Q: Instance v state variables in react.js In react.js, is it better to store a timeout reference as an instance variable (this.timeout) or a state variable (this.state.timeout)?
React.createClass({
     handleEnter: function () {
         // Open a new one after a delay
         var self = this;
         this.timeout = setTimeout(function () {
             self.openWidget();
         }, DELAY);
     },
     handleLeave: function () {
        // Clear the timeout for opening the widget
        clearTimeout(this.timeout);
     }
    ...
})

or
React.createClass({
     handleEnter: function () {
         // Open a new one after a delay
         var self = this;
         this.state.timeout = setTimeout(function () {
             self.openWidget();
         }, DELAY);
     },
     handleLeave: function () {
        // Clear the timeout for opening the widget
        clearTimeout(this.state.timeout);
     }
    ...
})

both of these approaches work. I just want to know the reasons for using one over the other.

A: I suggest storing it on the instance but not in its state. Whenever state is updated (which should only be done by setState as suggested in a comment), React calls render and makes any necessary changes to the real DOM.
Because the value of timeout has no effect on the rendering of your component, it shouldn't live in state. Putting it there would cause unnecessary calls to render.

A: In addition to what @ssorallen said, you should also remember to handle the component unmounting before your handleLeave is called.
React.createClass({
     handleEnter: function () {
         // Open a new one after a delay
         this._timeout = setTimeout(function () {
             this.openWidget();
         }.bind(this), DELAY);
     },
     handleLeave: function () {
        // Clear the timeout for opening the widget
        clearTimeout(this._timeout);
     },
     componentWillUnmount: function(){
        // Clear the timeout when the component unmounts
        clearTimeout(this._timeout);
     },
    ...
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Application of mean value theorem to $\int^{6\pi}_{4\pi} \frac{\sin x}{x}dx$ yields incorrect result I've come up with the following proof for $\int^{6\pi}_{4\pi} \frac{\sin x}{x}dx = 0$:

The statement is true, due to the mean value theorem specifying the existence of a $k \in [2\pi,4\pi]$ such that:
\begin{align*}
\int^{6\pi}_{4\pi} \frac{\sin x}{x}dx
&= \frac{1}{k}\int^{6\pi}_{4\pi}\sin x dx \\
&= \frac{1}{k}(- \cos x \bigg|^{6\pi}_{4\pi}) \\
&= \frac{\cos 4\pi - \cos 6\pi}{k} \\
&= 0
\end{align*}

However according to Wolfram Alpha this does not seem to be correct. Is the mean value theorem not applicable here for some reason, or did I do something else wrong here?

A: One version of mean value theorem for definite integral states:

Given two functions $f, g$ on $[ a, b ]$. If $f$ is continuous and $g$ is an integrable function which doesn't change sign on $[ a, b ]$, then there exists $c \in (a,b)$  such that
  $$\int_a^b f(x) g(x) dx = f(c) \int_a^b g(x) dx$$

For your case, you can't apply this version of mean value theorem because
$g(x) = \sin x$ changes sign over $[4\pi, 6\pi]$.

A: $$\int\frac{\sin x}x\,dx$$
does not evaluate to $-\cos x+K$ because of the division by $x$. This is one of the trigonometric integrals and has its own notation:
$$\int\frac{\sin x}x\,dx=\operatorname{Si}(x)+K$$
Therefore your proof is wrong and
$$\int_{4\pi}^{6\pi}\frac{\sin x}x\,dx=\operatorname{Si}(6\pi)-\operatorname{Si}(4\pi)=0.02587\dots$$


text:
Q: VS 11 Unit Testing Frameworks We have started working on VS11 projects involving a DDD - Agile - TDD approach.
I'm using VS 11 Beta and I'm very impressed by the new Unit Tests features that includes the possibility to use 3rd party frameworks (xUnit , NUnit...).
Unfortunately, I have not been able to find out any post/article about a fair comparison between these different frameworks and the new features each one provides in the new IDE.
Which one is suitable for this kind of approach with an intensive and huge projects ?
Thanks for you support.
Melek

A: xUnit codeplex page has nice comparison of unit-test frameworks in general.


text:
Q: Group By and get top N in Simple SQL I have following table in SQLite
BANK:
user-id sender-name receiver-name amount
----------------------------------------
1       A           B             200
2       A           C             250
3       A           B             400
4       A           B             520
4       A           D             120
4       A           D             130
4       A           B             110
4       A           B             300
4       A           B             190
4       A           C             230
4       A           B             110
4       A           C             40
4       A           C             80

I need to find out top 3 transaction from each receiver. There are multiple solutions provided for several other database which is not compatible with SQLite cause of the use of certain functions like PARTITION and RANK and even user-defined variables.
I need the solution in simple SQL queries to allow use with SQLite.
Expected result:
receiver-name amount
--------------------
B             560
C             1220
D             250

A: I managed to do it with using only simple function with self-join.
Now you can just update N with your preferred value, for my case top 3, it would be LIMIT 3.
SELECT receiver-name ,(
    SELECT SUM(amount) as sum_amount
    FROM (
        SELECT amount
        FROM bank as b2
        WHERE b2.receiver-name = b.receiver-name
        ORDER BY b2.amount DESC
        LIMIT 3
    )
) as sum_amount
FROM bank as b
GROUP BY receiver-name


text:
Q: Getting numerical value of spinner selection for use in calculation I have a spinner for Period which contains the selections:
3 months
6 months
10 months
12 months
18 months

PROBLEM:
I can get the value of the spinner selection but I need a way to get just the numerical value of the selection ( i.e. just the 3 from 3 months ) for use in another activity with calculations using BigDecimal. Can anyone guide me accordingly?

A: The code below will replace all non digits and you will get inly integer value.
String s = spinner.getSelectedItem().toString();

int spinnerVal = Integer.parseInt(s.replaceAll("[\\D]", ""))


text:
Q: if db connection true load migrations codeigniter I have a form where I can fill out my database details, and then it gets placed in the database.php file.
Problem
When I click on the submit button it should load my migrations but can not load migrations because saying incorrect database name.
The reason Is because it loads at same time as the database and does not pick the name up yet.
Is there away to run the loadMigrations function once established db connection or database name.
$this->form_validation->set_rules('hostname', 'Hostname', 'required');
$this->form_validation->set_rules('username', 'Database Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|xss_clean');
$this->form_validation->set_rules('database', 'Database', 'required');
$this->form_validation->set_rules('driver', 'Database Driver');
$this->form_validation->set_rules('prefix', 'Database Prefix');

$this->load->library('form_validation');

if ($this->form_validation->run($this) == false) {

$this->load->view('template/step_3');

} else {

$data = array();
$data['hostname']   = $this->input->post('hostname');
$data['username']   = $this->input->post('username');
$data['password']   = $this->input->post('password');
$data['database']   = $this->input->post('database');
$data['driver'] = $this->input->post('driver');
$data['prefix']  = $this->input->post('prefix');

$data  = $this->load->view('template/configuration/database', $data, true);
write_file(dirname(FCPATH) . '/admin/application/config/database.php', $data, 'r+');
write_file(dirname(FCPATH) . '/catalog/config/database.php', $data, 'r+');
write_file(FCPATH . '/application/config/database.php', $data, 'r+');

/*
|
|   This migration does not work because will not pick up database name
|   You all ways have to refresh page. Need away that can load migrations
|   Once there is a database name in the database.php file.
|
*/

$this->load->dbutil();
if($this->dbutil->database_exists($this->input->post('database'))) {
$this->load->library('migration');
$this->migration->version(1);
redirect('step_4'); // connected, go on
} else {
redirect('step_3'); // failed, go back
}

}

A: You can check db connection like following:
$db = $this->load->database('default', true);

if($connected = $db->initialize())
{
     redirect('step_4'); // connected, go on
}
else
{
     redirect('step_3'); // failed, go back
}

Another Way
// Returns boolean or mysql/mysqli object
function test_db_connection()
{
    $hostname = $this->input->post('hostname');
    $database = $this->input->post('database');
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $driver   = $this->input->post('driver');

    if($driver == 'mysqli')
    {
        return function_exists('mysqli_connect') && @mysqli_connect($hostname, $username, $password, $database);
    }

    $link = @mysql_connect("$hostname", $username, $password);
    return $link && mysql_select_db("$database", $link)
}

This function that i'm using is working right. If doesnt work, check your codes again.


text:
Q: How do I log unique authors in git? I have a big project with many authors.
For example,
user1 - commit1
user2 - commit2
user1 - commit3

I want to get all unique authors.
The result must be user1 user2
How do I log unique authors in git?

A: Try out this one:
 git shortlog -s | awk '{print $2,$3}' | sort -fu

Edit: This will get you the emails as well
git shortlog -se | sed -re 's/^\s*[[:digit:]]*\s*//' | sort -fu

or, on macOS without the -r flag - highlighted by Oliver in comments below - would be:
git shortlog -se | sed -e 's/^\s*[[:digit:]]*\s*//' | sort -fu

A: Here's one easy way:
git log --format="%an" | sort -u

A: I needed to get the authors and committers so below is the https://devhints.io/git-log to helpful commands.
code below gets you the author name (%an) and author email (%ae) in this format
personName - person@email.com
git log --format="%an - %ae" | sort -u
git log --format="%cn - %ce" | sort -u

A: Another possibility is gitqlite "SELECT DISTINCT author_name FROM commits" using gitqlite, which is a tool for running ad-hoc SQL queries on git data.
(Full disclosure, I'm a creator/maintainer of the project)


text:
Q: Discrepancy in calculation using modulo operator I am trying to find cube root of a set of numbers using following
x^(1/3) %% 1 ==0

but I am not getting the correct value. When I tried to see what is happening in the console found the following behavior :
> 4 %% 1
[1] 0
> 64^(1/3) %% 1
[1] 1

Why is this giving different results? Am I doing something wrong?

A: If we convert to integer, it would work
as.integer(64^(1/3) ) %% 1

A: From a mathematical perspective, a workaround is to factorize x first (pracma::factors is used in the following example), e.g.,
nRoot <- function(x, n = 3) {
  u <- pracma::factors(x)
  prod(unique(u)**(table(u) / n))
}

then you will see
> nRoot(64) %% 1
[1] 0

> nRoot(216) %% 1
[1] 0

while
> 64^(1/3) %% 1
[1] 1

> 216^(1/3) %% 1
[1] 1


text:
Q: Pixels shift in WriteableBitmap I have faced a problem with WriteableBitmap. I am trying to render a 3d cube. But when pixels is being written to WriteableBitmap, part of them just shift.
Initialized cube:

And that what's happening, when I am trying to rotate it by 45 degrees along x.

Problem appears for all kind of rotation, except y (rotation by 10 degrees along z)

I have tested same points with usual Bitmap and SetPixel() method. That's what I get after rotating cube along 45 degrees by three axis. I don't see any problems here

I think that problem can be with my writeableBitmap pixels setting algorithm (maybe problem with pixel offset?).
Second image with grey background:

What I am expecting from cube rotated by 45 deegres along x. Red line - edge. Text - facets

WriteableBitmap drawing algorithm:
public WriteableBitmap DrawSceneByPoints(int width, int height, List<MPoint> points)
    {
        WriteableBitmap wBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);

        Int32Rect rect = new Int32Rect(0, 0, width, height);

        var stride = (rect.Width * wBitmap.Format.BitsPerPixel + 7) / 8;

        byte[] pixels = new byte[rect.Height * stride];

        // For user: Moves 0,0 point from top-left to bottom-left
        for (int i = 0; i < points.Count; ++i)
            points[i].Y = height - points[i].Y;

        int alpha = 255;
        int red = 0;
        int green = 0;
        int blue = 0;

        for (int i = 0; i < points.Count; ++i)
        {
            int pixelOffset = (int)(points[i].X + points[i].Y * wBitmap.PixelWidth) * wBitmap.Format.BitsPerPixel / 8;

            pixels[pixelOffset] = (byte)blue;
            pixels[pixelOffset + 1] = (byte)green;
            pixels[pixelOffset + 2] = (byte)red;
            pixels[pixelOffset + 3] = (byte)alpha;
        }

        wBitmap.WritePixels(rect, pixels, stride, 0);

        return wBitmap;
    }

Usual bitmap drawing algorithm:
public Bitmap DrawSceneByPointsBitmap(int width, int height, List<MPoint> points)
    {
        Bitmap bitmap = new Bitmap(width, height);

        // For user: Moves 0,0 point from top-left to bottom-left
        for (int i = 0; i < points.Count; ++i)
            points[i].Y = height - points[i].Y;

        for (int i = 0; i < points.Count; ++i)
            bitmap.SetPixel((int)points[i].X, (int)points[i].Y, System.Drawing.Color.White);

        return bitmap;
    }

Scene Render method:
public WriteableBitmap Render()
    {
        new ShapeEditor().TransformShapes(Shapes, CurrentCamera);

        List<MPoint> allPoints = GetAllPoints();

        return new Painter().DrawSceneByPoints(this.Width, this.Height, allPoints);
    }

Line rastrizer:
class BresenhamLine : ILineRasterizer
{
    public List<MPoint> GetLine(MPoint point1, MPoint point2)
    {
        return Bresenham3D((int)point1.X, (int)point1.Y, (int)point1.Z, (int)point2.X, (int)point2.Y, (int)point2.Z);
    }

    private List<MPoint> Bresenham3D(int x1, int y1, int z1, int x2, int y2, int z2)
    {
        var points = new List<MPoint>();

        float x0 = x1, y0 = y1, z0 = z1;
        int i, dx, dy, dz, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2;
        int[] point = new int[3];

        point[0] = x1;
        point[1] = y1;
        point[2] = z1;

        dx = x2 - x1;
        dy = y2 - y1;
        dz = z2 - z1;

        x_inc = (dx < 0) ? -1 : 1;
        l = Math.Abs(dx);

        y_inc = (dy < 0) ? -1 : 1;
        m = Math.Abs(dy);

        z_inc = (dz < 0) ? -1 : 1;
        n = Math.Abs(dz);

        dx2 = l << 1;
        dy2 = m << 1;
        dz2 = n << 1;

        if ((l >= m) && (l >= n))
        {
            err_1 = dy2 - l;
            err_2 = dz2 - l;
            for (i = 0; i < l; i++)
            {
                points.Add(new MPoint(point[0], point[1], point[2]));

                if (err_1 > 0)
                {
                    point[1] += y_inc;
                    err_1 -= dx2;
                }
                if (err_2 > 0)
                {
                    point[2] += z_inc;
                    err_2 -= dx2;
                }
                err_1 += dy2;
                err_2 += dz2;
                point[0] += x_inc;
            }
        }
        else if ((m >= l) && (m >= n))
        {
            err_1 = dx2 - m;
            err_2 = dz2 - m;
            for (i = 0; i < m; i++)
            {
                points.Add(new MPoint(point[0], point[1], point[2]));

                if (err_1 > 0)
                {
                    point[0] += x_inc;
                    err_1 -= dy2;
                }
                if (err_2 > 0)
                {
                    point[2] += z_inc;
                    err_2 -= dy2;
                }
                err_1 += dx2;
                err_2 += dz2;
                point[1] += y_inc;
            }
        }
        else
        {
            err_1 = dy2 - n;
            err_2 = dx2 - n;
            for (i = 0; i < n; i++)
            {
                points.Add(new MPoint(point[0], point[1], point[2]));

                if (err_1 > 0)
                {
                    point[1] += y_inc;
                    err_1 -= dz2;
                }
                if (err_2 > 0)
                {
                    point[0] += x_inc;
                    err_2 -= dz2;
                }
                err_1 += dy2;
                err_2 += dx2;
                point[2] += z_inc;
            }
        }

        return points;
    }

    private void Swap<T>(ref T l, ref T r)
    {
        T temp = l;

        l = r;

        r = temp;
    }
}

Polygon rasterizer:
public List<MPoint> RasterizePolygon(MFacet triangle)
    {
        var points = new List<MPoint>();

        Vector2 vertex0 = new Vector2(triangle.Vertices[0].X, triangle.Vertices[0].Y),
            vertex1 = new Vector2(triangle.Vertices[1].X, triangle.Vertices[1].Y),
            vertex2 = new Vector2(triangle.Vertices[2].X, triangle.Vertices[2].Y);

        if (vertex0.Y == vertex1.Y && vertex0.Y == vertex2.Y) return new BresenhamLine().GetLine(triangle.Vertices[0], triangle.Vertices[2]);
                                                  // sort the vertices, vertex0, vertex1, vertex2 lower-to-upper
        if (vertex0.Y > vertex1.Y) Swap(ref vertex0, ref vertex1);
        if (vertex0.Y > vertex2.Y) Swap(ref vertex0, ref vertex2);
        if (vertex1.Y > vertex2.Y) Swap(ref vertex1, ref vertex2);

        int total_height = (int)(vertex2.Y - vertex0.Y);

        for (int i = 0; i < total_height; i++)
        {
            bool second_half = i > vertex1.Y - vertex0.Y || vertex1.Y == vertex0.Y;

            int segment_height = second_half ? (int)(vertex2.Y - vertex1.Y) : (int)(vertex1.Y - vertex0.Y);

            float alpha = (float)i / total_height;
            float beta = (float)(i - (second_half ? vertex1.Y - vertex0.Y : 0)) / segment_height; // be careful: with above conditions no division by zero here

            Vector2 A = vertex0 + (vertex2 - vertex0) * alpha;
            Vector2 B = second_half ? vertex1 + (vertex2 - vertex1) * beta : vertex0 + (vertex1 - vertex0) * beta;

            if (A.X > B.X) Swap(ref A, ref B);

            for (int j = (int)A.X; j <= B.X; j++)
            {
                points.Add(new MPoint(j, vertex0.Y + i, 1));

                if (j > B.X || (A.X < vertex0.X && A.X < vertex1.X && A.X < vertex2.X))
                    Swap(ref vertex0, ref vertex0);
            }
        }

        return points;
    }

A: I use writeablebitmap to convert a 2d array of elevations into a hypsometric picture. Colour represents height.
I recommend working with a 2d array which represents your scene and just iterate through that.
There are 4 bytes per pixel for bgra32.
                WriteableBitmap WBM = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);

                byte[] pixels = new byte[width * height * 4];
                double perColour = (double)(max - min) / 254d;
                Color[] ca = Application.Current.Resources["HypsoColours"] as Color[];

                int ix = 0;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        int elv = elevations[x, y];
                        int eff = elv - min;
                        int ptr = 0;
                        if (eff> 0)
                        {
                            ptr = (int)((elv - min) / perColour);
                        }
                        Color colour = ca[ptr];
                        pixels[ix] = colour.B;
                        ix++;
                        pixels[ix] = colour.G;
                        ix++;
                        pixels[ix] = colour.R;
                        ix++;
                        pixels[ix] = 255;
                        ix++;
                    }
                }
                WBM.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0);
                WBM.Freeze();
                return WBM;


text:
Q: Pendulum on a moving cart that begins acceleration I have a pendulum hanging on a cart that is travelling at constant velocity. The pendulum is oscillating about a fixed pivot. The initial movement of the pendulum can be represented by this equation:
$$ \theta(t)\; =\; \theta_{o}\:cos\:(\sqrt{\frac{g}{L}}\:t) $$
This function will result in a cosine wave.
Is there a formula that allows me to plot the subsequent behaviour of the pendulum.
So far from my research, I have found out the formula that represents a stationary cart that begins acceleration.
$$ \theta(t)\; =\; \theta_{o}\:cos\:(\sqrt{\frac{g}{L}}\:t)\: -\: tan^{-1}(\frac{a}{g})  $$
a : cart's acceleration
Since the pendulum is already swinging in the first scenario. If I know its $\theta$ and $\omega$ just before the cart begins to accelerate. Is it possible to incorporate these pieces of information to the above formula?


text:
Q: How to trim all the preceding zeroes of a 32-bit binary number? I was trying to trim all the leading/preceding zeroes in a binary 32-bit number and print out  the output by these following 2 codes of which the first one showed error while the other code was successful:
I want to know why the former one failed. please explain in detail. it would mean a lot to me.
    string trimmer(string& binary_str) {

    int i=0;// 'i' will finally have the index of the binary string which is having value as '0' and is
            //  just the preceding zero to the first 1 in the string

    while (binary_str.at(i) != 1) {//this will iterate over the srting until it reaches the zero before
                                   //the first 1 in the string
        i++;
    }
    binary_str.erase(0, i);      //this will erase all the preceeding zeroes
    return binary_str;
}

This above written code didnt work and showed up error,
But this second code worked:
string trimmer(string& binary_str) {
    int i=0;
    for (i = 0; i < 32; i++) {
        if (binary_str.at(i) == '1') {
            break;
        }
    }
    binary_str.erase(0, i);
    return binary_str;
}

Both had the function, ie, if input was given: a binary string 00000000000000000000001011001011
then the output should be 1011001011.
The former code used while loop whereas the latter used for loop with if conditional. bot codes follow the same logic. but the former one with while loop showed up error whereas the latter one didn't.
Can anybody explain to me the reason behind the while loop to show up error? it would mean a lot to me.
The complete code is as follows:
#include<bits/stdc++.h>
using namespace std;
/*
string trimmer(string& binary_str) {
    int i=0;
    while (binary_str.at(i) != 1) {
        i++;
    }
    binary_str.erase(0, i);
    return binary_str;
}
*/
string trimmer(string& binary_str) {
    int i=0;
    for (i = 0; i < 32; i++) {
        if (binary_str.at(i) == '1') {
            break;
        }
    }
    binary_str.erase(0, i);
    return binary_str;
}

int main(){
    string bStr="00000000001011001011";
    bStr = trimmer(bStr);
    cout<< bStr<<'\n';
    return 0;
}

A: You can use find_first_not_of to find the first character of that isn't a 0. Then you can erase all characters up to that point. If a string is all zeros, it will be completely erased.
void trim_leading_zeros(std::string &str) {
    str.erase(0, str.find_first_not_of('0'));
}

A: Try using modern C++ features:
#include <iostream>
#include <algorithm>
#include <string>

void ltrim_zero(std::string& str) {
    str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](int character) {
        return '0' != character;
    }));
}

int main(){
    std::string bStr = "00000000001011001011";
    ltrim_zero(bStr);
    std::cout << bStr << std::endl;
    return 0;
}

Try live

A: find the first occurrence of '1' and use this variation of string constructor
    string (const string& str, size_t pos, size_t len = npos);

str=string to be copied from
pos= starting position to copy from
npos= number of character to copy from source(str) string.


text:
Q: Parameters class in c++ I  have a c++ project which has multiple cpp files and functions.
Each file needs its own parameters (i.e., MaxHorizonVelocity, MaxVerticalVelocity etc.).
I want that these parameters won't be hard coded but read from a single configuration-parameters file at an initialization step.
For now I think to define a parameters class which will read the parameters at the begining and will be "static" (in some sense which I'm not sure about ...).
Is that considered a good practice? Is there another way?

A: I usually handle this problem in below way. The code itself is self-explanatory.
All configurable items must be derived from IConfigurable interface.
class IConfigurable {
    public:
        virtual void configure(XMLNode&) = 0;
};

Each configurable item assumes that configure function will be called and given XMLNode will be the root node in configuration xml file. After that each configurable item does specific parsing according to itself.
class CommandClick : public IConfigurable {
    public:
        void configure(XMLNode& xCommandNode) {
            XMLNode xClickCoordinate = xCommandNode.getChildNode("Coordinate");
            unsigned int x = atoi(xClickCoordinate.getAttribute("x"));
            unsigned int y = atoi(xClickCoordinate.getAttribute("y"));
            mClickCoordinate.setX(x);
            mClickCoordinate.setY(y);
        }
    private:
        Coordinate mClickCoordinate;
};


text:
Q: How to keep cloud storage synced when changing an operating system? I have a folder with symlinks synced to a cloud storage and I'm switching a linux distro.
Is there a way to keep my data, which is on a separate /home partition that will not be formatted, synced on the fresh install without re-downloading everything?


text:
Q: Waiting for object creation or accessing it immediately if it already exists I've faced the following problem today: we have a class Foo which has an instance of Bar inside of it. A method initBar() is called at some point during a lifecycle of class (which is very asynchronous, lots of RxJava) and it does bar = new Bar()
Now, the problem is that I want to access bar inside of some other method doStuff(), which is not guaranteed to be called after the initBar(), so the bar can either still be null or already exist.
If bar already exists I want to run a function analyze(bar) synchronously right away, if it's still null - I want to schedule it to run once bar is set (as a part of initBar() call).
Bonus questions: how to specify on which thread analyze(bar) should be executed; what if multiple methods want to access bar; how to safely cancel these.
Now, I know how to implement this using RxJava: add extra PublishSubject<Bar> subject and subscribe to it while calling .repeat() to get the value if it was already set, and then from initBar() do subject.onNext(bar). That's easy. It even covers the case of accessing it from multiple places and specifying a thread to run the code on.
But I feel like I'm reinventing a wheel here - there probably is a solution out there for this type of problems, when you want to access an object without worrying on whether it's already set or not. Should it be considered Promise and be done with CompletableFuture or JDeferred? Or is there some nice RxJava recipe for this already? There's gotta be something clean and easy ...
Here's full code of Foo for reference:
class Foo {
    Bar bar;

    void initBar() { bar = new Bar(); }

    void doStuff() {
         //This is the missing piece
         doWhenBar(bar -> analyze(bar));
    }

    void lifecycle1() {
        Observable.create(..)
            ...
            .doOnNext(this::initBar())
            ...
    }

    void lifecycle2() {
        Observable.create(..)
            ...
            .subscribe(this::doStuff())
    }

    //More methods where lifecycle1() and lifecycle2() can be called in random order
    ...
}

A: If bar is only created once, use a SingleSubject and now you can react to Bar being created:
class Foo {
    final SingleSubject<Bar> bar = SingleSubject.create();

    void initBar() { bar.onSuccess(new Bar()); }

    Single<Bar> doStuff() {
         //This is the missing piece
         return bar.observeOn(Schedulers.computation())
         .doOnSuccess(b -> analyze(b));
    }

    void lifecycle1() {
        Observable.create(..)
        ...
        .doOnNext(this::initBar())
        ...
    }

    void lifecycle2() {
        Observable.create(..)
        ...
        .concatMapSingle(this::doStuff)
        .subscribe(...)
    }

// More methods where lifecycle1() and lifecycle2()
// can be called in random order
...
}


text:
Q: '400 Bad request' - Google not redirecting back correctly after Authentication using DotNetOpenAuth and PhoneGap ChildBrowser plugin I'm working on a simple implementation of THIS DotNetOpenAuth  tutorial.
On a regular browser such as Chrome, Firefox and IE it works fine. But when I call this "google_login.aspx" page from the PhoneGap childBrowser plugin It fails.
Failure happens in the form of a 400 -Bad Request - Invalid URL after the user has put his credentials into Google.
When Google tries to redirect back to my site, Google trying to use a bad url which looks like this:
https://myurl.com/(F(8g0QkKd61D6yBbN2pkuZwAXOTGChqwruytA0LCC_nZko2mXgddbDhT3nXCj3XWVwOSkyfNGENHtctVXbnAyFQcj344Cai3rrkKKO_SNM_laGIqIPN2pkSBJQQYc98T0qv_gZbm3R8Qufry7u-HLAAT_RfVpMtpbCM6sw-FLPuxxHUETRHjd8lA9DR7LKIfkMYYinZU_qLduO02f012wZ2feVi8XW479WOvrWCr_rHFAxPNEQFurrJO1rxGs1LUFzTZ4pNlgpm4LwHrv7lTtK5-adDKbQJXzFrjEAG22pNxGfKpesHNsV-m88zp20w70FtF56wppLfzadNgq7cPDlb3hIwbsA-JGI1he8low8_KWDNZev5RqtX8cPtQKpFIL0))/Default.aspx

Instead of this:
https://myurl.com/Default.aspx

This only happens on the PhoneGap childBrowser plugin, other browsers take me to the right place.
After getting the 400 bad request error I can manually browse to my homepage and it shows that I am in fact signed in, and that the simple redirect back from Google is what failed.
Anyone know how of a fix or possible workaround to my problem?
Solution:
I had to specify the returnToURL parameter in the OpenIdRelyingParty.CreateRequest :

A: This looks like it may be ASP.NET's cookieless session support feature.  If your failing scenario is one where session cookies are rejected, and if enabled in the web.config file, I believe ASP.NET will essentially store the cookie in your URLs instead, creating a kind of virtual path.  Obviously something is going wrong with this though.  I suggest you isolate the problem by:

*

*Turn on DotNetOpenAuth logging

*Collect a Fiddler2 trace of the entire login attempt

...to figure out where this stray path is coming from.

A: To solve this problem:

*

*Add the App_Browsers ASP.NET folder to your project if it doesn't already exist (right-click on the project, click Add -> Add ASP.NET Folder -> App.Browsers

*Add a file called generic.browser to the App.Browsers folder

*Replace any automatically generated code in the generic.browser file with:
<browsers>
    <browser refID="Default">
        <capabilities>
            <capability name="cookies" value="true" />
        </capabilities>
    </browser>
</browsers>

The problem occurs with reasonable frequency on iOS devices such as iPad and iOS when running Forms Authentication. The user will receive the error: Bad Request - Invalid URL. HTTP Error 400. The request URL is invalid.


text:
Q: iPhone 4: Play audio while on call I have developed an application which will play audio when call is on. And the person on opposite side can hear it.
It works fine with pre iphone4. But its not working with iphone4.
After some search, I found that iPhone4 considers that audio sound as noise and filters it out. Is there any other way to do it?
Thanks in advance.


text:
Q: How do I edit others' questions?
Possible Duplicate:
How much rep do I need to edit others' posts on Stack Overflow?

How do I edit other users' questions or tags? Is there any reputation requirement?

A: Yes, there's a reputation limit.  You need 2000 reputation to edit regular posts and 500 to retag, or 100 to edit posts marked Community Wiki.  See the FAQ for more details.

A: This depends on the SE site you are talking about. For SO the answer is given, with 2000 to edit other peoples' questions and 100 for cw. Yet other sites, even depending on there stage in live, have other requirements.
See here for the numbers. And the widget SE-site\abilities that @radp pointed out works on all sites.


text:
Q: Проблема с подключением сервлетов на Glassfish5 Я новичок в Java, и вот недавно занялась изучением серверов. Начала с Tomcat и с ним проблем не возникло, затем я перешла на Glassfish. Добавила бины, отредактировала классы. При запуске открывается страница index.html, затем я выбираю Select1, и переходит на select1.jsp, на ней я ввожу число, и по идее в этот момент должен сработать Select1Servlet, но выходит ошибка 404. Я прикрепила фото структуры проекта и код. Заранее спасибо за помощь.
empBean:
package app.bean;

import app.entity.Emp;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;

@Stateless
public class EmpBean {
    @PersistenceContext(unitName = "DEVMODE")
    private EntityManager em;

    public Emp add(Emp emp) {
        return em.merge(emp);
    }

    public Emp get(Integer empno) {
        return em.find(Emp.class, empno);
    }

    public void update(Emp emp) {
        add(emp);
    }
    public void delete(long empno){
        em.remove(get((int) empno));
    }

    public List<Emp> getAll(){
        TypedQuery<Emp> namedQuery = em.createNamedQuery("Emp.getAll", Emp.class);
        return namedQuery.getResultList();
    }
}

Emp:
package app.entity;

import javax.persistence.*;
import java.sql.Date;

@Entity(name="emp")
@NamedQuery(name = "Emp.getAll", query = "SELECT e from emp e")

public class Emp {
    @Id
    @Column(name="empno")
    private Integer empno ;
    @Column(name="ename")
    private String ename;
    @Column(name="job")
    private String job;
    @Column(name="mgr")
    private Integer mgr;
    @Column(name="hiredate")
    private Date hiredate;
    @Column(name="sal")
    private Integer sal;
    @Column(name="comm")
    private Integer comm;
    @Column(name="deptno")
    private Integer deptno;

    public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Integer sal, Integer comm, Integer deptno, String id) {
        this.empno = empno;
        this.ename = ename;
        this.job = job;
        this.mgr = mgr;
        this.hiredate = hiredate;
        this.sal = sal;
        this.comm = comm;
        this.deptno = deptno;
    }

    public Emp() {
    }

    public Integer getEmpno() {
        return empno;
    }

    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Integer getMgr() {
        return mgr;
    }

    public void setMgr(Integer mgr) {
        this.mgr = mgr;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public Integer getSal() {
        return sal;
    }

    public void setSal(Integer sal) {
        this.sal = sal;
    }

    public Integer getComm() {
        return comm;
    }

    public void setComm(Integer comm) {
        this.comm = comm;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

}

Select1Servlet:
package app.servlets;

import app.bean.DeptBean;
import app.bean.EmpBean;
import app.bean.SalgradeBean;
import app.entity.Dept;
import app.entity.Emp;
import app.entity.Salgrade;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;

//@WebServlet("/search")
public class Select1Servlet extends HttpServlet {

    @EJB
    private EmpBean empBean;
    private DeptBean deptBean;
    private SalgradeBean salgradeBean;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        req.setCharacterEncoding("UTF-8");
        req.getRequestDispatcher("/searchview.jsp").forward(req, resp);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
//        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/users";
        String userName = "root";
        String password = "7777";

        Statement st;
        try {
//            Class.forName("com.mysql.jdbc.Driver");
//            conn = DriverManager.getConnection(url , userName, password);
            System.out.println("Connected!");
            String numb = request.getParameter("numb");

            ArrayList al = null;
            ArrayList pid_list = new ArrayList();

//            String query = "SELECT emp.ename, emp.job, emp.sal, dept.dname, salgrade.grade FROM dept,emp,salgrade WHERE (emp.empno = '" + numb + "' ) AND (emp.deptno = dept.deptno) and (emp.sal BETWEEN losal and hisal)  ";

//            System.out.println("query " + query);
            st = conn.createStatement();
//            ResultSet rs = st.executeQuery(query);
            Emp emp = empBean.get(Integer.valueOf(numb));
            String ename= emp.getEname();
            String job = emp.getJob();
            Integer sal = emp.getSal();
            Integer deptnoEmp= emp.getDeptno();
            Dept dept = deptBean.get(Integer.valueOf(deptnoEmp));
            String dname = dept.getDname();
            Salgrade salgrade = salgradeBean.get(sal);
            Integer grade = salgrade.getGrade();

//            while (rs.next()) {
                al = new ArrayList();
//                out.println(rs.getString(1));
//                out.println(rs.getString(2));
//                out.println(rs.getString(3));
//                out.println(rs.getString(4));
                al.add(ename);
                al.add(job);
                al.add(sal);
                al.add(dname);
                al.add(grade);

                System.out.println("al :: " + al);
                pid_list.add(al);
//            }

            request.setAttribute("piList", pid_list);
            RequestDispatcher view = request.getRequestDispatcher("/searchview.jsp");
            view.forward(request, response);
            conn.close();
            System.out.println("Disconnected!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

select1.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title> Enter the number </title>
    <link rel="stylesheet" href="design/w3.css">

<form method="post" name="frm" action="search">

Search User

User Number
            : <input type="number" name="numb" id="numb">

            <input type="submit" name="submit" value="Search" onclick="form.action='/search';">

</form>

searchview.jsp:
<%@ page import="java.util.*" %>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%--<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>--%>
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title> List of emp </title>
    <link rel="stylesheet" href="design/w3.css">

<form  method="get" name="frm" action="searchview">

            User Record

        User Name
        Job
        Sal
        Dname
        Grade

    <%
       int count = 0;
       String color = "#ffffff";
       if (request.getAttribute("piList") != null) {
           ArrayList al = (ArrayList) request.getAttribute("piList");
           System.out.println(al);
           Iterator itr = al.iterator();
           while (itr.hasNext()) {

               if ((count % 2) == 0) {
                   color = "#ffffff";
               }
               count++;
               ArrayList pList = (ArrayList) itr.next();
   %>
    <tr style="background-color:<%=color%>;">
        <%=pList.get(0)%>
        <%=pList.get(1)%>
        <%=pList.get(2)%>
        <%=pList.get(3)%>
        <%=pList.get(4)%>

    <%
           }
       }
       if (count == 0) {
   %>

        No Record Found..

    <%            }
   %>

</form>


text:
Q: How to populate a many-to-many relationship as table For my project (hotel website) I have two entities Room & Week and a many-to-many relationship between them with two additionals fields:

*

*price: Price for a room and a week

*number: Number of room available for a week

I would like to create a form to allow the admin to see/change all price/number in a single table like this:

Price & number are text fields.
Is there a known way to generate this with Symfony or do you know a bundle?
Thanks for help.

A: if i read it well your database setup is bad. A week is not an entity but a period of time! you could make an entity with a name like 'RoomOffer' where you have fields like starttime, stoptime, price and room. the room field is then a many-to-many or a many-to-one relation...
Then your table shows lot's of the same forms (each cell). You could use a collection for that.http://symfony.com/doc/current/cookbook/form/form_collections.html
Be warned: its advanced.

A: Finally, I did it by myself, I did:

*

*Create the HTML table

*In each cell I create twi fields like myfield[XX][price] && myfield[XX][number] and after I get all POST data to update my database if needed. With XX a DB id

Regards,


text:
Q: Div that fits into parent and maintains an aspect ratio I've got a div element that maintains an aspect ratio: it calculates its height based on its width (using the padding trick). What I'd like to do is to put this div into another one by fitting the maximum space available, vertically and horizontally, no crop. I think the closest thing to what I want is the object-fit: contain - which is img only.
I want the div to cover the max height and width possible while maintaining the aspect ratio. No vertical or horizontal crop.
Is it even possible with CSS only? If so, how?
Update:
A good article where things are at the moment.
code (Can be any other solution, doesn't have to be built on this snippet):

html,
body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.container {
  position: relative;
  width: 100%;
}

.container:before {
  content: "";
  display: block;
  width: 50%;
  padding-top: 50%;
}

.embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: red;
}

    this should accommodate all the available space and maintain aspect ratio, no crop when width is too wide

A: aspect-ratio with overflow:hidden on Chromium 88, Firefox 87 , and Safari Technology Preview 118 is your friend.
Update January 2023:
Now you'll need a @container (aspect-ratio > X) container query too. Firefox v110.0b2, Safari and Chromium all pass.
I updated the code below, also the demo on jsitor.

html,
body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.container {
  container-type: size;
  container-name: resize-box;
  display: grid;
  resize: both;
  overflow: hidden;
  border: black 2px solid;
  min-width: 50px;
  min-height: 50px;
  width: 150px;
}

.embed {
  width: 100%;
  aspect-ratio: 1/1;
  object-fit: contain;
  overflow: hidden;
  border: 2px red solid;
  box-sizing: border-box;
  display: flex;
  margin: auto;
}

@container resize-box (aspect-ratio > 1/1) {
  .embed {
    width: auto;
    height: 100%;
  }
}

.embed > div {
  margin: auto;
}

1:1

A: The only workaround I managed to achieve so far is to wrap the child element in to svg's foraignObject tag:

const container = document.getElementById('container');
document.getElementById('btn').addEventListener('click', () => {
  container.style.height = container.style.height === '100px' ? '200px' : '100px';
});
body {
  margin: 1rem;
}

*,
*::before,
*::after {
  box-sizing: border-box;
}

button {
  margin-bottom: 1rem;
}

#container {
  background-color: #ffceaf;
  width: 400px;
}

svg {
  background-color: #b8d6ff;
  height: auto;
  width: auto;
  max-width: 100%;
  max-height: 100%;
  overflow: hidden;
}

#content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border: solid;
}
<button id="btn">Change parent height</button>

  <svg width="15000" height="5000">
    <foreignObject width="100%" height="100%">

        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content
        content content content content content content content

    </foreignObject>
  </svg>

This solution has downsides:

*

*Browser compatibility (IE/Edge do not support foraignObject properly)

*It's not a best practice. Including elements from a different XML namespace may cause futher issues(?).

I feel like using JS might be better option here.

A: Ok, it looks like it can't be solved by CSS only. If anyone interested, I've put together a React component that does the job (Tests and better README soon, when I have time).
It wraps its children into a div and uses JavaScript to compute the width and height of that div in order to accommodate the available space while maintains the given aspect ratio. It basically stretches the wrapper until one of the sides reaches its maximum.
BREAKING UPDATE a CSS only solution has been found!

A: I'm not sure if this is the best solution, but it is pure css.
It uses nested flexboxes. The outer is flex-direction: row and the inner is flex-direction: column. It is important the inner also has to have aspect-ratio is set to 1/1 and notice that inner's height is set and inner:before's width is set.

.outer {
  width: 80%;
  height: 80%;
  margin: auto;
  background-color: red;
  padding: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.inner {
  height: 100%;
  aspect-ratio: 1 / 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.inner:before {
  content: '';
  width: 100%;
  aspect-ratio: 1 / 1;
  background-color: blue;
}

A: Here's my CSS-only solution:
Codepen Link or run demo here ⬇

.resizable-container {
  resize: both;
  overflow: scroll;
  border: 1px solid black;
  padding: 3px;
  height: 140px;
  width: 330px;
}

.container {
  height: 100%;
  box-sizing: border-box;
}

.aspect-thing {
  aspect-ratio: 16/9;
  border: 2px red solid;
  box-sizing: border-box;

  max-width: 100%;
  max-height: 100%;
  margin: auto;
}

Resize me ^


text:
Q: phpunit.rest.xml fatal error could not read "" I am trying to run the Magento web api tests by running the following command:
vendor/bin/phpunit --config ./dev/tests/api-functional/phpunit_rest.xml

But it gives this error:
PHP Fatal error:  Uncaught PHPUnit\Framework\Exception: Could not read "".

/var/www/osp.example.com/magento-headless/Magento2/dev/tests/api-functional/testsuite/Magento/WebApiTest.php:39
/var/www/osp.example.com/magento-headless/Magento2/vendor/phpunit/phpunit/phpunit:61

  thrown in /var/www/osp.example.com/magento-headless/Magento2/vendor/phpunit/phpunit/src/Util/Xml.php on line 135

After a lot of debugging, I see that WebpApiTest.php runs the function getConfigurationFile which gives back an empty string. This is the code of that function:
    /**
     * Returns config file name from command line params.
     *
     * @return string
     */
    private static function getConfigurationFile(): string
    {
        $params = getopt('c:', ['configuration:']);

        $longConfig = $params['configuration'] ?? '';
        $shortConfig = $params['c'] ?? '';

        return $shortConfig ? $shortConfig : $longConfig;
    }

I don't really get what its doing and which information it is supposed to return.
Can anyone check what kinda information it is supposed to return? Maybe then I can fix it and run the webapi tests of Magento 2.

A: Does the file ./dev/tests/api-functional/phpunit_rest.xml exist?
Magento includes ".dist" versions of configuration files for certain tools. The first step to using them is to make a copy without the ".dist" extension (thus preserving the original as a backup/reference).

A: It seems like PHPUnit tries to find a file named after the name-attribute of the testsuite-tag

*

*if it either cannot find any tests (wrong naming or wrong directory)

*here is a fatal error occuring in a test-script; which occures so early that PHPUnit cannot identify the content of that file as a test - as no class could be loaded up until that point.


text:
Q: Cisco VPN Client automatic login I need to automate the login process of a Cisco VPN Client version 5.0.07.0440.
I've tried using a command line like this but there is something wrong:
vpnclient.exe connect MyVPNConnection user username pwd password

This starts the connection but then a User Authentication dialog is shown, asking for username, password and domain. Username and password are already filled, domain is not necessary.
To continue I must press the OK button.
Is there a way to not show the dialog and automatically login into the vpn?

A: Run vpnclient.exe /?:

That way just run
vpnclient.exe connect MyVPNConnection -s < file.txt
file.txt
username
password

A: Below worked for me Cisco AnyConnect Secure Mobility Client:

*

*Try to connect to VPN for the first time using vpncli.exe and note every keystroke i.e every command, every enter( \n ) you press, username & password you enter.

*Copy each command sequentially in .login_info file.

Sample .login_info:
connect unkbown.data-protect.com
\n
\n
KC23452
\n

Note: Replace \n with normal enter, these are the exact steps that I followed while connecting via vpncli.exe. Username and group-name were saved automatically that's the reason the 2nd and 3rd lines are \n ( enter ). Also, the last \n is required.

*Go to C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client

*Open CMD here

*vpncli.exe -s < .login_info

A: First, we need to use the vpncli.exe command line approach with the -s switch.
It works from command line or script. If you were looking for a solution in C#:
//file = @"C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"
var file = vpnInfo.ExecutablePath;
var host = vpnInfo.Host;
var profile = vpnInfo.ProfileName;
var user = vpnInfo.User;
var pass = vpnInfo.Password;
var confirm = "y";

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = file,
        Arguments = string.Format("-s"),
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
    }
};

proc.OutputDataReceived += (s, a) => stdOut.AppendLine(a.Data);
proc.ErrorDataReceived += (s, a) => stdOut.AppendLine(a.Data);

//make sure it is not running, otherwise connection will fail
var procFilter = new HashSet<string>() { "vpnui", "vpncli" };
var existingProcs = Process.GetProcesses().Where(p => procFilter.Contains(p.ProcessName));
if (existingProcs.Any())
{
    foreach (var p in existingProcs)
    {
        p.Kill();
    }
}

proc.Start();
proc.BeginOutputReadLine();

//simulate profile file
var simProfile = string.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}"
    , Environment.NewLine
    , string.Format("connect {0}", host)
    , profile
    , user
    , pass
    , confirm
    );

proc.StandardInput.Write(simProfile);
proc.StandardInput.Flush();

//todo: these should be a configurable value
var waitTime = 500; //in ms
var maxWait = 10;

var count = 0;
var output = stdOut.ToString();
while (!output.Contains("state: Connected"))
{
    output = stdOut.ToString();

    if (count > maxWait)
        throw new Exception("Unable to connect to VPN.");

    count++;
    Thread.Sleep(waitTime);
}
stdOut.Append("VPN connection established! ...");

(This might have extra stuff which is not required for you specific case.)

A: Here is a BAT script for automatic logon using Cisco AnyConnect Secure Mobility Client (version 4.10.03104):
taskkill -im vpnui.exe -f
"%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" disconnect
SLEEP 3
"%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" -s < credential.txt
SLEEP 8
"%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe"

The file "credential.txt" must contain three lines:
connect <host>
<login>
<password>

where <host> is IP address or hostname of the host to connect, <login> is your login, and <password> is your password. The first line taskkill -im vpnui.exe -f is nesessary for killing the GUI, because when the GUI is running the login through the command line doesn't work. The last line launches the GUI again after successive logon.
The same script written as a VBS file (suitable for Windows Task Sheduler):
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run "taskkill -im vpnui.exe -f"

WshShell.Run """%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" disconnect"

WScript.Sleep 3000

WshShell.Run "cmd /K ""%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" -s < credential.txt"

WScript.Sleep 8000

WshShell.Run """%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe"""

Save this script as "login.vbs", and assign running it as an "Action" in the Windows Task Sheduler.


text:
Q: Salto de pagina concatenado en una variable Laravel Estoy desarrollando un proyecto utilizando Laravel.
Cuando intento mostrar por pantalla los detalles de un actor, muestra todo en la misma linea de esta manera:

Esta tomando los  como texto y no como salto de pagina.
Esta es mi porcion de codigo
    public function getDetails()
{
  return ('id :'.$this->id.'
'.'Nombre: '.$this->first_name.'
'.'Apellido: '.$this->last_name.'
'.'Rating: '.$this->rating.'
'.'Id de pelicula favorita: '.$this->favorite_movie_id);
}

Yo quiciera mostar cada detalle en un renglon aparte.
Gracias!!

A: Es muy probable que estés printeando en blade los datos de la siguiente manera.
{{ tu_codigo }}

Prueba de la siguiente manera si quieres que "renderice" el html que llega como respuesta:
{!! tu_codigo !!}


text:
Q: TortoiseSVN -- Icons are not displaying After TortoiseSVN bugged me to update, i downloaded a new installer and ran it. It still works fine now, though it does not properly display icon overlays (despite that option being on in the settings). How can i fix it?

A: If you've just updated to 1.6.8 (as I have), you might have to do a repair install to fix the icon overlay issue. As detailed on the TortoiseSVN blog here.


text:
Q: Undo redo Operation I have used the following code for undo redo operation. I am changing the label's background color and my undo/redo operation is working fine but now i have added label's text color so whenever i change only background color or text color individually it works fine but if i change background color and text color both at a time then it will not work properly. what should i do? please help.!
@IBOutlet var myObject: UILabel!

//  MARK: - View Life Cycle
override func viewDidLoad() {
    super.viewDidLoad()
    myObject.backgroundColor = UIColor.yellow
}

func setMyObjectColor(_ color: UIColor) {
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectColor(myObject.backgroundColor!)
        myObject.backgroundColor = color
}

func setMyObjectTextColor(_ color: UIColor) {
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectTextColor(myObject.textColor!)
        myObject.textColor = color
}

@IBAction func changeColor(_ sender: Any){
    setMyObjectColor(UIColor.blue)
}

@IBAction func changeTextColor(_ sender: Any){
    setMyObjectTextColor(UIColor.white)
}

@IBAction func undo(_ sender: Any) {
    undoManager?.undo()
}

@IBAction func redo(_ sender: Any) {
    undoManager?.redo()
}}

A: @IBOutlet var myObject: UILabel!

//  MARK: - View Life Cycle
override func viewDidLoad() {
    super.viewDidLoad()
    myObject.backgroundColor = UIColor.yellow
}

func setMyObjectColor(_ Backcolor: UIColor) {
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectColor(myObject.backgroundColor!)
        myObject.backgroundColor = Backcolor
}

func setMyObjectTextColor(_ Textcolor: UIColor) {
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectTextColor(myObject.textColor!)
        myObject.textColor = Textcolor
}

func setMyObjectText(_ Text: String) {
    (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setMyObjectText((myObject.text! as AnyObject) as! String)
    myObject.text = Text
}

@IBAction func changeColor(_ sender: Any){
    setMyObjectColor(UIColor.blue)
}

@IBAction func changeTextColor(_ sender: Any){
    setMyObjectTextColor(UIColor.white)
}

@IBAction func changeText(_ sender: Any) {
    setMyObjectText("Khush")
}

@IBAction func undo(_ sender: Any) {
    undoManager?.undo()
}

@IBAction func redo(_ sender: Any) {
    undoManager?.redo()
}

Using this code my issue is solved.


text:
Q: Wordpress Admin page on Ubuntu is hidden by the grey screen I've just move all wordpress site from Windows server to Ubuntu server. The main site (http://example.com) show correctly, but the admin page (~/wp-admin) has problems.
I can see the left sidebar only (post, page, theme...), but the main frame where shows me the content of post to edit, lists my plugins,... now is hidden by the grey screen, and I can't  do anymore with it.
You can see the screenshot here: https://www.upsieutoc.com/image/DWnf (sorry I don't have enough repu for post photo directly), and sorry because my language (Vietnamese) in the screenshot.
Thanks for reading my post and hope you answer me ASAP


text:
Q: upgrade to manifest 2 my chrome apps no longer functions my application for google chrome no longer works, i upgraded as oer google to manifest 2 but now the popup baloon no longer opens when the icon is clicked below are both manifest and script.
when menifest 1 was in place the box did not open fully, hopfully your expert advice can help
  {
  "name": "XE Currency Converter",
    "manifest_version": 2,

  "version": "2.3.2",
  "description": "An exchange rate based currency converter provided by XE.com",
  "browser_action": {
    "default_icon": "19.png",
    "popup": "popup.html"
  }
  }

my script

<FORM METHOD=POST ACTION="http://www.xe.com/ucc/convert.cgi" target="_blank">

    xe.com
    Universal Currency Converter   ®

    <!XERC-UCC1-P1.1-R1>

Convert this

    <!XERC-UCC1-P1.3-R1>

  from this currency

    <!XERC-UCC1-P1.5-R1>

    <!XERC-UCC1-P1.5-R1>

  into this currency.

    <INPUT TYPE="text" NAME="Amount" VALUE="1" SIZE=10>

    <!XERC-UCC1-P1.2-R2>

    <SELECT NAME="From" SIZE=5  id ="FROM">
      <OPTION VALUE="EUR" SELECTED>Euro EUR</OPTION>
      <OPTION VALUE="USD">United States Dollars USD</OPTION>
      <OPTION VALUE="GBP">United Kingdom Pounds GBP</OPTION>
      <OPTION VALUE="CAD">Canada Dollars CAD</OPTION>
      <OPTION VALUE="AUD">Australia Dollars AUD</OPTION>
      <OPTION VALUE="JPY">Japan Yen JPY</OPTION>
      <OPTION VALUE="INR">India Rupees INR</OPTION>
      <OPTION VALUE="NZD">New Zealand Dollars NZD</OPTION>
      <OPTION VALUE="CHF">Switzerland Francs CHF</OPTION>
      <OPTION VALUE="ZAR">South Africa Rand ZAR</OPTION>
      <OPTION VALUE="EUR">-- Top Currencies: --</OPTION>
<OPTION VALUE="AED">AED - United Arab Emirates Dirham</OPTION>
<OPTION VALUE="AFN">AFN - Afghan Afghani</OPTION>
<OPTION VALUE="ALL">ALL - Albanian Lek</OPTION>
<OPTION VALUE="AMD">AMD - Armenian Dram</OPTION>
<OPTION VALUE="ANG">ANG - Dutch Guilder</OPTION>
<OPTION VALUE="AOA">AOA - Angolan Kwanza</OPTION>
<OPTION VALUE="ARS">ARS - Argentine Peso</OPTION>
<OPTION VALUE="AUD">AUD - Australian Dollar</OPTION>
<OPTION VALUE="AWG">AWG - Aruban or Dutch Guilder</OPTION>
<OPTION VALUE="AZN">AZN - Azerbaijani New Manat</OPTION>
<OPTION VALUE="BAM">BAM - Bosnian Convertible Marka</OPTION>
<OPTION VALUE="BBD">BBD - Barbadian or Bajan Dollar</OPTION>
<OPTION VALUE="BDT">BDT - Bangladeshi Taka</OPTION>
<OPTION VALUE="BGN">BGN - Bulgarian Lev</OPTION>
<OPTION VALUE="BHD">BHD - Bahraini Dinar</OPTION>
<OPTION VALUE="BIF">BIF - Burundian Franc</OPTION>
<OPTION VALUE="BMD">BMD - Bermudian Dollar</OPTION>
<OPTION VALUE="BND">BND - Bruneian Dollar</OPTION>
<OPTION VALUE="BOB">BOB - Bolivian Boliviano</OPTION>
<OPTION VALUE="BRL">BRL - Brazilian Real</OPTION>
<OPTION VALUE="BSD">BSD - Bahamian Dollar</OPTION>
<OPTION VALUE="BTN">BTN - Bhutanese Ngultrum</OPTION>
<OPTION VALUE="BWP">BWP - Botswana Pula</OPTION>
<OPTION VALUE="BYR">BYR - Belarusian Ruble</OPTION>
<OPTION VALUE="BZD">BZD - Belizean Dollar</OPTION>
<OPTION VALUE="CAD">CAD - Canadian Dollar</OPTION>
<OPTION VALUE="CDF">CDF - Congolese Franc</OPTION>
<OPTION VALUE="CHF">CHF - Swiss Franc</OPTION>
<OPTION VALUE="CLP">CLP - Chilean Peso</OPTION>
<OPTION VALUE="CNY">CNY - Chinese Yuan Renminbi</OPTION>
<OPTION VALUE="COP">COP - Colombian Peso</OPTION>
<OPTION VALUE="CRC">CRC - Costa Rican Colon</OPTION>
<OPTION VALUE="CUC">CUC - Cuban Convertible Peso</OPTION>
<OPTION VALUE="CUP">CUP - Cuban Peso</OPTION>
<OPTION VALUE="CVE">CVE - Cape Verdean Escudo</OPTION>
<OPTION VALUE="CZK">CZK - Czech Koruna</OPTION>
<OPTION VALUE="DJF">DJF - Djiboutian Franc</OPTION>
<OPTION VALUE="DKK">DKK - Danish Krone</OPTION>
<OPTION VALUE="DOP">DOP - Dominican Peso</OPTION>
<OPTION VALUE="DZD">DZD - Algerian Dinar</OPTION>
<OPTION VALUE="EGP">EGP - Egyptian Pound</OPTION>
<OPTION VALUE="ERN">ERN - Eritrean Nakfa</OPTION>
<OPTION VALUE="ETB">ETB - Ethiopian Birr</OPTION>
<OPTION VALUE="EUR">EUR - Euro</OPTION>
<OPTION VALUE="FJD">FJD - Fijian Dollar</OPTION>
<OPTION VALUE="FKP">FKP - Falkland Island Pound</OPTION>
<OPTION VALUE="GBP">GBP - British Pound</OPTION>
<OPTION VALUE="GEL">GEL - Georgian Lari</OPTION>
<OPTION VALUE="GGP">GGP - Guernsey Pound</OPTION>
<OPTION VALUE="GHS">GHS - Ghanaian Cedi</OPTION>
<OPTION VALUE="GIP">GIP - Gibraltar Pound</OPTION>
<OPTION VALUE="GMD">GMD - Gambian Dalasi</OPTION>
<OPTION VALUE="GNF">GNF - Guinean Franc</OPTION>
<OPTION VALUE="GTQ">GTQ - Guatemalan Quetzal</OPTION>
<OPTION VALUE="GYD">GYD - Guyanese Dollar</OPTION>
<OPTION VALUE="HKD">HKD - Hong Kong Dollar</OPTION>
<OPTION VALUE="HNL">HNL - Honduran Lempira</OPTION>
<OPTION VALUE="HRK">HRK - Croatian Kuna</OPTION>
<OPTION VALUE="HTG">HTG - Haitian Gourde</OPTION>
<OPTION VALUE="HUF">HUF - Hungarian Forint</OPTION>
<OPTION VALUE="IDR">IDR - Indonesian Rupiah</OPTION>
<OPTION VALUE="ILS">ILS - Israeli Shekel</OPTION>
<OPTION VALUE="IMP">IMP - Isle of Man Pound</OPTION>
<OPTION VALUE="INR">INR - Indian Rupee</OPTION>
<OPTION VALUE="IQD">IQD - Iraqi Dinar</OPTION>
<OPTION VALUE="IRR">IRR - Iranian Rial</OPTION>
<OPTION VALUE="ISK">ISK - Icelandic Krona</OPTION>
<OPTION VALUE="JEP">JEP - Jersey Pound</OPTION>
<OPTION VALUE="JMD">JMD - Jamaican Dollar</OPTION>
<OPTION VALUE="JOD">JOD - Jordanian Dinar</OPTION>
<OPTION VALUE="JPY">JPY - Japanese Yen</OPTION>
<OPTION VALUE="KES">KES - Kenyan Shilling</OPTION>
<OPTION VALUE="KGS">KGS - Kyrgyzstani Som</OPTION>
<OPTION VALUE="KHR">KHR - Cambodian Riel</OPTION>
<OPTION VALUE="KMF">KMF - Comoran Franc</OPTION>
<OPTION VALUE="KPW">KPW - North Korean Won</OPTION>
<OPTION VALUE="KRW">KRW - South Korean Won</OPTION>
<OPTION VALUE="KWD">KWD - Kuwaiti Dinar</OPTION>
<OPTION VALUE="KYD">KYD - Caymanian Dollar</OPTION>
<OPTION VALUE="KZT">KZT - Kazakhstani Tenge</OPTION>
<OPTION VALUE="LAK">LAK - Lao or Laotian Kip</OPTION>
<OPTION VALUE="LBP">LBP - Lebanese Pound</OPTION>
<OPTION VALUE="LKR">LKR - Sri Lankan Rupee</OPTION>
<OPTION VALUE="LRD">LRD - Liberian Dollar</OPTION>
<OPTION VALUE="LSL">LSL - Basotho Loti</OPTION>
<OPTION VALUE="LTL">LTL - Lithuanian Litas</OPTION>
<OPTION VALUE="LVL">LVL - Latvian Lat</OPTION>
<OPTION VALUE="LYD">LYD - Libyan Dinar</OPTION>
<OPTION VALUE="MAD">MAD - Moroccan Dirham</OPTION>
<OPTION VALUE="MDL">MDL - Moldovan Leu</OPTION>
<OPTION VALUE="MGA">MGA - Malagasy Ariary</OPTION>
<OPTION VALUE="MKD">MKD - Macedonian Denar</OPTION>
<OPTION VALUE="MMK">MMK - Burmese Kyat</OPTION>
<OPTION VALUE="MNT">MNT - Mongolian Tughrik</OPTION>
<OPTION VALUE="MOP">MOP - Macau Pataca</OPTION>
<OPTION VALUE="MRO">MRO - Mauritanian Ouguiya</OPTION>
<OPTION VALUE="MUR">MUR - Mauritian Rupee</OPTION>
<OPTION VALUE="MVR">MVR - Maldivian Rufiyaa</OPTION>
<OPTION VALUE="MWK">MWK - Malawian Kwacha</OPTION>
<OPTION VALUE="MXN">MXN - Mexican Peso</OPTION>
<OPTION VALUE="MYR">MYR - Malaysian Ringgit</OPTION>
<OPTION VALUE="MZN">MZN - Mozambican Metical</OPTION>
<OPTION VALUE="NAD">NAD - Namibian Dollar</OPTION>
<OPTION VALUE="NGN">NGN - Nigerian Naira</OPTION>
<OPTION VALUE="NIO">NIO - Nicaraguan Cordoba</OPTION>
<OPTION VALUE="NOK">NOK - Norwegian Krone</OPTION>
<OPTION VALUE="NPR">NPR - Nepalese Rupee</OPTION>
<OPTION VALUE="NZD">NZD - New Zealand Dollar</OPTION>
<OPTION VALUE="OMR">OMR - Omani Rial</OPTION>
<OPTION VALUE="PAB">PAB - Panamanian Balboa</OPTION>
<OPTION VALUE="PEN">PEN - Peruvian Nuevo Sol</OPTION>
<OPTION VALUE="PGK">PGK - Papua New Guinean Kina</OPTION>
<OPTION VALUE="PHP">PHP - Philippine Peso</OPTION>
<OPTION VALUE="PKR">PKR - Pakistani Rupee</OPTION>
<OPTION VALUE="PLN">PLN - Polish Zloty</OPTION>
<OPTION VALUE="PYG">PYG - Paraguayan Guarani</OPTION>
<OPTION VALUE="QAR">QAR - Qatari Riyal</OPTION>
<OPTION VALUE="RON">RON - Romanian New Leu</OPTION>
<OPTION VALUE="RSD">RSD - Serbian Dinar</OPTION>
<OPTION VALUE="RUB">RUB - Russian Ruble</OPTION>
<OPTION VALUE="RWF">RWF - Rwandan Franc</OPTION>
<OPTION VALUE="SAR">SAR - Saudi or Saudi Arabian Riyal</OPTION>
<OPTION VALUE="SBD">SBD - Solomon Islander Dollar</OPTION>
<OPTION VALUE="SCR">SCR - Seychellois Rupee</OPTION>
<OPTION VALUE="SDG">SDG - Sudanese Pound</OPTION>
<OPTION VALUE="SEK">SEK - Swedish Krona</OPTION>
<OPTION VALUE="SGD">SGD - Singapore Dollar</OPTION>
<OPTION VALUE="SHP">SHP - Saint Helenian Pound</OPTION>
<OPTION VALUE="SLL">SLL - Sierra Leonean Leone</OPTION>
<OPTION VALUE="SOS">SOS - Somali Shilling</OPTION>
<OPTION VALUE="SPL">SPL - Seborgan Luigino</OPTION>
<OPTION VALUE="SRD">SRD - Surinamese Dollar</OPTION>
<OPTION VALUE="STD">STD - Sao Tomean Dobra</OPTION>
<OPTION VALUE="SVC">SVC - Salvadoran Colon</OPTION>
<OPTION VALUE="SYP">SYP - Syrian Pound</OPTION>
<OPTION VALUE="SZL">SZL - Swazi Lilangeni</OPTION>
<OPTION VALUE="THB">THB - Thai Baht</OPTION>
<OPTION VALUE="TJS">TJS - Tajikistani Somoni</OPTION>
<OPTION VALUE="TMT">TMT - Turkmenistani Manat</OPTION>
<OPTION VALUE="TND">TND - Tunisian Dinar</OPTION>
<OPTION VALUE="TOP">TOP - Tongan Pa'anga</OPTION>
<OPTION VALUE="TRY">TRY - Turkish Lira</OPTION>
<OPTION VALUE="TTD">TTD - Trinidadian Dollar</OPTION>
<OPTION VALUE="TVD">TVD - Tuvaluan Dollar</OPTION>
<OPTION VALUE="TWD">TWD - Taiwan New Dollar</OPTION>
<OPTION VALUE="TZS">TZS - Tanzanian Shilling</OPTION>
<OPTION VALUE="UAH">UAH - Ukrainian Hryvna</OPTION>
<OPTION VALUE="UGX">UGX - Ugandan Shilling</OPTION>
<OPTION VALUE="USD">USD - US Dollar</OPTION>
<OPTION VALUE="UYU">UYU - Uruguayan Peso</OPTION>
<OPTION VALUE="UZS">UZS - Uzbekistani Som</OPTION>
<OPTION VALUE="VEF">VEF - Venezuelan Bolivar Fuerte</OPTION>
<OPTION VALUE="VND">VND - Vietnamese Dong</OPTION>
<OPTION VALUE="VUV">VUV - Ni-Vanuatu Vatu</OPTION>
<OPTION VALUE="WST">WST - Samoan Tala</OPTION>
<OPTION VALUE="XAF">XAF - Central African CFA Franc BEAC</OPTION>
<OPTION VALUE="XAG">XAG - Silver Ounce</OPTION>
<OPTION VALUE="XAU">XAU - Gold Ounce</OPTION>
<OPTION VALUE="XCD">XCD - East Caribbean Dollar</OPTION>
<OPTION VALUE="XDR">XDR - IMF Special Drawing Rights</OPTION>
<OPTION VALUE="XOF">XOF - CFA Franc</OPTION>
<OPTION VALUE="XPD">XPD - Palladium Ounce</OPTION>
<OPTION VALUE="XPF">XPF - CFP Franc</OPTION>
<OPTION VALUE="XPT">XPT - Platinum Ounce</OPTION>
<OPTION VALUE="YER">YER - Yemeni Rial</OPTION>
<OPTION VALUE="ZAR">ZAR - South African Rand</OPTION>
<OPTION VALUE="ZMK">ZMK - Zambian Kwacha</OPTION>
<OPTION VALUE="ZWD">ZWD - Zimbabwean Dollar</OPTION>
    </SELECT>

    <!XERC-UCC1-P1.4-R2>

    <input type="button" value="&#8660" onClick="swapVar(); window.location.reload();">

    <SELECT NAME="To" SIZE=5 id ="TO">
      <OPTION VALUE="USD" SELECTED>United States Dollars USD</OPTION>
      <OPTION VALUE="EUR">Euro EUR</OPTION>
      <OPTION VALUE="GBP">United Kingdom Pounds GBP</OPTION>
      <OPTION VALUE="CAD">Canada Dollars CAD</OPTION>
      <OPTION VALUE="AUD">Australia Dollars AUD</OPTION>
      <OPTION VALUE="JPY">Japan Yen JPY</OPTION>
      <OPTION VALUE="INR">India Rupees INR</OPTION>
      <OPTION VALUE="NZD">New Zealand Dollars NZD</OPTION>
      <OPTION VALUE="CHF">Switzerland Francs CHF</OPTION>
      <OPTION VALUE="ZAR">South Africa Rand ZAR</OPTION>
      <OPTION VALUE="USD">-- Top Currencies: --</OPTION>
<OPTION VALUE="AED">AED - United Arab Emirates Dirham</OPTION>
<OPTION VALUE="AFN">AFN - Afghan Afghani</OPTION>
<OPTION VALUE="ALL">ALL - Albanian Lek</OPTION>
<OPTION VALUE="AMD">AMD - Armenian Dram</OPTION>
<OPTION VALUE="ANG">ANG - Dutch Guilder</OPTION>
<OPTION VALUE="AOA">AOA - Angolan Kwanza</OPTION>
<OPTION VALUE="ARS">ARS - Argentine Peso</OPTION>
<OPTION VALUE="AUD">AUD - Australian Dollar</OPTION>
<OPTION VALUE="AWG">AWG - Aruban or Dutch Guilder</OPTION>
<OPTION VALUE="AZN">AZN - Azerbaijani New Manat</OPTION>
<OPTION VALUE="BAM">BAM - Bosnian Convertible Marka</OPTION>
<OPTION VALUE="BBD">BBD - Barbadian or Bajan Dollar</OPTION>
<OPTION VALUE="BDT">BDT - Bangladeshi Taka</OPTION>
<OPTION VALUE="BGN">BGN - Bulgarian Lev</OPTION>
<OPTION VALUE="BHD">BHD - Bahraini Dinar</OPTION>
<OPTION VALUE="BIF">BIF - Burundian Franc</OPTION>
<OPTION VALUE="BMD">BMD - Bermudian Dollar</OPTION>
<OPTION VALUE="BND">BND - Bruneian Dollar</OPTION>
<OPTION VALUE="BOB">BOB - Bolivian Boliviano</OPTION>
<OPTION VALUE="BRL">BRL - Brazilian Real</OPTION>
<OPTION VALUE="BSD">BSD - Bahamian Dollar</OPTION>
<OPTION VALUE="BTN">BTN - Bhutanese Ngultrum</OPTION>
<OPTION VALUE="BWP">BWP - Botswana Pula</OPTION>
<OPTION VALUE="BYR">BYR - Belarusian Ruble</OPTION>
<OPTION VALUE="BZD">BZD - Belizean Dollar</OPTION>
<OPTION VALUE="CAD">CAD - Canadian Dollar</OPTION>
<OPTION VALUE="CDF">CDF - Congolese Franc</OPTION>
<OPTION VALUE="CHF">CHF - Swiss Franc</OPTION>
<OPTION VALUE="CLP">CLP - Chilean Peso</OPTION>
<OPTION VALUE="CNY">CNY - Chinese Yuan Renminbi</OPTION>
<OPTION VALUE="COP">COP - Colombian Peso</OPTION>
<OPTION VALUE="CRC">CRC - Costa Rican Colon</OPTION>
<OPTION VALUE="CUC">CUC - Cuban Convertible Peso</OPTION>
<OPTION VALUE="CUP">CUP - Cuban Peso</OPTION>
<OPTION VALUE="CVE">CVE - Cape Verdean Escudo</OPTION>
<OPTION VALUE="CZK">CZK - Czech Koruna</OPTION>
<OPTION VALUE="DJF">DJF - Djiboutian Franc</OPTION>
<OPTION VALUE="DKK">DKK - Danish Krone</OPTION>
<OPTION VALUE="DOP">DOP - Dominican Peso</OPTION>
<OPTION VALUE="DZD">DZD - Algerian Dinar</OPTION>
<OPTION VALUE="EGP">EGP - Egyptian Pound</OPTION>
<OPTION VALUE="ERN">ERN - Eritrean Nakfa</OPTION>
<OPTION VALUE="ETB">ETB - Ethiopian Birr</OPTION>
<OPTION VALUE="EUR">EUR - Euro</OPTION>
<OPTION VALUE="FJD">FJD - Fijian Dollar</OPTION>
<OPTION VALUE="FKP">FKP - Falkland Island Pound</OPTION>
<OPTION VALUE="GBP">GBP - British Pound</OPTION>
<OPTION VALUE="GEL">GEL - Georgian Lari</OPTION>
<OPTION VALUE="GGP">GGP - Guernsey Pound</OPTION>
<OPTION VALUE="GHS">GHS - Ghanaian Cedi</OPTION>
<OPTION VALUE="GIP">GIP - Gibraltar Pound</OPTION>
<OPTION VALUE="GMD">GMD - Gambian Dalasi</OPTION>
<OPTION VALUE="GNF">GNF - Guinean Franc</OPTION>
<OPTION VALUE="GTQ">GTQ - Guatemalan Quetzal</OPTION>
<OPTION VALUE="GYD">GYD - Guyanese Dollar</OPTION>
<OPTION VALUE="HKD">HKD - Hong Kong Dollar</OPTION>
<OPTION VALUE="HNL">HNL - Honduran Lempira</OPTION>
<OPTION VALUE="HRK">HRK - Croatian Kuna</OPTION>
<OPTION VALUE="HTG">HTG - Haitian Gourde</OPTION>
<OPTION VALUE="HUF">HUF - Hungarian Forint</OPTION>
<OPTION VALUE="IDR">IDR - Indonesian Rupiah</OPTION>
<OPTION VALUE="ILS">ILS - Israeli Shekel</OPTION>
<OPTION VALUE="IMP">IMP - Isle of Man Pound</OPTION>
<OPTION VALUE="INR">INR - Indian Rupee</OPTION>
<OPTION VALUE="IQD">IQD - Iraqi Dinar</OPTION>
<OPTION VALUE="IRR">IRR - Iranian Rial</OPTION>
<OPTION VALUE="ISK">ISK - Icelandic Krona</OPTION>
<OPTION VALUE="JEP">JEP - Jersey Pound</OPTION>
<OPTION VALUE="JMD">JMD - Jamaican Dollar</OPTION>
<OPTION VALUE="JOD">JOD - Jordanian Dinar</OPTION>
<OPTION VALUE="JPY">JPY - Japanese Yen</OPTION>
<OPTION VALUE="KES">KES - Kenyan Shilling</OPTION>
<OPTION VALUE="KGS">KGS - Kyrgyzstani Som</OPTION>
<OPTION VALUE="KHR">KHR - Cambodian Riel</OPTION>
<OPTION VALUE="KMF">KMF - Comoran Franc</OPTION>
<OPTION VALUE="KPW">KPW - North Korean Won</OPTION>
<OPTION VALUE="KRW">KRW - South Korean Won</OPTION>
<OPTION VALUE="KWD">KWD - Kuwaiti Dinar</OPTION>
<OPTION VALUE="KYD">KYD - Caymanian Dollar</OPTION>
<OPTION VALUE="KZT">KZT - Kazakhstani Tenge</OPTION>
<OPTION VALUE="LAK">LAK - Lao or Laotian Kip</OPTION>
<OPTION VALUE="LBP">LBP - Lebanese Pound</OPTION>
<OPTION VALUE="LKR">LKR - Sri Lankan Rupee</OPTION>
<OPTION VALUE="LRD">LRD - Liberian Dollar</OPTION>
<OPTION VALUE="LSL">LSL - Basotho Loti</OPTION>
<OPTION VALUE="LTL">LTL - Lithuanian Litas</OPTION>
<OPTION VALUE="LVL">LVL - Latvian Lat</OPTION>
<OPTION VALUE="LYD">LYD - Libyan Dinar</OPTION>
<OPTION VALUE="MAD">MAD - Moroccan Dirham</OPTION>
<OPTION VALUE="MDL">MDL - Moldovan Leu</OPTION>
<OPTION VALUE="MGA">MGA - Malagasy Ariary</OPTION>
<OPTION VALUE="MKD">MKD - Macedonian Denar</OPTION>
<OPTION VALUE="MMK">MMK - Burmese Kyat</OPTION>
<OPTION VALUE="MNT">MNT - Mongolian Tughrik</OPTION>
<OPTION VALUE="MOP">MOP - Macau Pataca</OPTION>
<OPTION VALUE="MRO">MRO - Mauritanian Ouguiya</OPTION>
<OPTION VALUE="MUR">MUR - Mauritian Rupee</OPTION>
<OPTION VALUE="MVR">MVR - Maldivian Rufiyaa</OPTION>
<OPTION VALUE="MWK">MWK - Malawian Kwacha</OPTION>
<OPTION VALUE="MXN">MXN - Mexican Peso</OPTION>
<OPTION VALUE="MYR">MYR - Malaysian Ringgit</OPTION>
<OPTION VALUE="MZN">MZN - Mozambican Metical</OPTION>
<OPTION VALUE="NAD">NAD - Namibian Dollar</OPTION>
<OPTION VALUE="NGN">NGN - Nigerian Naira</OPTION>
<OPTION VALUE="NIO">NIO - Nicaraguan Cordoba</OPTION>
<OPTION VALUE="NOK">NOK - Norwegian Krone</OPTION>
<OPTION VALUE="NPR">NPR - Nepalese Rupee</OPTION>
<OPTION VALUE="NZD">NZD - New Zealand Dollar</OPTION>
<OPTION VALUE="OMR">OMR - Omani Rial</OPTION>
<OPTION VALUE="PAB">PAB - Panamanian Balboa</OPTION>
<OPTION VALUE="PEN">PEN - Peruvian Nuevo Sol</OPTION>
<OPTION VALUE="PGK">PGK - Papua New Guinean Kina</OPTION>
<OPTION VALUE="PHP">PHP - Philippine Peso</OPTION>
<OPTION VALUE="PKR">PKR - Pakistani Rupee</OPTION>
<OPTION VALUE="PLN">PLN - Polish Zloty</OPTION>
<OPTION VALUE="PYG">PYG - Paraguayan Guarani</OPTION>
<OPTION VALUE="QAR">QAR - Qatari Riyal</OPTION>
<OPTION VALUE="RON">RON - Romanian New Leu</OPTION>
<OPTION VALUE="RSD">RSD - Serbian Dinar</OPTION>
<OPTION VALUE="RUB">RUB - Russian Ruble</OPTION>
<OPTION VALUE="RWF">RWF - Rwandan Franc</OPTION>
<OPTION VALUE="SAR">SAR - Saudi or Saudi Arabian Riyal</OPTION>
<OPTION VALUE="SBD">SBD - Solomon Islander Dollar</OPTION>
<OPTION VALUE="SCR">SCR - Seychellois Rupee</OPTION>
<OPTION VALUE="SDG">SDG - Sudanese Pound</OPTION>
<OPTION VALUE="SEK">SEK - Swedish Krona</OPTION>
<OPTION VALUE="SGD">SGD - Singapore Dollar</OPTION>
<OPTION VALUE="SHP">SHP - Saint Helenian Pound</OPTION>
<OPTION VALUE="SLL">SLL - Sierra Leonean Leone</OPTION>
<OPTION VALUE="SOS">SOS - Somali Shilling</OPTION>
<OPTION VALUE="SPL">SPL - Seborgan Luigino</OPTION>
<OPTION VALUE="SRD">SRD - Surinamese Dollar</OPTION>
<OPTION VALUE="STD">STD - Sao Tomean Dobra</OPTION>
<OPTION VALUE="SVC">SVC - Salvadoran Colon</OPTION>
<OPTION VALUE="SYP">SYP - Syrian Pound</OPTION>
<OPTION VALUE="SZL">SZL - Swazi Lilangeni</OPTION>
<OPTION VALUE="THB">THB - Thai Baht</OPTION>
<OPTION VALUE="TJS">TJS - Tajikistani Somoni</OPTION>
<OPTION VALUE="TMT">TMT - Turkmenistani Manat</OPTION>
<OPTION VALUE="TND">TND - Tunisian Dinar</OPTION>
<OPTION VALUE="TOP">TOP - Tongan Pa'anga</OPTION>
<OPTION VALUE="TRY">TRY - Turkish Lira</OPTION>
<OPTION VALUE="TTD">TTD - Trinidadian Dollar</OPTION>
<OPTION VALUE="TVD">TVD - Tuvaluan Dollar</OPTION>
<OPTION VALUE="TWD">TWD - Taiwan New Dollar</OPTION>
<OPTION VALUE="TZS">TZS - Tanzanian Shilling</OPTION>
<OPTION VALUE="UAH">UAH - Ukrainian Hryvna</OPTION>
<OPTION VALUE="UGX">UGX - Ugandan Shilling</OPTION>
<OPTION VALUE="USD">USD - US Dollar</OPTION>
<OPTION VALUE="UYU">UYU - Uruguayan Peso</OPTION>
<OPTION VALUE="UZS">UZS - Uzbekistani Som</OPTION>
<OPTION VALUE="VEF">VEF - Venezuelan Bolivar Fuerte</OPTION>
<OPTION VALUE="VND">VND - Vietnamese Dong</OPTION>
<OPTION VALUE="VUV">VUV - Ni-Vanuatu Vatu</OPTION>
<OPTION VALUE="WST">WST - Samoan Tala</OPTION>
<OPTION VALUE="XAF">XAF - Central African CFA Franc BEAC</OPTION>
<OPTION VALUE="XAG">XAG - Silver Ounce</OPTION>
<OPTION VALUE="XAU">XAU - Gold Ounce</OPTION>
<OPTION VALUE="XCD">XCD - East Caribbean Dollar</OPTION>
<OPTION VALUE="XDR">XDR - IMF Special Drawing Rights</OPTION>
<OPTION VALUE="XOF">XOF - CFA Franc</OPTION>
<OPTION VALUE="XPD">XPD - Palladium Ounce</OPTION>
<OPTION VALUE="XPF">XPF - CFP Franc</OPTION>
<OPTION VALUE="XPT">XPT - Platinum Ounce</OPTION>
<OPTION VALUE="YER">YER - Yemeni Rial</OPTION>
<OPTION VALUE="ZAR">ZAR - South African Rand</OPTION>
<OPTION VALUE="ZMK">ZMK - Zambian Kwacha</OPTION>
<OPTION VALUE="ZWD">ZWD - Zimbabwean Dollar</OPTION>
    </SELECT>

    <!XERC-UCC1-P1.6-R2>

   Scroll down to see more currencies

    <!XERC-UCC1-P3.2-R1>
    <INPUT VALUE="Perform Currency Conversion" type=submit onClick="save()">

    <input type="button" value="Set Default Conversion" onClick="set(); window.location.reload();">

    Universal Currency Converter under license from XE.com. Terms of Use

A: You should extract the scripts into a separate file when using manifest v. 2. See Chrome extension documents on Google sites for more


text:
Q: Google gsutil auth without prompt I want to use gsutil inside a Docker container. I have created an O2Auth Service Account JSON file.
How can I setup gsutil auth to use the JSON config file and execute commands without prompting?
Currently I get something like this:
$ gsutil config -e
It looks like you are trying to run "/.../google-cloud-sdk/bin/bootstrapping/gsutil.py config".
The "config" command is no longer needed with the Cloud SDK.
To authenticate, run: gcloud auth login
Really run this command? (y/N) y
This command will create a boto config file at /.../.boto
containing your credentials, based on your responses to the following questions.
What is the full path to your private key file?

What command/parameters/setup do I have to use to circumstance prompts?

A: Solved this issue by executing:
gcloud auth activate-service-account --key-file=/opt/gcloud/auth.json

The whole example and finished container can be found here: blacklabelops/gcloud

A: If you want gsutil only and bypass the prompt you can do it easily with an expect script:
#!/usr/bin/expect
spawn gsutil config -e
expect "What is the full path to your private key file?" { send "/path/your.key\r" }
expect "Would you like gsutil to change the file permissions for you? (y/N)" { send "y\r" }
expect "What is your project-id?" { send "your-projet-42\r" }
interact

A: The -o Credentials:gs_service_key_file=<path to JSON file> does the good work, using the boto configuration override parameters as documented at https://cloud.google.com/storage/docs/gsutil/addlhelp/TopLevelCommandLineOptions
$ gsutil -v
gsutil version: 4.57
$ gsutil -o Credentials:gs_service_key_file=key.json ls -al gs://bucket/filename
79948  2021-05-24T02:12:25Z  gs://bucket/filename#1111111145678393  metageneration=2

A: The above solutions don't work for me.
What solved this problem for me is the following

*

*Set the gs_service_key_file in the [Credentials] section of the boto config file (see here)

*Activate your service account with gcloud auth activate-service-account

*Set your default project in gcloud config
Dockerfile snipped:
ENV GOOGLE_APPLICATION_CREDENTIALS /.gcp/your_service_account_key.json
ENV GOOGLE_PROJECT_ID your-project-id

RUN echo '[Credentials]\ngs_service_key_file = /.gcp/your_service_account_key.json' \
    > /etc/boto.cfg
RUN mkdir /.gcp
COPY your_service_account_key.json $GOOGLE_APPLICATION_CREDENTIALS

RUN gcloud auth activate-service-account --key-file=$GOOGLE_APPLICATION_CREDENTIALS --project $GOOGLE_PROJECT_ID
RUN gcloud config set project $GOOGLE_PROJECT_ID

A: using only gsutil:
first run this command to configure the authentication manually
gsutil config -a

This will create /root/.boto file with the needed credentials.
Copy that path/file into your docker image.
gsutil will now work with those credentials.


text:
Q: Count Positive Consecutive Elements in Dataframe Question
Is there a way to count elements along an axis in a dataframe that conform to a condition?
Background
I am trying count the consecutive positive digits left to right along the horizontal axis (axis=1).  For example, row zero would result in 0 because the row starts with a negative number, while row one would result in 2 as there are two consecutive positive numbers. Row two would result in 3 and so on.
I've tried looping over it and applying methods, but I am at a loss.
Code
df = pd.DataFrame(np.random.randn(5, 5))

df

            0           1          2           3           4
0   -1.017333   -0.322464   0.635497    0.248172    1.567705
1   0.038626    0.335656    -1.374040   0.273872    1.613521
2   1.655696    1.456255    0.051992    1.559657    -0.256284
3   -0.776232   -0.386942   0.810013    -0.054174   0.696907
4   -0.250789   -0.135062   1.285705    -0.326607   -1.363189

binary = np.where(df < 0, 0, 1)
binary
array([[0, 0, 1, 1, 1],
       [1, 1, 0, 1, 1],
       [1, 1, 1, 1, 0],
       [0, 0, 1, 0, 1],
       [0, 0, 1, 0, 0]])

A: Here's a similar approach in Pandas
In [792]: df_p = df > 0

In [793]: df_p
Out[793]:
       0      1      2      3      4
0  False  False   True   True   True
1   True   True  False   True   True
2   True   True   True   True  False
3  False  False   True  False   True
4  False  False   True  False  False

In [794]: df_p['0'] * (df_p < df_p.shift(1, axis=1)).idxmax(axis=1).astype(int)
Out[794]:
0    0
1    2
2    4
3    0
4    0
dtype: int32

A: Here's one approach -
def count_pos_consec_elems(a):
    count = (a[:,1:] < a[:,:-1]).argmax(1)+1
    count[a[:,0] < 1] = 0
    count[a.all(1)] = a.shape[1]
    return count

Sample run -
In [145]: df
Out[145]:
          0         1         2         3         4
0  0.602198 -0.899124 -1.104486 -0.106802 -0.092505
1  0.012199 -1.415231  0.604574 -0.133460 -0.264506
2 -0.878637  1.607330 -0.950801 -0.594610 -0.718909
3  1.200000  1.200000  1.200000  1.200000  1.200000
4  1.434637  0.500000  0.421560 -1.001847 -0.980985

In [146]: binary = df.values > 0

In [147]: count_pos_consec_elems(binary)
Out[147]: array([1, 1, 0, 5, 3])


text:
Q: Routing in Reactjs App running with Tornado webserver doesn't work I am going to run a Reactjs app by Tornado (Python) webserver.
The routing system in Reactjs does not work.
For example:
https://localhost/        (Works!)
https://localhost/login   (Error 404!)

It seems the error comes from Tornado.
The following is the main files:
app.py:
  return tornado.web.Application([
    (r"/subscription", SubscriptionHandler),
    (r"/user/authenticate", AuthenticateHandler),
    (r"/user/register", RegistrationHandler),
    (r"/static/js/(.*)", tornado.web.StaticFileHandler, {"path": js_root}),
    (r"/static/css/(.*)", tornado.web.StaticFileHandler, {"path": css_root}),
    (r"/static/lib/(.*)", tornado.web.StaticFileHandler, {"path": node_modules}),
    (r"/(.*)", tornado.web.StaticFileHandler, {"path": widget_root, "default_filename": "index.html"})
], cookie_secret="1234567890")

App.js:
render() {
    return(
      <BrowserRouter>
        <Switch>
          <Route path="/" component={Profile} exact/>
          <Route path="/login" component={Login} exact/>
          <Route path="/signup" component={Signup} exact/>
          <Route path="/subscription" component={Subscription} exact/>
          <Route path="/payment" component={PaymentMethod} exact/>
          <Route component={Error}/>
        </Switch>
      </BrowserRouter>
    )
  }

A: Actually, I found out the what issue is. Instead of using <BrowserRouter> tag I used <HashRouter> and it is solved


text:
Q: How to check free disk space before file creation Suppose I need to create a file and before that I need to check size of available disk space for that operation.
Maybe java.io.File.createNewFile() will throw a IOException when there is not enough free space?
What would be the best approach?

A:
In java 1.6

*

*public long getTotalSpace()

*public long getFreeSpace()

Check this document

In java 1.7

*

*getTotalSpace()

*getUnallocatedSpace()

*getUsableSpace()

Check this document

In java 8

*

*getFreeSpace()

*getUsableSpace()

Check this document
Please check this Example if you need some help for code
Edit: I got this intresting bug while searching for your problem.
      Please have a look at this.PrintWriter does not throw IOException for full floppy disk

A: You can use this to check available space.
http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getFreeSpace%28%29
But deal with excception is not a bad idea, in most case I assume that your free space on the disk will be ok

A: in simple you can check like this.
   long freeSpace = new File("d:/").getFreeSpace(); //Here I am checking my d drive free space.


text:
Q: How can I define a function in C with + (not as a character) in its arguments? I want to define function calc in the way :
calc(num1,num2,+)

returns num1 + num2

A: You can't do that with functions but you can write a function-like macro:
#define calc(a,b,op) ( (a) op (b) )

Examples:
#include <stdio.h>

#define calc(a,b,op) ( (a) op (b) )

int main()
{
  printf("%d\n", calc(1,1,+));
  printf("%d\n", calc(1,1,-));
}

More proper and type safe program design would however be to use function pointer templates instead:
#include <stdio.h>

typedef int opfunc_t (int a, int b);

int calc(int a, int b, opfunc_t* op) { return op(a,b); }
int add (int a, int b) { return a + b; }
int sub (int a, int b) { return a - b; }

int main()
{
  printf("%d\n", calc(1,1,add));
  printf("%d\n", calc(1,1,sub));
}

The latter example is generally the preferred way.


text:
Q: Promisify Socket.IO / EventEmitter I am a bit surprised by the fact that I don't find much when googling for Promisify Socket.IO. Is it that uncommon?
I also had troubles to promisify it myself:
Promise.promisifyAll(io)
io.onceAsync('connect')
.then((socket) => ...)
.catch((err) => console.log(error))

This always triggers the error case, I assume because .once is a callback with only one argument, where Promises expect the first one to be the error. Any idea how to deal with these kind of things?

A: I can think of several reasons why promises aren't a good fit with socket.io and EventEmitter interfaces in general:

*

*For the most part, socket.io is an event driven interface and promises do not align architecturally with events that can occur more than once (since a promise is a one-shot device).  Yes, you can use a promise for .connect(), but not for incoming messages.  So, most people (myself included) probably don't think it makes sense to have half an interface using promises and the other half using event handlers.  Likely better to use one model for the whole API.

*Promise.promisifyAll() requires node.js style async callbacks (with error value as the first argument and data as the second argument) and that isn't what any of the socket.io event handler callbacks use.  To make promises work with something like the connect event you'd have to write your own custom promsification which is likely more work than just using the event handler it is written for.
An exception to the above might be if you are trying to coordinate the next occurrence of an event with other async events (something that isn't usually done) in which case promises might be useful for the coordination.  As an example, supposed you wanted to know when three separate asynchronous operations were all complete, one of which was the next occurrence of a socket.io event.  Then, it might make sense to manually promisify that event so you could use promises to coordinate your multiple async operations.
But for normal socket.io usage, promises just aren't a good architectural fit.  Similarly, you wouldn't typically use promises for a click handler in a web page.

FYI, if you want to promisify just the connect operation, you could do that manually like this:
io.connectAsync = function(url, options) {
    return new Promise(function(resolve, reject) {
        io.connect(url, options);
        io.once('connect', function(socket) {
            resolve(socket);
        });
        io.once('connect_error', function() {
            reject(new Error('connect_error'));
        });
        io.once('connect_timeout', function() {
            reject(new Error('connect_timeout'));
        });
    });
}

io.connectAsync().then(function(socket) {
    // connected here
    socket.on('someMsg', function() {
       // process message here
    });
}, function(err) {
    // error connecting here
});


text:
Q: For custom report types with one-to-many object relationship, how to filter *after* join (NB: As per comments, this is specifically a technical question around Salesforce reporting capabilities.)
Reports using the standard report type "Opportunities with Products" will include Opportunities that have no related Products. But the report can be filtered on Products fields and then only the opportunities with products matching that filter are included in the result.  You can even filter a Products field equals "" and the report will list all the Opportunities with no Products.
This means (in a relational database sense) that Opportunities are being left-joined with Products and then filters are being applied.
I want to do something similar with a custom Report Type and so far have been unable.
If I create a new Report Type with primary object Opportunities object and related object Products I have two options:

*

*"Each Opportunities record must have at least one related Products record" => resulting reports will not show Opportunities if there's no related Product at all (unlike the standard report).  In a relational database sense, this is an inner join not the desired left join.

*"Opportunities records may or may not have related Products records" => in resulting reports if I put a filter on Products fields then every Opportunities record is still included in the report (unlike the standard report).  In a relational database sense, Opportunities are being left-joined with the pre-filtered Products result.
How do I make a custom Report Type that will show me all Opportunities records but let me naturally apply a simple Products field post-filter to the joined result, as per the standard report?