text:
Q: React AuthContext doesn't store data in LocalStorage I'm trying to create an authentification in a mern project with Context and I followed a tutorial on Freecodecamp.
The problem is I can't inject data in LocalStorage.
The data is sent to the backend, but nothing is stored in LS.
My App.js
import React, { useState } from "react";
import { Navigate, Router, Routes, Route } from "react-router-dom";

// Pages
import {
  Home,
  Dashboard,
  MembersPage,
  ProfilePage,
  CreatePost,
  OnePost,
} from "./Pages/index";

export const AuthContext = React.createContext();
const initialState = {
  token: null,
  userId: null,
  isAuthenticated: false,
};
const reducer = (state, action) => {
  switch (action.type) {
    case "LOGIN":
      localStorage.setItem("token", JSON.stringify(action.payload.token));
      localStorage.setItem("userId", JSON.stringify(action.payload.userId));
      localStorage.setItem(
        "firstName",
        JSON.stringify(action.payload.firstName)
      );
      localStorage.setItem("lastName", JSON.stringify(action.payload.lastName));
      localStorage.setItem("email", JSON.stringify(action.payload.email));
      localStorage.setItem(
        "isAuthenticated",
        JSON.stringify(action.payload.isAuthenticated)
      );
      return {
        ...state,
        token: action.payload.token,
        userId: action.payload.user,
        isAuthenticated: true,
      };
    case "LOGOUT":
      localStorage.clear();
      return {
        ...state,
        token: null,
        userId: null,
        isAuthenticated: false,
      };
    default:
      return state;
  }
};

function App() {
  const [state, dispatch] = React.useReducer(reducer, initialState);

  return (
    <AuthContext.Provider
      value={{
        state,
        dispatch,
      }}
    >
      <Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="/dashboard" exact element={<Dashboard />} />
        <Route path="/profile" exact element={<ProfilePage />} />
        <Route path="/members" exact element={<MembersPage />} />
        <Route path="/posts" exact element={<CreatePost />} />
        <Route path="/posts/:id" exact element={<OnePost />} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </AuthContext.Provider>
  );
}
export default App;

The Login.jsx:
const Login = () => {
  const navigate = useNavigate();
  const { dispatch } = React.useContext(AuthContext);
  const initialState = {
    email: "",
    password: "",
    isSubmitting: false,
    errorMessage: null,
  };
  const [data, setData] = React.useState(initialState);

  const handleInputChange = (event) => {
    setData({
      ...data,
      [event.target.name]: event.target.value,
    });
  };
  const handleLogin = (event) => {
    event.preventDefault();
    setData({
      ...data,
      isSubmitting: true,
      errorMessage: null,
    });
    axios({
      method: "post",
      headers: { "Access-Control-Allow-Origin": "*" },
      url: "http://localhost:8080/home/login",
      data: {
        email: data.email,
        password: data.password,
      },
    })
      .then((res) => {
        navigate("/dashboard");
        if (res.ok) {
          return res.json();
        }
        throw res;
      })
      .then((resJson) => {
        dispatch({
          type: "LOGIN",
          payload: resJson,
        });
      })
      .catch((error) => {
        console.log(error);
        setData({
          ...data,
          isSubmitting: false,
          errorMessage: error.message || error.statusText,
        });
      });
  };

  return (
          <Box
            component="form"
            onSubmit={handleLogin}
            noValidate
          >

              Email Address
              <input
                type="text"
                value={data.email}
                onChange={handleInputChange}
                name="email"
                id="email"
              />

              Password
              <input
                type="password"
                value={data.password}
                onChange={handleInputChange}
                name="password"
                id="password"
              />

            {data.errorMessage && (
              {data.errorMessage}
            )}

            <button disabled={data.isSubmitting}>
              {data.isSubmitting ? "Loading..." : "Login"}
            </button>
            <Grid container></Grid>
          </Box>
  );
};

export default Login;

I have some trouble understanding React Context, but I followed several tutorials and there is always something wrong..
I had created an authentication in another way, but I had a bug to retrieve userId (at the first connection it was "undefined", defined after a page refresh, but userId wasn't sent to the back),now I changed the auth, but nothing is injected in LS...
Can anyone help me, please?
I've been blocking on it for a long time and I don't have anymore courage to completely change the project..


text:
Q: Solution Check for Determinant
Solution is 4.
Original matrix is simply [v1;v2;v3;v4]. It forms an identity matrix. Hence the only alteration of the determinant comes from row 1 operation where v1 is multiplied by 2. Then the determinant will also be multiplied by two so 2*2 =4.
We ignore the rest of row operations since they have no effect on the determinant.
Is this line of reasoning correct?

A: We have
$$\begin{vmatrix}2v_1\\3v_1+4v_2\\v_2+v_3\\v_1+2v_4\end{vmatrix}=2\begin{vmatrix}v_1\\3v_1+4v_2\\v_2+v_3\\v_1+2v_4\end{vmatrix}=2\begin{vmatrix}v_1\\4v_2\\v_2+v_3\\2v_4\end{vmatrix}=16\begin{vmatrix}v_1\\v_2\\v_2+v_3\\v_4\end{vmatrix}=16\begin{vmatrix}v_1\\v_2\\v_3\\v_4\end{vmatrix}=32$$
To check we can try with
$$\begin{vmatrix}2&0&0&0\\0&1&0&0\\0&0&1&0\\0&0&0&1\end{vmatrix}=2$$
and
$$\begin{vmatrix}2&0&0&0\\3&4&0&0\\0&1&1&0\\1&0&0&2\end{vmatrix}=32$$

A: Note that:
$$\begin{align}|A|=\begin{vmatrix}v_1\\v_2\\v_3\\v_4\end{vmatrix}&=2 \Rightarrow \\
\begin{vmatrix}2v_1\\4v_2\\v_3\\2v_4\end{vmatrix}&=32 \ \ \ \ \ \stackrel{\frac32R_1+R_2\to R_2\\ \frac14R_2+R_3\to R_3\\ \frac12R_1+R_4\to R_4}{\Rightarrow} \\
\begin{vmatrix}2v_1\\3v_1+4v_2\\v_2+v_3\\v_1+2v_4\end{vmatrix}&=32.\end{align}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: driver.findelement values are changing every time I'm trying to download the job log from maestro tool. Every time the driver.findelement values are changing. Can some one please help me with solution.
Example 1) driver.find_element_by_css_selector('#AjaxTable11851_t1 > tbody > tr.tvg_table_row_stripe0 > td:nth-child(1) > input[type=checkbox]').click()
Example 2) driver.find_element_by_css_selector('#AjaxTable11859_t1 > tbody > tr.tvg_table_row_stripe0 > td:nth-child(1) > input[type=checkbox]').click()

A: One way to create a single CSS selector would be the below
[id^=AjaxTable] > tbody > tr.tvg_table_row_stripe0 > td:nth-child(1) > input[type=checkbox]

... but, I can't tell for sure that it will find only the element you want without testing it on the page.


text:
Q: why the change event is not called? When I set the text of a input text with: $('#rif').val('bla bla bla');
Why if I add a .change() event on that input text is not called?

A: Because the .change() event is trigerred after user intervention on the input. You can trigger it manually though after changing the value of the input field:
$('#rif').val('bla bla bla').change();

A: If you change the value programatically the .change() event will not fire. If you are setting the value yourself from code you need to trigger the .change() event yourself too.
$('#rif').change();

or using the longhand form:
$('#rif').trigger('change');


text:
Q: Remove Special characters from file name I need to remove special characters from file, I tried following code based on this example, it is generating few errors. I need this code to work for asp.net webform based application.
using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test {
    public static void Main() {
        // your code goes here

        var file_name = GetValidFileName("this is)file<ame.txt");
        Console.WriteLine(file_name);
        private static string GetValidFileName(string fileName) {
            // remove any invalid character from the filename.
            return Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "");
        }
    }
}

Sample code on & output ideone.com

A: You have put private static string GetValidFileName in public static void Main() and in C# is not allowed. Just simple change the code as follow and it will work:
using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test {
    public static void Main() {
    // your code goes here

    var file_name = GetValidFileName("this is)file<ame.txt");
    Console.WriteLine(GetValidFileName(file_name));

    }
    private static string GetValidFileName(string fileName) {
        // remove any invalid character from the filename.
        String ret = Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "")
        return ret.Replace(" ", String.Empty);
    }
}

A: string newName = UploadFile.FileName.Replace("&", "and");

A: Try this:
Console.WriteLine("Type a File Name:");
char[ ] invalidChars = System.IO.Path.GetInvalidFileNameChars();

string? FileName = Console.ReadLine();
if( FileName != null )
{
   string OutputFileName="";

   for (int i = 0; i < FileName.Length; i++)
   {
      char c = FileName[i];

      if (! invalidChars.Contains(c))
      {
         OutputFileName += c;
      }
   }
   Console.WriteLine("Output :");
   Console.WriteLine(OutputFileName);
}


text:
Q: Send an Array through redirect PHP I'm trying to send an array to another page, such that when I get the array on the next page, only the array shows up and not the values. I then want to extract the values individually. I'm using the following code below. While this code works, on the redirect page, it returns 0=555928038&1=1694191&2=359564591&3=33280807&4=918458113 in the url. I don't want to see these values in the url. I want to see just the array and then I want to extract the values. What can I do to change this header redirect?
header('Location: twittercurlusershow.php?' . http_build_query($arrayoffollowers));

A: Store the array somewhere else (database, filesystem, session) along with a unique identifier. Attach the identifier to the URL. On the target page, restore the array from the identifier.
Alternatively, serialize and base64-encode the array, add it to the url as a request variable and on the target page, base64-decode and unserialize it. This is only feasible for small arrays because the maximum length of URLs a Browser can handle might be as low as 2083 bytes.

A: You could use the $_SESSION variable to store the array on your original page and then call it up from twittercurlusershow.php.
Here is a tutorial on using $_SESSION.


text:
Q: call external js function within razor I have this code:
Html.RequiresJs("~/Scripts/site/scripts.app.js", 5);
@{

if (String.IsNullOrEmpty(stringQueryElement) && !upcoming.Any())
    {
        <script type="text/javascript">
            X();
        </script>
    }
}

Inside scripts.app.js file I have a function X() which I want to call out when my if statement is true. How I call it? Because the syntax I have now does not work.
Did some debugging and I can see that IF statement works correctly. The only question is how do I call my function that is stored in scripts.app.js.
Thanks for help in advance.

A: As your comment stated, your scripts.app.js is injected just before </body>. This means the script's functions are available after it is evaluated by the browser. Because you try to run your script before that has happened, it won't detect your X() function.
Use the document ready to make sure all scripts are evaluated:
if (String.IsNullOrEmpty(stringQueryElement) && !upcoming.Any())
    {
        <script type="text/javascript">
            $(function() {
                X();
            });
        </script>
    }
}

(Assuming you're using jQuery)


text:
Q: Can std::stoi verify if the value of digit exceeds range of base? I'm using std::stoi in following manner
int ConvertToInt( const std::string& aVal )
{
    int lVal = std::stoi( aVal, nullptr, 0 );
    return lVal;
}

Third argument in std::stoi was provided as 0 to convert automatically both DEC and HEX values.
I also use try-catch structure to catch std::invalid_argument, std::out_of_range and ( ... ) althought when I provide number as 0xgg no exception is thrown and the number is converted to 0 which is not my intention.
Is it possbile to catch digits, which are out of range and throw some exception ?

A: std::stoi parses the string until an invalid character is encountered, which is interpreted to be the end of the integer.

Is it possbile to catch digits, which are out of range and throw some exception ?

Yes. You can use the pos argument. After the conversion, the pointed integer will contain the index of the first unconverted character. If the *pos is not equal to the size of the input, then there are unconverted characters, which must have not been valid. You can throw an exception in such case.


text:
Q: Cross browser xml pretty printing alternative to identity transform While developing a Single Page Application, I'm generating some XML that I'd like to be able to read in-browser.
While developing, I'm usually working in whatever latest version of Safari and it all works great, but when I wanted to show some progress to someone, and they were using Firefox, the generated XML was all on one line.
I picked the identity transform to pretty print based on research I did because it seemed like the cleanest solution to my problem, but now it doesn't seem to work on Gecko based browsers.

The code I'm using in Typescript is:
private prettifyXml(unformattedDocument:XMLDocument) : XMLDocument {

    let identityTransformSheet = '\<' +
        'xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\
            <xsl:output omit-xml-declaration="yes" indent="yes"/>\
            <xsl:template match="node()|@*">\
                <xsl:copy>\
                    <xsl:apply-templates select="node()|@*"/>\
                </xsl:copy>\
            </xsl:template>\
        </xsl:stylesheet>';

    let parser = new DOMParser();
    let processor = new XSLTProcessor();
    processor.importStylesheet(parser.parseFromString(identityTransformSheet, 'text/xml'));
    let result = processor.transformToDocument(unformattedDocument);
    return result;
}

And this is used:
    // `xml` holds a document created by DOMParser and filled with a serialized representation of the model.

    let result = (new XMLSerializer()).serializeToString(this.prettifyXml(xml));
    this.xmlEquivalent(result);
    return result;

This works fine in Safari but seems to do nothing in Firefox. Is there a way to make this functionality cross browser or is there perhaps a better way to do it?
(I'm hoping for a standards compliant solution without adding another library)

A: As you asked for alternatives, the post you linked to discussing the use of the identity transformation proposed by Dimitre Novatchev also has a comment suggesting the use of the XPath visualizer stylesheet instead of the identity transformation. So to demonstrate that that is possible I made some adaptions to the XSLT and CSS and Javascript to allow it to be used inside another HTML document instead of creating a separate, complete HTML document, the result is https://martin-honnen.github.io/js/2017/pretty-print/pretty-print-test1.html which does work for me in on Windows 10 with current versions of Edge, Chrome and Firefox. I don't have Safari to test. It will certainly not work as written with IE as I have solely used the XSLTProcessor API in Javascript first introduced in Mozilla and and now be supported in anything but IE; if you need IE support then you should be able to have that by using IE specific code to run the XSLT transformation.
Here is the code of the HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Testing a proof of concept of pretty-printing of an XML DOM tree as a HTML collapsible table structure</title>
        <link rel="stylesheet" type="text/css" href="pretty-print1.css"/>

Testing a proof of concept of pretty-printing of an XML DOM tree as a HTML collapsible table structure

Example result

the XSLT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="html"/>
  <xsl:template match="/">

        <xsl:apply-templates/>

  </xsl:template>

  <xsl:template match="*">

      <

      <xsl:variable name="class" select="'elemname'"/>

        <xsl:value-of select="name(.)"/>

      <xsl:call-template name="findNamespace"/>

      <xsl:apply-templates select="@*"/>
      />

  </xsl:template>

  <xsl:template match="*[text()]">

    <xsl:variable name="class" select="'elemname'"/>

      <

        <xsl:value-of select="name(.)"/>

      <xsl:call-template name="findNamespace"/>

      <xsl:apply-templates select="@*"/>
      >

        <xsl:apply-templates/>

      </

        <xsl:value-of select="name(.)"/>

      >

  </xsl:template>

  <xsl:template match="*[* or processing-instruction() or comment()
                         or string-length(text()) > 50]" priority="10">

    <xsl:variable name="class" select="'elemname'"/>

          -

          <

            <xsl:value-of select="name(.)"/>

          <xsl:call-template name="findNamespace"/>
          <xsl:apply-templates select="@*"/>
          >

            <xsl:apply-templates/>

          </

            <xsl:value-of select="name(.)"/>

          >

  </xsl:template>
  <xsl:template match="@*">

    <xsl:variable name="vPos" select="position()"/>

    <xsl:variable name="vPref" select="substring-before(name(), ':')"/>

    <xsl:if test="$vPref
               and
                  not(../@*[position() < $vPos]
                           [substring-before(name(), ':')
                           = $vPref]
                      )">
      <xsl:call-template name="findNamespace"/>
    </xsl:if>

    <xsl:variable name="class" select="'attrname'"/>

    <xsl:variable name="class2" select="'markup'"/>

    <xsl:variable name="class3" select="'attrvalue'"/>

    <xsl:text> </xsl:text>

      <xsl:value-of select="name(.)"/>

    ="

      <xsl:call-template name="replaceAmpersands">
        <xsl:with-param name="vString" select="string(.)"/>
      </xsl:call-template>

    "
  </xsl:template>

  <xsl:template match="text()">

    <xsl:variable name="class" select="'text'"/>

      <xsl:call-template name="replaceAmpersands">
        <xsl:with-param name="vString" select="string(.)"/>
      </xsl:call-template>

  </xsl:template>

  <xsl:template match="processing-instruction()">

    <xsl:variable name="class" select="'indent pi'"/>

      <?
      <xsl:value-of select="name(.)"/>
      <xsl:text> </xsl:text>
      <xsl:value-of select="."/>
?>

  </xsl:template>

  <xsl:template match="processing-instruction()[string-length(.) > 50]">

    <xsl:variable name="class" select="'pi'"/>

    <xsl:variable name="class2" select="'indent expander-content'"/>

          -

          <?
          <xsl:value-of select="name(.)"/>

            <xsl:value-of select="."/>

          <xsl:text>?></xsl:text>

  </xsl:template>

  <xsl:template match="comment()">

    <xsl:variable name="class" select="'comment indent'"/>

      <!--
      <xsl:value-of select="."/>
      -->

  </xsl:template>

  <xsl:template match="comment()[string-length(.) > 50]">

    <xsl:variable name="class" select="'comment'"/>

    <xsl:variable name="class2" select="'indent expander-content'"/>

          -

          <!--

            <xsl:value-of select="."/>

          -->

  </xsl:template>

  <xsl:template name="findNamespace">

    <xsl:variable name="vName" select="substring-before(name(), ':')"/>
    <xsl:variable name="vUri" select="namespace-uri(.)"/>

    <xsl:variable name="vAncestNamespace">
      <xsl:call-template name="findAncNamespace">
        <xsl:with-param name="pName" select="$vName"/>
        <xsl:with-param name="pUri" select="$vUri"/>
      </xsl:call-template>
    </xsl:variable>

    <xsl:if test="not(number($vAncestNamespace))">
      <xsl:if test="namespace-uri()
                  or
                    not(generate-id()
                       =
                        generate-id(../@*[name()
                                         =
                                          name(current())]
                                    )
                        )">
        <xsl:if test="parent::* or namespace-uri() or contains(name(), ':')">
          <xsl:text> </xsl:text>

            <xsl:value-of select="'xmlns'"/>
            <xsl:if test="contains(name(), ':')">
              <xsl:value-of select="concat(':', $vName)"/>
            </xsl:if>

          ="

            <xsl:value-of select="namespace-uri()"/>

          "
        </xsl:if>
      </xsl:if>
    </xsl:if>
  </xsl:template>

  <xsl:template name="findAncNamespace">
    <xsl:param name="pNode" select="."/>
    <xsl:param name="pName" select="substring-before(name(), ':')"/>
    <xsl:param name="pUri" select="namespace-uri(.)"/>

     <xsl:choose>
      <xsl:when test="not($pNode/parent::*)
                     and not($pName) and not($pUri)">1</xsl:when>
      <xsl:when test="not($pNode/parent::*)">0</xsl:when>
      <xsl:otherwise>
        <xsl:variable name="vSamePrefs"
        select="number($pName
                      = substring-before(name($pNode/..), ':')
                      )"/>

        <xsl:variable name="vSameUris"
         select="number($pUri  = namespace-uri($pNode/..))"/>

        <xsl:choose>
          <xsl:when test="$vSamePrefs and not($vSameUris)">0</xsl:when>
          <xsl:when test="not($vSamePrefs)">
            <xsl:call-template name="findAncNamespace">
              <xsl:with-param name="pNode" select="$pNode/.."/>
              <xsl:with-param name="pName" select="$pName"/>
              <xsl:with-param name="pUri" select="$pUri"/>
            </xsl:call-template>
          </xsl:when>
           <xsl:otherwise>1</xsl:otherwise>
        </xsl:choose>
      </xsl:otherwise>
    </xsl:choose>

  </xsl:template>

  <xsl:template name="replaceAmpersands">
    <xsl:param name="vString"/>

   <xsl:variable name="vAmp">&</xsl:variable>

   <xsl:choose>
   <xsl:when test="contains($vString, $vAmp)">
     <xsl:value-of select="substring-before($vString, $vAmp)"/>
     <xsl:value-of select="concat($vAmp, 'amp;')"/>
     <xsl:call-template name="replaceAmpersands">
       <xsl:with-param name="vString"
       select="substring-after($vString, $vAmp)"/>
     </xsl:call-template>
   </xsl:when>
   <xsl:otherwise>
     <xsl:value-of select="$vString"/>
   </xsl:otherwise>
   </xsl:choose>

  </xsl:template>
</xsl:stylesheet>

Take the CSS from https://martin-honnen.github.io/js/2017/pretty-print/pretty-print1.css, it is all meant anyway as a proof of concept, not as polished, finished code.
These days I would rather suggest to a worked out solution like https://github.com/pgfearo/xmlspectrum that might work in the browser with the help of Saxon-CE or Saxon-JS.


text:
Q: Initializing jagged arrays with Lists inside by a for loop I get NullReferenceException when I want to add item to my elements in jagged array.
public List<int>[][] Map;

void Start()
{
    Map = new List<int>[60][];
    for(byte x = 0; x < 60 ; x++)
    {
        Map[x] = new List<int>[60];
        // initialization of rows
    }

    Map [23] [34].Add (21);
}

A: You have a jagged array which each of its elements is a List<int>. You initialize the array but not the elements.
So when you call Add on an uninitialized element which is a List<int> you get the exception.
Map = new List<int>[60][];
for (int x = 0; x < 60; x++)
{
    Map[x] = new List<int>[60];

    for (int y = 0; y < 60; y++)
    {
        Map[x][y] = new List<int>(); // initializing elements
    }
    // initialization of rows
}

Map[23][34].Add(21);


text:
Q: AG-Grid - Show sort icon without reloading data I have an angular application and when I load my page the columns are not yet defined.
The columns are defined when I retrieve the data (which are already sorted).
So if I apply a state on my sorted column (after the data are initialized), the data are refreshed again and I want to avoid this.
Is there a solution to show the sort icon without AG-Grid refresh the data ?
To be more explicit, here is my angular code :
getRows(params: any): void {
  //retrieve my data
  this.myservice.getAll(params.currentPage, params.pageSize, params.sort).subscribe((data) => {
    //send my datas to AG-Grid
    params.successCallBack(data.results, data.totalItems);
    if (params.currentPage == 0 && this.firstLoad) {
      //my datas contain the columns definition
      this.initGrid(data.viewParams);
    }
  });
}

initGrid(viewParams: ViewParamsModel): void {
    this.firstLoad = false;
    this.dataGrid.setColumnDefs(viewParams.columns);

    //I try with this but it reloads my data
    this.gridColumnApi.applyColumnState({
         state: [
         {
            colId: 'name',
            sort: 'asc',
         }],
    });
}

A: When doing this.dataGrid.setColumnDefs(viewParams.columns)
add   sort: 'desc'/'asc'
columnDefs: [
    {
      field: 'Column1',
      sort: 'desc',   // <====== add this
    },


text:
Q: Returning a collection of pointers by value I have a library function that creates and returns (by value) a vector of pointers to some objects on the heap. This works well and good when I'm using c++ but now I need to export this function so that it can be linked with C and I'm confused on how to achieve this in a clean way.
My first naïve attempt was the following:
airport_t **listAiportsByCode(const char *code) {
    vector<airport_handle*> airports;
    // Fill up vector with pointer to airports on the heap ...
    airports.push_back(nullptr);
    airport_t** c_airports = airports.data();
    return c_airports;
}

which obviously won't work since the airports vector is stack allocated.
Do I need to allocate an array on the heap and simply document that the array needs to be deleted after use?
airport_t **listAiportsByIATA(const char *iata) {
    vector<airport_handle*> airports;
    // Fill up vector with airports ...
    airports.push_back(nullptr);
    airport_t* c_airports = new airport_t*[BUFFER];
    std::copy(airports.begin(), airports.end(), c_airports);
    return c_airports;
}

I'm used to programming in high level languages and this seems to mee as a too ugly design for such a trivial function.

A: It is quite ugly, but that is the C way of doing things.
You could either take your approach, or get an airport_t** as a parameter and have the client allocate memory for you.
You would only need to fill the client allocated memory, and return the number of elements inserted.
int listAiportsByIATA(const char *iata, airport_t **c_airports) {
    vector<airport_handle*> airports;
    // Fill up vector with airports ...
    airports.push_back(nullptr);
    std::copy(airports.begin(), airports.end(), c_airports);
    return airports.size();
}

this solution however will have another problem, the client will need to allocate enough memory for you to fill. So you probably want to add another check.

A: For dealing with the memory I think your only options are to allocate the array and have the client tidy it up or have the client allocate the array.
It also might be cleaner to not use a vector and write directly into the array?
Allocating array for the client:
airport_t **listAiportsByIATA(const char *iata) {

    airport_t** c_airports = new airport_t*[BUFFER];

    // Fill up vector with airports ...
    for (airport_t** airport = c_airports; airport < c_airports + BUFFER; ++airport) {
        *airport = nullptr;
    }

    return c_airports;
}

Client allocates array:
void listAiportsByIATA(const char *iata, airport_t ** c_airports, int maxSize) {

    // Fill up vector with airports ...
    for (airport_t** airport = c_airports; airport < c_airports + maxSize; ++airport) {
        *airport = nullptr;
    }

}


text:
Q: Sub aggregation scripting with parameters taken from parent aggregation Is there a way to use the key value of an aggregation bucket as a parameter in a sub-aggregation?
Having an index like:
{
    "id": 152,
    "description": "cool stuff",
    "datesWithTotal" : [
        {
            "date" : "2014-02-02T00:00:00",
            "total" : 47.2
        },
        {
            "date" : "2014-02-03T00:00:00",
            "total" : 51.2
        },
        {
            "date" : "2014-02-04T00:00:00",
            "total" : 56.4
        }
    ]
}

I would like to perform a date_histogram aggregation with a sub-aggregation which will perform some operation based on the current parentbucket.key value
{
    "aggs": {
        "histo": {
            "date_histogram": {
                "field": "datesWithTotal.date",
                "interval": "1d"
            },
            "aggs": {
                "script-test": {
                    "scripted_metric": {
                        "init_script": "_agg['sum'] = 0",
                        "map_script": "_agg.sum += (PARENTBUCKET.KEY == 'somevalue' ? 1 : 0)",
                        "combine_script": "return _agg.sum"
                    }
                }
            }
        }
    }
}

I've already used some scripts in this way but each one was not using anything from the parent, just plain integer parameters.

A: This is just an ideea. I've tested it quickly but, for whatever  reason, is not outputting what I thought it should. Maybe it gives you some further ideas or you can make it work in a way I haven't been able to so far:
{
  "aggs": {
    "histo": {
      "date_histogram": {
        "field": "datesWithTotal.date",
        "interval": "1d"
      },
      "aggs": {
        "doesIncludeDate": {
          "terms": {
            "script": "new Date(doc[\"datesWithTotal.date\"].value).format(\"yyyy-MM-dd\")",
            "valueType": "string",
            "include": {
              "pattern": "2014-02-04"
            }
          },
          "aggs": {
            "script-test": {
              "scripted_metric": {
                "init_script": "_agg['sum'] = 0",
                "map_script": "_agg.sum += 1",
                "combine_script": "return _agg.sum"
              }
            }
          }
        },
        "doesNotIncludeDate": {
          "terms": {
            "script": "new Date(doc[\"datesWithTotal.date\"].value).format(\"yyyy-MM-dd\")",
            "valueType": "string",
            "exclude": {
              "pattern": "2014-02-04"
            }
          },
          "aggs": {
            "script-test": {
              "scripted_metric": {
                "init_script": "_agg['sum'] = 0",
                "map_script": "_agg.sum += 0",
                "combine_script": "return _agg.sum"
              }
            }
          }
        }
      }
    }
  }
}

The idea is to use a terms aggregation with an include and another terms with an exclude to have buckets that match your parent bucket key or not. For those that match use your script with _agg.sum += 1 for the other use _agg.sum += 0.
Of course, all of this is for a very specific script you have: a date is X or not. If the script is more complex, it won't be useful. And I don't think you can access the parent key from a script (or I haven't found a way to do it).


text:
Q: Replacing strings in a file containing ${Some string in variable} in powershell I have text file which contains some keys of an hash table in the form of ${key}. I need to parse the text file and replace ${key} with it's value. Below is the code i am using
    #$config is the hashtable
   $document = Get-Content sample.txt
    foreach ($conf in $config.Keys) {
        [string]$match = '${' + $conf + '}'
        $document = $document.Replace($match, $($config.$conf))
        }
    }

I have tried below alternatives for $match string
[string]$match = "`${" + $conf + "}"
[string]$match='${'
$match+=$conf
$match+='}'

I even tried hard coding the string as $match='${BACKUP_FOLDER}' but in all the cases it does nothing. I have also tried -match to see if something matches but it always returns false.
I have confirmed that the text file contains several patterns of ${key} format and if i copy the output of $match and search in the file i can find the patterns. Could you please point out what's wrong. I am using Powershell V5.0
Sample input
$config=@{"BACKUP_DIR"="_Backup";"STAGING_DIR"="_Staging"}

Contents of sample.txt
Overwrites the contents of new installation with old installation
    Always use / as path seperator-->
    <!-- <rename path="" newName=""/> -->
    <!--
    ${BACKUP_DIR}
    rename-> rename file/directory in new installation

Output: ${BACKUP_DIR} should be replaced with _Backup

A: Looks like there're a couple of typos in the hashtable. Following is a complete solution you can save as script and run, or copy to console.
$document = @'
Overwrites the contents of new installation with old installation
    Always use / as path seperator-->
    <!-- <rename path="" newName=""/> -->
    <!--
    ${BACKUP_FOLDER}
    rename-> rename file/directory in new installation
'@

$config=@{"BACKUP_FOLDER"="_Backup";"STAGING_DIR"="_Staging"}

Write-Output "`n`nINPUT`n$document"

foreach ($conf in $config.Keys) {
        [string]$match = '${' + $conf + '}'
        $document = $document.Replace($match, $config.$conf)
}

Write-Output "`n`nOUTPUT`n$document"


text:
Q: How to fill Pandas index NaN's I have a Excel file with a index that is merged over several rows in Excel, and when I load it in pandas, it reads the first row as the index label, and the rest (the merged cells) is filled with NaNs. How can I loop over the index so that it fills the NaNs with the corresponding index?
EDIT: Image of excel removed by request. I don't have any specific code, but I can write an example.
import pandas as pd
df = pd.read_excel('myexcelfile.xlsx', header=1)
df.head()
                     Index-header               Month
0                          Index1                   1
1                           NaN                     2
2                           NaN                     3
3                           NaN                     4
4                           NaN                     5
5                           Index2                  1
6                           NaN                     2
...

A: Try this:
In [205]: df
Out[205]:
    Index-header  Month
0         Index1    1.0
1            NaN    2.0
2            NaN    3.0
3            NaN    4.0
4            NaN    5.0
5         Index2    1.0
6            NaN    2.0
...          NaN    NaN

In [206]: df['Index-header'] = df['Index-header'].fillna(method='pad')

In [207]: df
Out[207]:
    Index-header  Month
0         Index1    1.0
1         Index1    2.0
2         Index1    3.0
3         Index1    4.0
4         Index1    5.0
5         Index2    1.0
6         Index2    2.0
...       Index2    NaN

A: from StringIO import StringIO
import pandas as pd

txt = """Index1,1
,2
,3
Index2,1
,2
,3"""

df = pd.read_csv(StringIO(txt), header=None, index_col=0, names=['Month'])
df

df.set_index(df.index.to_series().ffill(), inplace=True)
df


text:
Q: ToList returns a list with an unique null element I'm running this LINQ code, but in the elements where the Options property should be an empty List, there is a List with one element, which is just 'null', any idea how to fix this?
 var metadata = from md in context.Metadata
                       join o in context.MetadataOptions on md.MetadataId equals o.MetadataId into op
                       from opts in op.DefaultIfEmpty()
                       group opts by md into ops
                       select new MetadataDTO
                       {
                           Enabled = ops.Key.Enabled,
                           Name = ops.Key.Name,
                           MetadataCategoryId = ops.Key.MetadataCategoryId,
                           MetadataId = ops.Key.MetadataId,
                           Id = ops.Key.Id,
                           Type = ops.Key.Type,
                           Options = ops.ToList()
                       };

Thanks!!


text:
Q: Bazel + QtCreator It seems, there is no "standard/official" way of opening Bazel (the build system used to build tensorflow applications) projects in QtCreator, but have anyone figured out any workaround?

A: Ok, I figured it out. At this fork of TensorFlow you can find a workaround of QtCreator support. The following features are tested and work:

*

*building project with (Ctrl+B)

*running with (Ctrl+R)

*text highlighting

*locator (Ctrl+L)

*code navigation (F2)

A: So I found some time to play with it and here is my early version of the Bazel support plugin for Qt Creator: https://bitbucket.org/knuckles/qtc-bazel-plugin/
Again, it's in early stage but it can be used to open a Bazel WORKSPACE, see targets and sources in the project explorer view, and build arbitrary targets.
It's still a WIP and lacks a few features, but feel free to give it a try - it may be enough for simple projects.

A: I know this is not what you're asking, but there is Bazel plugin for IntellijIdea: https://github.com/bazelbuild/intellij.


text:
Q: How to configure AspectJ with Load Time Weaving without Interface On my project, I currently use AspectJ (not just Spring AOP due to some limitation) with the weaving at the Compile Time. In order to speed up the development on Eclipse, I want to do the weaving at the Load Time. I succeed to do that but with one major constraint: using an interface for my service that contained some transactional methods. If I declare the service with its implementation instead of its interface, in the caller class, there is no weaving and so no transaction supported.
So if it is supported by AspectJ, how to configure AspectJ with Load Time Weaving without Interface ?
I created a little project that reproduce the issue:
The following test fail.
The following test succeed if :

*

*the injected service is declared with its interface instead of its implementation (i.e. replace "@Inject MyServiceImpl service" by "@Inject MyService service"), the test succeed.

*the weaving is executed during the compilation (the configuration, POM & Spring application context, is obviously different in this case). But my goal is to do the weaving at the Load-Time to avoid a weaving phase every time I save a Java file.

*Spring AOP (tx:annotation-driven mode="proxy"), that is a proxy-based solution, is used instead of AspectJ. But in this case, we encountered the self-invocation issue, i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.
aspectj-ltw/src/test/java/mycompany/aspectj_ltw/MyServiceImplTest.java
package mycompany.aspectj_ltw;

import static junit.framework.Assert.assertTrue;

import javax.inject.Inject;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" })
public class MyServiceImplTest {

    @Inject
    MyServiceImpl service;

    @Test
    public void shouldBeExecutedInTransaction() {
        assertTrue(this.service.isExecutedInTransaction());
    }
}

aspectj-ltw/src/main/java/mycompany/aspectj_ltw/MyService.java
package mycompany.aspectj_ltw;

public interface MyService {

    boolean isExecutedInTransaction();

}

aspectj-ltw/src/main/java/mycompany/aspectj_ltw/MyServiceImpl.java
package mycompany.aspectj_ltw;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Service
public class MyServiceImpl implements MyService {

    @Transactional
    public boolean isExecutedInTransaction() {
        return TransactionSynchronizationManager.isActualTransactionActive();
    }

}

aspectj-ltw/src/test/resources/META-INF/applicationContext.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:component-scan base-package="mycompany.aspectj_ltw" />

    <context:load-time-weaver aspectj-weaving="on" />
    <aop:config proxy-target-class="true"/>
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <tx:annotation-driven mode="aspectj"
        transaction-manager="transactionManager" proxy-target-class="true" />

    <bean class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" id="dataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:mem:mydb" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        id="transactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

aspectj-ltw/src/test/resources/META-INF/aop.xml
<!DOCTYPE aspectj PUBLIC
        "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
  <weaver options="-showWeaveInfo -debug -verbose -XmessageHandlerClass:org.springframework.aop.aspectj.AspectJWeaverMessageHandler">
        <include within="mycompany.aspectj_ltw..*"/>
  </weaver>
</aspectj>

aspectj-ltw\pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mycompany</groupId>
    <artifactId>aspectj-ltw</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>aspectj-ltw</name>

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.2.143</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>0.9.24</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>0.9.24</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <forkMode>always</forkMode>
                    <argLine>
                        -javaagent:C:/maven-2_local_repo/org/springframework/spring-instrument/3.0.5.RELEASE/spring-instrument-3.0.5.RELEASE.jar
                    </argLine>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

VM arguments to run the test:
-javaagent:C:/maven-2_local_repo/org/springframework/spring-instrument/3.0.5.RELEASE/spring-instrument-3.0.5.RELEASE.jar

A: If I'm not mistaken, the issue here is not due to AspectJ, but rather to the way things work in the precise JUnit use case. When running your test, the MyServiceImplTest class is loaded first, before the Spring context was created (you need the test class' annotations to get the appropriate runner and config locations), hence before any Spring AOP mechanism was leveraged. That is, at least, the explanation I came up with when I faced the very same situation a few months ago... Since the javaagent is there from the JVM startup on, one would have to fully read/understand the weaver's code to precisely explain why it fails here (I didn't :p).
So anyway, the MyServiceImplTest type, along with all its member's types, which are loaded with it - this goes for types in method signatures as well -, cannot be woven.
To work around this:

*

*either avoid using the woven types in the test class members and methods signature (e.g. using interfaces like you did)

*or add the AspectJ weaver to your javaagents (in addition to the spring-instrument one); with this, if I recall correctly, Spring should be able to get its AOP-based mechanisms to work properly:
-javaagent:/maven-2_local_repo/org/aspectj/aspectjweaver/1.7.0/aspectjweaver-1.7.0.jar -javaagent:/maven-2_local_repo/org/springframework/spring-instrument/3.0.5.RELEASE/spring-instrument-3.0.5.RELEASE.jar
Nota: in your META-INF/aop.xml, it may be necessary to add the -Xreweavable weaver option.

A: First of all , if you are using maven, set your pom.xml:
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.7</version>
    </dependency>

Then you have had to compile your code using the aspectj compiler.
This compiler generate an aop.xml file in META-INF/aop.xml
(I'm using eclipse sts)
After that, I want to run a Junit test.
So you have to set your VM args in the eclipse run configuration window:
 -javaagent:${ASPECTJ_WEAVER_1.7}\aspectjweaver-1.7.0.jar -javaagent:${SPRING_INSTRUMENT}\spring-instrument-3.1.2.RELEASE.jar
where ${ASPECTJ_WEAVER_1.7} ${SPRING_INSTRUMENT} are an environtment var. Use the var button to create these vars (is located at bottom right of the window). These vars target to the folders where the aspectjweaver-1.7.0.jar and spring-instrument-3.1.2.RELEASE.jar are located. Follow the asistant to make this. It's not difficult.
Take care that the previous javaagent lines haven't any invisible strange character or similar. It's sound strange but I had to rewrite several times the same line until eclipse said that this line is fine.
Then, you can run your Junit test.
The first you can see is aspectj runtime loading. Later you will see spring loading... and after that your test will run is haven't got any spring problem or similar.
This is a heavy process.
I hope this information can help you
Regards


text:
Q: What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming? In Map Reduce programming the reduce phase has shuffling, sorting and reduce as its sub-parts. Sorting is a costly affair.
What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

A: Let's revisit key phases of Mapreduce program.
The map phase is done by mappers. Mappers run on unsorted input key/values pairs. Each mapper emits zero, one, or multiple output key/value pairs for each input key/value pairs.
The combine phase is done by combiners. The combiner should combine key/value pairs with the same key. Each combiner may run zero, once, or multiple times.
The shuffle and sort phase is done by the framework. Data from all mappers are grouped by the key, split among reducers and sorted by the key. Each reducer obtains all values associated with the same key. The programmer may supply custom compare functions for sorting and a partitioner for data split.
The partitioner decides which reducer will get a particular key value pair.
The reducer obtains sorted key/[values list] pairs, sorted by the key. The value list contains all values with the same key produced by mappers. Each reducer emits zero, one or multiple output key/value pairs for each input key/value pair.
Have a look at this  javacodegeeks article by Maria Jurcovicova and mssqltips article by Datta for a better understanding
Below is the image from safaribooksonline article

A: Some of the data processing requirements doesn't need sort at all. Syncsort had made the sorting in Hadoop pluggable. Here is a nice blog from them on sorting. The process of moving the data from the mappers to the reducers is called shuffling, check this article for more information on the same.

A: I thought of just adding some points missing in above answers. This diagram taken from here clearly states the what's really going on.

If I state again the real purpose of

*

*Split: Improves the parallel processing by distributing the processing load across different nodes (Mappers), which would save the overall processing time.

*Combine: Shrinks the output of each Mapper. It would save the time spending for moving the data from one node to another.

*Sort (Shuffle & Sort): Makes it easy for the run-time to schedule (spawn/start) new reducers, where while going through the sorted item list, whenever the current key is different from the previous, it can spawn a new reducer.

A: First of all shuffling is the process of transfering data from the mappers to the reducers, so I think it is obvious that it is necessary for the reducers, since otherwise, they wouldn't be able to have any input (or input from every mapper). Shuffling can start even before the map phase has finished, to save some time. That's why you can see a reduce status greater than 0% (but less than 33%) when the map status is not yet 100%.
Sorting saves time for the reducer, helping it easily distinguish when a new reduce task should start. It simply starts a new reduce task, when the next key in the sorted input data is different than the previous, to put it simply. Each reduce task takes a list of key-value pairs, but it has to call the reduce() method which takes a key-list(value) input, so it has to group values by key. It's easy to do so, if input data is pre-sorted (locally) in the map phase and simply merge-sorted in the reduce phase (since the reducers get data from many mappers).
Partitioning, that you mentioned in one of the answers, is a different process. It determines in which reducer a (key, value) pair, output of the map phase, will be sent. The default Partitioner uses a hashing on the keys to distribute them to the reduce tasks, but you can override it and use your own custom Partitioner.
A great source of information for these steps is this Yahoo tutorial (archived).
A nice graphical representation of this is the following (shuffle is called "copy" in this figure):

Note that shuffling and sorting are not performed at all if you specify zero reducers (setNumReduceTasks(0)). Then, the MapReduce job stops at the map phase, and the map phase does not include any kind of sorting (so even the map phase is faster).
UPDATE: Since you are looking for something more official, you can also read Tom White's book "Hadoop: The Definitive Guide". Here is the interesting part for your question.
Tom White has been an Apache Hadoop committer since February 2007, and is a member of the Apache Software Foundation, so I guess it is pretty credible and official...

A: I've always assumed this was necessary as the output from the mapper is the input for the reducer, so it was sorted based on the keyspace and then split into buckets for each reducer input. You want to ensure all the same values of a Key end up in the same bucket going to the reducer so they are reduced together. There is no point sending K1,V2 and K1,V4 to different reducers as they need to be together in order to be reduced.
Tried explaining it as simply as possible

A: Shuffling is the process by which intermediate data from mappers are transferred to 0,1 or more reducers. Each reducer receives 1 or more keys and its associated values depending on the number of reducers (for a balanced load). Further the values associated with each key are locally sorted.

A: Because of its size, a distributed dataset is usually stored in partitions, with each partition holding a group of rows. This also improves parallelism for operations like a map or filter. A shuffle is any operation over a dataset that requires redistributing data across its partitions. Examples include sorting and grouping by key.
A common method for shuffling a large dataset is to split the execution into a map and a reduce phase. The data is then shuffled between the map and reduce tasks. For example, suppose we want to sort a dataset with 4 partitions, where each partition is a group of 4 blocks.The goal is to produce another dataset with 4 partitions, but this time sorted by key.

In a sort operation, for example, each square is a sorted subpartition with keys in a distinct range. Each reduce task then merge-sorts subpartitions of the same shade.
The above diagram shows this process. Initially, the unsorted dataset is grouped by color (blue, purple, green, orange). The goal of the shuffle is to regroup the blocks by shade (light to dark). This regrouping requires an all-to-all communication: each map task (a colored circle) produces one intermediate output (a square) for each shade, and these intermediate outputs are shuffled to their respective reduce task (a gray circle).
The text and image was largely taken from here.

A: There only two things that MapReduce does NATIVELY: Sort and (implemented by sort) scalable GroupBy.
Most of applications and Design Patterns over MapReduce are built over these two operations, which are provided by shuffle and sort.

A: This is a good reading. Hope it helps. In terms of sorting you are concerning, I think it is for the merge operation in last step of Map. When map operation is done, and need to write the result to local disk, a multi-merge will be operated on the splits generated from buffer. And for a merge operation, sorting each partition in advanced is helpful.

A: Well,
In Mapreduce there are two important phrases called Mapper and reducer both are too important, but Reducer is mandatory. In some programs reducers are optional. Now come to your question.
Shuffling and sorting are two important operations in Mapreduce. First Hadoop framework takes structured/unstructured data and separate the data into Key, Value.
Now  Mapper program separate and arrange the data into keys and values to be processed. Generate Key 2 and value 2 values. This values should process and re arrange in proper order to get desired solution. Now this shuffle and sorting done in your local system (Framework take care it) and process in local system after process framework cleanup the data in local system.
Ok
Here we use combiner and partition also to optimize this shuffle and sort process. After proper arrangement, those key values passes to Reducer to get desired Client's output. Finally Reducer get desired output.
K1, V1 -> K2, V2 (we will write program Mapper), -> K2, V' (here shuffle and soft the data) -> K3, V3 Generate the output. K4,V4.
Please note all these steps are logical operation only, not change the original data.
Your question: What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?
Short answer: To process the data to get desired output. Shuffling is aggregate the data, reduce is get expected output.


text:
Q: Why subtracting 1 is considered ill-conditioned? I was reading the following to better understand stability:

Consider evaluating $f(x) = \sqrt{1+x}-1$ for $x$ near $0$. $C_f(x) = \frac{\sqrt{1+x}+1}{2\sqrt{1+x}}$ so $C_f(0) = 1$ so it is not
ill-conditioned. To compute this we would have the 3 steps: $(1)\ t_1
 = 1+x$, $(2)\ t_2 = \sqrt{t_1}$, and $f(x)=t_2-1$. Steps $(1)$ and $(2)$ are well-conditioned (condition numbers $0$ and $1/2$) while
step $(3)$ is ill-conditioned. Thus we would say the algorithm is
unstable.

I'm trying to understand why exactly the third step is ill-conditioned. Is it due to catastrophic cancellation because $t_1$ would be close to $1$? Is $1+x$ and $\sqrt{t_1}$ just not sensitive to perturbations due to floating point errors but $t_2-1$ is?

A: When you subtract two nearly equal floating point numbers you lose precision.  In your example suppose we are working with seven place base $10$ numbers and let $x=10^{-4}$.  Then $t_1=1+x=1.000100$ is exact.  $t_2=\sqrt {t_1}=1.000050$ is within $\frac 12LSB$.  But when we subtract $t_2-1$ we get $5.0 \cdot 10^{-5}$ and only those two places are good.  The leading five places canceled out.  That is the catastrophic loss of precision.


text:
Q: LM317 Get Stable Output voltage at 1,25 V I am currently trying to use the LM317 with a stable output voltage of 1,25 V.
The general formula is
$$
Vo = Vref\cdot\left(1+\frac{R2}{R1}\right) + Iadj\cdot R2
$$

I used this circuit to create the 1,25 V output voltage:

simulate this circuit – Schematic created using CircuitLab
This circuit is directly according to the formula. R1 is infinitely high, R2 is zero. In general I measure the 1,25 V output voltage. But when the load is drawing current, everything gets unstable. Then I measure voltages higher and lower than 1,25 V...
I read some things regarding the minimum current in Adj Terminal. Therefore I thought about calculating R1 to create Iadj at ~50µA (according to ST LM317 datasheet). But whats with R2, should it be shortened to ground in this case?
I also thought about inserting a series resistor at the output, just to create a small load of ~1mA. Maybe the LM317 needs a minimum load...
Are there any suggestions? Thanks for your help.

A: Yes, as suggested, the LM317 DOES need a minimum load.   The specification
sheet suggests about 10 mA, LM317 see table 7.5 "minimum load current".
The bias current to run the internal error amplifier comes from the
input pin (#3 of the TO220 package) and the circuit is completed by output current at the output
pin (#2), while the sense pin (#1) carries only a small trickle of sense current.   If the R1 resistor is 120 ohms, it will be an adequate load resistance (R2 = zero ohms).    Lacking an adequate load, though,
the formula is inapplicable, because the internal amplifiers are lacking
the needed power supply current.

A:
Maybe the LM317 needs a minimum load

Indeed it does. It is specified in the datasheet for the exact version you are using, and is typically between 2-10 mA.
In fact, this is (one of?) the reasons behind the slightly unusual value for R1 in the example schematics. It creates a minimum load of 5 mA at all times.
Adding a 240 ohm resistor to your circuit should clean it up.


text:
Q: How do I use an apply function in R to find the maximum of a variable for subgroups  salary <- data.frame(name=c("Kay","Dave","Jon","Jenny","Jim","Eve","Ed"),
 salary=c(60000, 100000, 50000, 80000, 30000, 40000, 20000),
 gender=factor(c("F","M","M","F","M","F","M")))

I am able to filter a female data frame with
femaleFiltered <- salary[ which(salary$gender=='F'), ]

and I am trying to use
getMaxSal1 <- function(x) {
    x[which.max(x$salary),]
}

apply(femaleFiltered,2,getMaxSal1)

but get error "Error in x$salary: $ operator is invalid for atomic vectors"

A: We can use subset from base R
subset(femaleFiltered, salary == max(salary))
#   name salary gender
#4 Jenny  80000      F

Or as per OP's requirement about a possible use of *apply
femaleFiltered[unlist(lapply(names(femaleFiltered),
       function(nm) which.max(femaleFiltered[nm]$salary))),]
#   name salary gender
#4 Jenny  80000      F

A: I'd suggest
aggregate(salary$salary, by=list(salary$gender), FUN = max)

oh just read about needing to do an apply function.
Make a list of two data frames, one for males, one for females.
Then use lapply()  with FUN = max.
lapply(list(femaleFiltered$salary, maleFiltered$salary), max)


text:
Q: "Prove that if $G$ is a group, then $\{x \in G : x^2 =e \}$ is a subgroup of $G$": is that correct? My teacher left this exercise:

"Prove that if $G$ is a group, then $\{x \in G : x^2 =e \}$ is a subgroup of $G$"

but I don't know if it's correct, I have seen similar exercises like that

"if $x^2 = e $ for all $x \in G$ then $G$ is abelian",

and in this case if $G$ is abelian then the proof is fairly simple but my teacher didn't say $G$ was abelian, so I'm not sure if that statement is true or if he forgot to say that $G$ is abelian.
I have tried to found a counterexample (if it exists) but haven't found any.
Any help? Thanks in advance

A: A reflection of the plane has order $2$, but the composite of two reflections in intersecting lines is a rotation, which does not necessarily have order $2$ ...

A: A probably simple counterexample: in $\;S_3\;$ , we have that $\;(12)^2=(13)^2=1\;$ , yet $\;(12)(13)=(132)\;$, and $\;(132)^2\neq1\;$ , so that the set $\;\{x\in G\;|\;x^2=e\}\;$ isn't even closed...


text:
Q: Why my toString() does not work in Android Studio? i have a code below where i try to create a Alarm clock. I have problem with string and toString. Which is shown as red in Android Studio. I have tried String.valueOf(value) but it have same problem with string??
any suggestions?
    public String AlarmTime() {
        int alarmHours = alarmTime.getCurrentHour();
        int alarmMinutes = alarmTime.getCurrentMinute();
        String stringAlarmMinutes;

        if (alarmMinutes < 10) {
            stringAlarmMinutes = "0";
            stringAlarmMinutes = stringAlarmMinutes.concat(alarmMinutes.toString());
        } else {
            stringAlarmMinutes = alarmMinutes.toString();
        }

        String stringAlarmTime;

        if(alarmHours > 12) {
            alarmHours=alarmHours - 12;
            stringAlarmTime=alarmHours.toString().concat(":").concat(alarmMinutes.toString()).concat(" PM");
        } else {
            stringAlarmTime=alarmHours.toString().concat(":").concat(alarmMinutes.toString()).concat(" AM");
        }
        return stringAlarmTime;
    }
}

A: Primitive types such as int do not have any methods, let alone a toString method.
String.valueOf(int) should be ok, so you must have made some other error there. I can't say, since you did not post that version.


text:
Q: How to throw popup only to those who are visiting from India? I want to show an entry popup only to those who are visiting from India using JavaScript.

A: Firstly get the IP of the visitor
$(document).ready(function () {
    $.getJSON("http://jsonip.com/?callback=?", function (data) {
        console.log(data);
        alert(data.ip);
    });
});

Then use a service that actually returns country names, like FreeGeoIp
$.getJSON("http://freegeoip.net/json/", function (data) {
    var country = data.country_name;
    var ip = data.ip;
});

After that shw your popup
if(country == 'India') {
    //......
}

A: You need to do IP Geo-location. There are a quite a few plugins that will help with this, find the one that best suits your application.


text:
Q: open raster in R! and some statistical operation I would like to open raster files (in ASCII or TIFF format), aggregate their cells and after this operation count correlation between values in this new raster file and another one. Unfortunately I do not know what is wrong in my commands - I get an error message:
x <- GDAL.open('~/Pulpit/dods/karol/TVDI 113_121/TVDI_kamp_evi_TRANSF.asc')

CPL ERROR 4: `~/Pulpit/dods/karol/TVDI 113_121/TVDI_kamp_evi_TRANSF.asc' does not exist in the file system, and is not recognised as a supported dataset name.
Error in .local(.Object, ...) : `~/Pulpit/dods/karol/TVDI 113_121/TVDI_kamp_evi_TRANSF.asc' does not exist in the file system, and is not recognised as a supported dataset name.

A: If you are having trouble getting the filenames, you might do this:
my_asc_files = dir("../somepath", pattern="*.asc", recursive=T, full.names=T)
files_I_want = my_asc_files[c(1,12,32,33)]

Then you can load your files like this
library(raster)
my_rasters = lapply(files_I_want, raster)

Then you may do this:
pairs(my_rasters)

and this:
for(i in 1:length(my_rasters))
  for(j in i:length(my_rasters))
    if(i != j) {
      df = na.omit(data.frame(values(my_rasters[[i]]), values(my_rasters[[j]])))
      cor(df[,1], df[,2])
    }

Although you will run into problems if the rasters are so large that you cannot hold two in memory at the same time. Without a better question it will be hard to give you better advice.

A: To read (open) a raster, one way is to use readGDAL:
library(rgdal)
r <- readGDAL("~/myhome/thisdir/IhaveaFile.asc")

This is my personal preference, and the only reason to otherwise use GDAL.open or raster is if my machine doesn't have the RAM (+abit) to deal with the data set in question.


text:
Q: Strange issue starting a node application from another directory I've got an MVC application using Nodejs / Express.
If I start the app using PM2 within the directory EG.
pm2 start my_app.js

All is well. If I try to start it from another directory EG.
pm2 start ../another_directory/my_app.js

The app appears to start fine, but when I browser the app it complains it can't find the view file. The error implies it's looking for the view file in the directory (EG my_folder/views I'm sat in, instead of ./another_directory/views/my_view.
Sorry this is a bit general. But does this ring a bell with anybody please?
Thanks.
Edit.
Would setting a Express namespace solve this issue as per:
Setting an Express namespace
Edit 2.
It didn't help.

A: If anybody is interested, I solved it by adding the following to my start uo .js script I was calling:
app.set('views', `${__dirname}/views`);

Seems I had to reinforce the path to the views.


text:
Q: How do i customize nav-item element only in my active page I'm new to Vue.js and Nuxt and I want to have my background img (blue line in top of items)  only in my active page (e.g contact page)

this is my HTML code :
<b-navbar-nav class="text">
    <b-nav-item to="/">ACCUEIL</b-nav-item>
    <b-nav-item href="/#">ARTICLES</b-nav-item>
    <b-nav-item href="#">CARTE</b-nav-item>
    <b-nav-item to="/about">L'ÉQUIPE</b-nav-item>
    <b-nav-item to="/contact">CONTACT</b-nav-item>
  </b-navbar-nav>

and my CSS :

any help please?

A: You could use the nuxt-link-active class to set the image styles on the active nav item instead of the nav-link which would apply it to all nav-items.
The nuxt-link-active is applied by default when using Nuxt.js. You can even set a custom CSS class to be applied for the active nav. You can read more about it in the documentation here.


text:
Q: C++20 source_location to replace macro to multi-parameter variadic template Can this be made to display the line number of the actual call site, like the macro does ?
#include <iostream>
#include <type_traits>
#include <source_location>
#include <cassert>
using namespace std;

namespace myLib{

template<typename Enumt, typename... Ts> // alert bad calls, throw
constexpr void setValsF(const unsigned line, Ts const&... args){
  cout << "line #"<<line<<": illegal call to setVals()\n";
  assert(is_enum_v<Enumt>);
}

template<class... Enumt, class = common_type_t<Enumt...> >
requires conjunction_v<is_enum<Enumt>...>
constexpr void setValsF(const unsigned line, Enumt&... vals){
  cout << "line #"<<line<<": legal call to setVals()\n";
}

}// myLib

int main(){

  enum enumVals : short { a = 0, b, c, count };

  // #define setVals(...) myLib::setValsF<enumVals>(__LINE__ __VA_OPT__(,__VA_ARGS__))
  constexpr auto setVals = [](auto&&... args) {
    myLib::setValsF<enumVals>(source_location::current().line(), args...); };

  setVals(a,b); // legal
  setVals(b,"text"); // illegal
}

run
.. keeping a nice simple API ( setVals(a,b) ), that is.
It would work :

*

*with a defaulted argument to the function template, but for the parameter pack. Couldn't figure a deduction guide in the presence of more than one template parameter.

*or if current() was the default constructor to source_location !

I resorted to runtime handling of bad calls (to certain APIs) as a courtesy to my library users, as my very specific insult is wayyy nicer than the indecipherable blob the compiler vomits.

A: Expanding on my comment, as requested by the OP.
Piotr Skotnicki's accepted answer to How to use source_location in a variadic template function? introduces an helper class and a deduction guide:

template <typename... Ts>
struct debug
{
   debug( Ts&&... ts
        , const std::source_location& loc = >std::source_location::current());
};

// The deduction guide forces the deduction of the pack, "separating"
// it from the default parameter.
template <typename... Ts>
debug(Ts&&...) -> debug<Ts...>;

int main()
{
   debug(5, 'A', 3.14f, "foo");
}

Here, though, something else needs to be passed. My proposal is to inject the requirements as a template parameter before the pack.
#include <concepts>
#include <iostream>
#include <source_location>

template <typename R, typename... Ts>
struct debug
{
  debug( R&& req      // <- A requirement that the pack ts must fulfill.
       , Ts&&... ts
       , std::source_location const& loc = std::source_location::current() )
  {
    std::cout << "line #" << loc.line() << ": "
              << ( req(ts...) ? "valid call\n" : "invalid call\n" );
  }
};

// We don't need to differentiate the first parameter of the pack, here.
template <typename... Args>
debug(Args&&...) -> debug<Args...>;

int main()
{
  enum enumVals : short { a = 0, b, c, count };

  // Since C++20 we can have templated lambdas. Here I don't need named parameters,
  // but I need named types to use std::same_as in the fold expression.
  constexpr auto all_enums = []<typename... Ts>(Ts&&...) {
    return ( ... and std::same_as<std::remove_cvref_t<Ts>, enumVals> );
  };

  debug(all_enums, a, b);   // -> line #31: valid call
  debug(all_enums, b, 1);   // -> line #32: invalid call
}

This is not as terse as setVals(a,b), in OP's code, but seems to work1 as intended.

1) Note that this works with gcc and clang(trunk) (as noted by Ted Lyngmo), but not with clang15: https://godbolt.org/z/zxxMTs4Kj


text:
Q: Efficiently filtering a dictionary in-place We have a dictionary d1 and a condition cond. We want d1 to contain only the values  that satisfy the condition cond. One way to do it is:
d1 = {k:v for k,v in d1.items() if cond(v)}

But, this creates a new dictionary, which may be very memory-inefficient if d1 is large.
Another option is:
for k,v in d1.items():
    if not cond(v):
       d1.pop(k)

But, this modifies the dictionary while it is iterated upon, and generates an error: "RuntimeError: dictionary changed size during iteration".
What is the correct way in Python 3 to filter a dictionary in-place?

A: If there are not many keys the corresponding values of which satisfy the condition, then you might first aggregate the keys and then prune the dictionary:
for k in [k for k,v in d1.items() if cond(v)]:
    del d1[k]

In case the list [k for k,v in d1.items() if cond(v)] would be too large, one might process the dictionary "in turns", i.e., to assemble the keys until their count does not exceed a threshold, prune the dictionary, and repeat until there are no more keys satisfying the condition:
from itertools import islice

def prune(d, cond, chunk_size = 1000):
    change = True
    while change:
        change = False

        keys = list(islice((k for k,v in d.items() if cond(v)), chunk_size))
        for k in keys:
            change = True
            del d[k]


text:
Q: How to create, not edit, an object with a list of objects in C# MVC 4 using model binding? Say I had a website where users create (and edit) video game consoles.  It has the following model.
VideoGameConsole:
  String name
  DateTime released
  List<VideoGames> games

VideoGame:
  String name
  DateTime released
  HttpPostedFileBase image

(I hope this example is simple enough.)
I'm wondering how to create such an object using model binding (not edit, I've seen a lot of solutions for rendering or editing an already existing dynamic list).  The current way seems to be the model binding only allows for you to create the VideoGameConsole with no games, then go back on the edit screen and add games.  I'm looking for a solution where the user can see the total object before creation.  At the very least, is there a name for what I'm trying to do that would make it easier to continue my own research on this?
Thanks.
Edit 1:
Two important notes that makes this even more... fun (in the Dwarf Fortress sense).
First, I've changed the model to include a HttpPostedFileBase for each VideoGame that represents an image.  So we need to be able to upload multiple files.  This doesn't make it that much more fun on its own.
Second, this needs to work without javascript (part of the userbase of our apps has javascript disabled for... reasons... and we can't just not support them).  This is where the real fun begins.
As for not using javascript, my partial solution to this is as follows.
When they click to add a new game, post the page back, do not save it, and then return the view model with that page offering the ability to edit the list of already added games or add a new one.  This is almost stateless, except on each post we add the image file to session (otherwise they'll have to re-add every file every time they decide to add a new game before hitting save).  Then we add javascript on top to make it so the intermediate postbacks are not needed if you have javascript enabled.

A: You've got examples for editing an existing model like you say, so use that as a guide and in your create action, create and send down a non-null model to your view, with say 10, 20, 100 (whatever number suits) of your child items pre-populated, and just prevent the user adding new child items over and above what you've provided in the create view.
On postback, you can check the validity of the child items, to discard those you'll not want to keep - those that haven't been modified by the user.


text:
Q: How to not show hidefile and hidefolder in ListView in android I am tired use a fileexplorer when Show a hiddenfile and hiddenfolder but i can not show hidden file and folder please help me.Thanks
in this code
for(File ff: dirs){
                Date lastModDate = new Date(ff.lastModified());
                DateFormat formater = DateFormat.getDateTimeInstance();
                String date_modify = formater.format(lastModDate);
                if(ff.isDirectory()) {
                        File[] fbuf = ff.listFiles();
                        int buf = 0;
                        if (fbuf != null) {
                            buf = fbuf.length;
                        } else buf = 0;
                        String num_item = String.valueOf(buf);
                        if (buf == 0) num_item = num_item + " item";
                        else num_item = num_item + " items";
//String formated = lastModDate.toString();
                        dir.add(new Item(ff.getName(), num_item, null, ff.getAbsolutePath(), "directory_icon"));
                    }


text:
Q: How to insert data into table using stored procedure I am passing form values to stored procedure parameters and i have a problem...
I want to execute this stored procedure from a C# program.
 I am VERY new at this, so any help on why I am getting these errors is greatly appreciated.
Stored Procedure Parameters
ALTER PROCEDURE [dbo].[User]
(
   @pname varchar(100),
   @Colour varchar(100),
   @Sheet varchar(100),
   @Size varchar(100),
   @GSM varchar(100),
   @pcost varchar(100),
   @is_deleted bit,
   @DOC datetime
)
as begin
INSERT INTO [SMjobcard].[dbo].[Papertype]
        ([pname]
       ,[Colour]
       ,[Sheet]
       ,[Size]
       ,[GSM]
       ,[pcost]
       ,[is_deleted]
       ,[DOC])
 VALUES
       (@pname,@Colour,@Sheet,@Size,@GSM,@pcost,@is_deleted,@DOC)
 END

C#
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.OleDb;

public partial class Admin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void Button1_Click(object sender, EventArgs e)
{
    String ConnString =   ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(ConnString);
    //SqlConnection con = new SqlConnection("Data Source=(local);Initial    Catalog=SMjobcard;Integrated Security=True");
    //con.Open();
    SqlCommand cmd = new SqlCommand(ConnString);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "User";
    cmd.Parameters.Add("@pname", SqlDbType.VarChar,50).Value = TextBox2.Text.Trim();
    cmd.Parameters.Add("@Colour", SqlDbType.VarChar,50).Value = TextBox3.Text.Trim();
    cmd.Parameters.Add("@Sheet", SqlDbType.VarChar,50).Value = TextBox4.Text.Trim();
    cmd.Parameters.Add("@Size", SqlDbType.VarChar,50).Value = TextBox5.Text.Trim();
    cmd.Parameters.Add("@GSM", SqlDbType.VarChar,50).Value = TextBox6.Text.Trim();
    cmd.Parameters.Add("@pcost", SqlDbType.VarChar,50).Value = TextBox7.Text.Trim();
    cmd.Parameters.Add("@is_deleted", SqlDbType.Bit).Value = true;
    cmd.Parameters.Add("@DOC", SqlDbType.DateTime).Value = TextBox9.Text.Trim();
    cmd.Connection = con;
    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        lblmsg.Text = "Record inserted successfully";
    }
    catch (Exception ex)
    {
       ex.ToString();
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
   }
}

** i have an error for converting string to decimal,string to Boolean,string to decimal plz help me **

A: Please check your table design and then create the Stored Procedure.it may be possible that your are inserting wrong data to wrong column.means string data to bool column.so please check.


text:
Q: how to color icon selected in bottomNavigationView with gradient color I have bottomNavigationview with some icon and I want when anyone selected icon , color of the icon changed to gradient color .
gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:startColor="#ee5f8a"
        android:endColor="#ed8f6d"
        android:angle="0"/>
</shape>

BottomNavigationview
<android.support.design.widget.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:elevation="5dp"
        app:itemIconSize="35dp"
        app:itemIconTint="@color/selector"
        app:labelVisibilityMode="unlabeled"
        app:menu="@menu/bottom_nav_menu" />

selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/colorPrimaryDark"
      android:state_checked="true" />
    <item android:color="#c2bdbf" />

</selector>

A: Add this attribute to BottomNavigationView
app:itemIconTint="@drawable/bottom_selector"

Create one drawable named bottom_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#ff0000"/>
<item android:color="@color/colorPrimaryDark"/>
</selector>

A: You need a drawable selector and not a color selector to create a gradient background.
drawable/selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/gradient" android:state_checked="true" />
</selector>

drawable/gradient.xml  (same as question)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="linear"
        android:startColor="#ee5f8a"
        android:endColor="#ed8f6d"
        android:angle="0"/>
</shape>

and finally your view
<android.support.design.widget.BottomNavigationView
    android:id="@+id/nav_view"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:layout_alignParentBottom="true"
    android:background="?android:attr/windowBackground"
    app:elevation="5dp"
    app:itemIconSize="35dp"
    app:itemBackground="@drawable/selector"
    app:labelVisibilityMode="unlabeled"
    app:menu="@menu/bottom_nav_menu" />


text:
Q: javascript: variable undefined When I use a variable in javascript, it gives an error

ReferenceError: getalletje is not defined

, depending on where I declare it.
This is where I declare the variable:
get_name: function(){
        var getalletje = 5;
        return getalletje;
    },

Where I'm trying to use the variable:
        self.$('.geldinuit-button').click(function(){

                self.screen_selector.show_popup('geldinuit',{
                    message: _t('Popup titel'),
                    comment: _t('getalletje'),
                    confirm: function(){
                        window.alert(getalletje);
                    },
                });

        });

It gives an error like this.
But: If I put var getalletje = 5;just above self.$('.geldinuit-button').click(function(){, it works.
Something extra I need to do?
Edit for Shomz: This is the full code:
.............
self.set_smart_status(status.newValue);
            });

            this.$el.click(function(){
                self.pos.connect_to_proxy();
            });
        },
    });

    module.PosWidget = module.PosBaseWidget.extend({
        template: 'PosWidget',
        init: function() {
            this._super(arguments[0],{});
            this.pos = new module.PosModel(this.session,{pos_widget:this});
            this.pos_widget = this; //So that pos_widget's childs have pos_widget set automatically

.............................
............................

    get_name: function(){
        var getalletje = 5;
        return getalletje;
    },
...........................
...........................
                self.$('.geldinuit-button').click(function(){

                        self.screen_selector.show_popup('geldinuit',{
                            message: _t('Popup titel'),
                            comment: _t('getalletje'),
                            confirm: function(){
                                window.alert( this.get_name() );
                            },
                        });

                });
..........................

A: It's a scoping issue - the variable you declare is available only locally. To get its value, you can do something like:
confirm: function(){
    window.alert( yourObject.get_name() );
},

where yourObject is the object that you defined the get_name method for.

A: you can't access variable outside of the function you declare it in. If you want to access variable in a global way you should declare it outside of get_name.
In your case I don't see the point but the following should work:
var getalletje = 0;

get_name: function(){
        getalletje = 5;
        return getalletje;
    },

self.$('.geldinuit-button').click(function(){

                self.screen_selector.show_popup('geldinuit',{
                    message: _t('Popup titel'),
                    comment: _t('getalletje'),
                    confirm: function(){
                        window.alert(getalletje);
                    },
                });

    });

also, shouldn't:
comment: _t('getalletje'),

become
comment: _t(getalletje),

UPDATE
Also, in your case this declaration isn't useful. I don't know if you changed your code when asking your question but in this case doing only:
self.$('.geldinuit-button').click(function(){
                var getalletje = 5;

            self.screen_selector.show_popup('geldinuit',{
                message: _t('Popup titel'),
                comment: _t('getalletje'),
                confirm: function(){
                    window.alert(getalletje);
                },
            });

});


text:
Q: angular dynamically assign template I need to use the youtube player from @angular/youtube-player but I need the videoId to be dynamic. Is it possible to assign variables to the component decorator?
I have tried this but I get an error:

const videoId = localStorage.setItem('videoId}', welcomeInfo.imageVideoUrl);

@Component({
  template: `<youtube-player
    videoId=${videoId}
    suggestedQuality="highres"
    [height]="600"
    [width]="1080"
    [startSeconds]="43"
    [endSeconds]="60">
  </youtube-player>`,
  selector: 'app-video'
})

A: To dynamically assign a videoId to the youtube-player you can do:
@Component({
  template: `<youtube-player
    [videoId]="videoId"
    suggestedQuality="highres"
    [height]="600"
    [width]="1080"
    [startSeconds]="43"
    [endSeconds]="60">
  </youtube-player>`,
  selector: 'app-video'
})


text:
Q: Recommend XML Difference open source Java libraries? I have a requirement to compare two XML documents and report differences.  String comparison is not sufficient as I want to be able to say that:
<Foo/>

is the same as
<Foo></Foo>

Anyone used a library they would recommend?

A: There's the cunningly named xmldiff which I've used before with success.
XMLUnit also works well. It's primarily for use in unit tests (alongside JUnit).

A: or try diffxml:

The standard Unix tools diff and patch
  are used to find the differences
  between text files and to apply the
  differences. These tools operate on a
  line by line basis using well-studied
  methods for computing the longest
  common subsequence (LCS).
Using these tools on hierarchically
  structured data (XML etc) leads to
  sub-optimal results, as they are
  incapable of recognizing the
  tree-based structure of these files.
This project aims to provide Open
  Source XML diff and patch utilities
  which operate on the hierarchical
  structure of XML documents.

A: What I always do is format both sides of the XML (xmllint -format) and diff the results.


text:
Q: Angular 2 typescript function that lasts some time only I am trying to make a function that lasts for a few seconds.
Something like this :
limitTo(function() {

},4000 );

How to limit time of a function ?

A: mybe something like:
var isFinished= false;

setTimeOut(function(){
    isFinished=true;
},500);

while (isFinished) {
    text += "The number is " + i;
    i++;
}


text:
Q: Resuming song playback after tombstoning I'm developing a simple rhythm game for Windows Phone 7 using XNA. Currently I'm writing the tombstoning logic but I've stumbled with the audio state.
I have a song playing in the background, using MediaPlayer. When my game is tombstoned, song playback should stop and its state saved, so that when my game is loaded again the song starts playing where it was left. I'm using the MediaPlayer class to play the song, but it seems there's no way to seek the song to an arbitrary position.
Is there any way to save and restore the state of MediaPlayer so that the song playback can be properly resumed? Or is there a better way to play a song in order to support tombstoning?
Thanks in advance

A: Try setting mediaplayer.position which is the point in the song where you want to play from.
http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer.position.aspx

A: It seems like the solution provided by dolhaig on CodeProject should give you what you need. Seems to be able to handle the saving off and resuming the song at it's current state and he indicates that it supports XNA in the article.
http://www.codeproject.com/KB/windows-phone-7/ResumeMusicPlayback.aspx?msg=3859350


text:
Q: add an object or edit if exist (indexeddb) I have this code and i can add or edit the object if exists, but the "for" finish before the function onsuccess is called, then the index "for" is bad.
How to pass the index onSuccess?
Help!!!
var active = dataBase.result;
var data = "";
var object = "";
var index = null;
var request;
$(".layers").promise().done(function () {
    var elements = document.getElementsByClassName('layers');
     for (var i = 0; typeof (elements[i]) != 'undefined'; i++) {
        if (elements[i].getAttribute("src").split("/")[4] !== "alpha.png") {
        data = active.transaction([elements[i].getAttribute("src").split("/")[3]], "readwrite");
        object = data.objectStore(elements[i].getAttribute("src").split("/")[3]);
        index = object.index("by_Name");
        request = index.get(String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]));

        request.onsuccess = function (e) {
            var result = e.target.result;
            if (result === undefined) {
                var resultPut = object.put({
                    Name: String(elements[i].getAttribute("src").split("/")[4] + "/" + elements[i].getAttribute("src").split("/")[6]),
                    Count: 1,
                    Type: String(elements[i].getAttribute("src").split("/")[4])
                });
                resultPut.onerror = function (e) {
                    alert(resultPut.error.name + '\n\n' + resultPut.error.message);
                };
            } else {
                result.Count++;
                var requestUpdate = object.put(result);
                requestUpdate.onerror = function (event) {
                    alert(requestUpdate.error.name + '\n\n' + requestUpdate.error.message);
                };
            }
        }(event);
        }
    }
    alert("Finish");
})

A: The thing is that, by the time the for has ended, the transactions with the object store are not. What you could try is to encapsulate the index like this:
for(var i = 0; i < elements.length; i++) {
    (function(myElement) {
        if (myElement.getAttribute("src").split("/")[4] !== "alpha.png") {
        ...
        }
    })(elements[i]);
}


text:
Q: Can someone show me how to connect to a H2 database with ColdFusion? I'm simply looking for some basic code examples showing me how to connect to a H2 database on the ColdFusion server and perhaps couple of examples of how to execute SQL statements.
Thanks.

A: I am not familiar with H2, but from skimming the tutorial, I would say start by creating an "other" datasource. Then connect using embedded mode.
These instructions are for the MySQL driver, but the same concepts apply to using any jdbc driver.

*

*Download and install the driver jar, and restart CF.

*Create a datasource of type "Other" and enter the appropriate:

*

*JDBC URL

*Driver class

*Username and password

You can get the rest from the documentation.


text:
Q: Search for Online Sockets in AS3 PLATFORM : AIR for Android
im trying to develop a quick search algorithm for search online sockets on my LAN network.
the first algorithm was creating 255 sockets base on my gateway
EXAMPLE:
192.168.1.1 is my gateway
so i'll have to create sockets and connect 192.168.1.0 up to 192.168.1.254 in searching for online sockets. This is quick in searching, however it causes lags because it eats a lot of RAM. Even after i dispose the sockets that have failed to connect. All sockets that are online are stored in a Vector array.
i dispose the failed sockets by:

*

*removing all listeners from the socket.

*closing the socket

*setting the socket to null.

*Call System.gc() to force garbage collection

The second algorithm was using only 1 socket and it will start to connect starting from 192.168.1.0 and increments up to 255 until it finds a online socket. When the socket fails to connect, it will proceed to the next ip depending on the timeout.
var ip = '192.168.1';
var ipCounter = 0;

socket.addEventListener(Event.CONNECT, connectHandler);
socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);

socket.timeout = 50;

function connectHandler(e:Event):void{

}

function ioErrorHandler(e:IOErrorEvent):void{
    ipCounter += 1;
    if(ipCounter > 255){
        ipCounter = 0;
    }
    socket.connect(ip+'.'+ipCounter.toString(), 18765);
}

socket.connect(ip+'.'+ipCounter.toString(), 18765);

this works however, it is slow.
How can i improved the search algorithm?

A: I finally found a faster solution.
I used DatagramSocket (UPD) instead for searching.
It's because it doesn't have to connect to a socket server to send data.
datagramSocket.send(bytearray, start, length, ip, port);


text:
Q: Basic Eventhandler Question Ok right now I have an object containing 3 strings, along with setters and getters. Now I have two questions -
First, I'm new to C# is there any way to optimize the following methods and make them more efficient?
    void getSearchResults(object sender, RoutedEventArgs e)
    {
        string baseURL = "http://api.search.live.net/xml.aspx?Appid=<MyAPPID>&query=%22";
        string companyName = ((TaxiCompany)sender).CoName;
        string formatAndKey = "%22&sources=web";
        WebClient c = new WebClient();
        c.DownloadStringAsync(new Uri(baseURL + companyName + formatAndKey));
        c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(findTotalResults);
    }

    //Parses search XML result to find number of results
    void findTotalResults(object sender, DownloadStringCompletedEventArgs e)
    {
        lock (this)
        {
            string s = e.Result;
            XmlReader reader = XmlReader.Create(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(s)));
            String results = "";
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name.Equals("web:Total"))
                    {
                        results = reader.ReadInnerXml();
                        break;
                    }

                }
            }
        }
    }

Second, I'm initializing an object - new Taxi Company (String name, String Phone, String Results). I've got name and number and I need to call the above two functions to get noOfResults so that I can initialize the object. However, I seem to run into a bunch of issues with the event handlers.
I've primarily been a web dev, so there might be something really basic I'm missing here. I have a feeling setting  up the bing methods to return a string back to the constructor might be th easiest, but not quite sure how.

A: First of all, you don't need the lock on the main page. Then, I would say that your XmlReader block should be replaced with the LINQ-to-XML variation called XDocument, that will allow you to access the XML document with a single, elegant line:
XDocument doc = XDocument.Parse(e.Result);

Once you have the document, you can check whether it contains a specific XNode.


text:
Q: Why does my FileSystemWatcher not raise events after a period of time? I have a small vb.net application utilising the FileSystemWatcher hooked up to a UNC path, after an undetermined period of time (< day) events from the watcher are not raised.
Im capturing the file created event and passing the path to a processfile code block:
Private Sub fsWatch1_Created(ByVal sender As Object, ByVal e AsSystem.IO.FileSystemEventArgs) Handles fsWatch1.Created
        'file created in path - process it!
         ProcessFile(e.FullPath)

    End Sub

A: To me it sounded like low-level problems with the network (that can't necessarily be fixed) - so a quick google search has yielded this article on CodeGuru:
http://www.codeguru.com/csharp/.net/net_general/eventsanddelegates/article.php/c9113
in which the author says that it's caused by intermittent network outages (they can go down more frequently than you think - and we're actually talking about the connection between just two machines here, which can be dropped for loads of reasons) and the watcher can end up getting corrupted.
The author hooks into the Error event, and recreates the watcher whenever it's raised.
Hope this helps.