text:
Q: Mouseleave link, reset timer and do not open popup - Elementor Popup On a webpage is a link. When you hover over the link with the mouse, it displays a popup of another webpage after a time delay. Is there a way to stop the popup from opening and reset the timeout if the mouseover the link is moved off of the link before the popup opens?
Below is the code I've tried but doesnt work
<script>
  document.addEventListener('DOMContentLoaded', function() {
      let elements = document.querySelectorAll( '.districtmarketgg' );
      let popupposts = ['3525'];

      elements.forEach(function(e,i){
        e.addEventListener( 'mouseenter', function(){
          setTimeout(function() {
            elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
          }, 2000);
      elements.forEach(function(e,i){
        e.addEventListener( 'mouseleave', function(){
          clearTimeout(function() {
            elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
          });
        })
      });
    });
  </script>

Thanks for your help.
I expected for the code to work but it didnt after I added the mouseleave lines of code. I've tried to add a clearTimeout function on mouseleave to the code but the code stops working after I add those lines.

A: clearTimeout() takes a reference to the timer's ID that you want to clear, not a function to execute.
You also don't need to loop over the collection twice. You can set both event handlers within one loop.
If you place the following script just prior to the closing body tag, you won't need the DOMContentLoaded event handler at all.
See comments inline below:
<body>
  <!-- all page HTML here -->
<script>
  let elements = document.querySelectorAll( '.districtmarketgg' );
  let popupposts = ['3525'];

  // Only 1 loop is needed here
  elements.forEach(function(e,i){
    let timer = null; // Need a variable to hold a reference to the timer

    e.addEventListener( 'mouseenter', function(){
      // Create the timer reference
      timer = setTimeout(function() {
        elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
      }, 2000);
    });

    // Same loop, new event handler
    e.addEventListener( 'mouseleave', function(){
      clearTimeout(timer);  // Stop the timer
    });
  })
</script>
</body>


text:
Q: What does =~ mean in VimScript? I can't for the life of me find an answer to this either on google or here or in the help files.
if "test.c" =~ "\.c"

At first I thought =~ mean ends in, but observe these results:
Command                               Result
echo "test.c" =~ "\.c"                1
echo "test.c" =~ "\.pc"               0
echo "test.pc" =~ "\.c"               1
echo "testc" =~ "\.c"                 1
echo "ctest" =~ "\.c"                 1
echo "ctestp" =~ "\.pc"               0
echo "pctestp" =~ "\.pc"              0
echo ".pctestp" =~ "\.pc"             0

An explanation would be great. A link to a site attempting to decipher VimScript would be even better.

A: From the docs:

*

*http://vimdoc.sourceforge.net/htmldoc/usr_41.html
For strings there are two more items:
a =~ b      matches with
a !~ b      does not match with

The left item "a" is used as a string.  The right item "b" is used as a
pattern, like what's used for searching.  Example:
:if str =~ " "
:  echo "str contains a space"
:endif
:if str !~ '\.$'
:  echo "str does not end in a full stop"
:endif

A: From the Vim documentation, it does a pattern match of the right operand (as a pattern) inside the left.

For strings there are two more items:

    a =~ b      matches with
    a !~ b      does not match with

The left item "a" is used as a string.  The right item "b" is used as a pattern, like what's used for searching.  Example:

    :if str =~ " "
    :  echo "str contains a space"
    :endif
    :if str !~ '\.$'
    :  echo "str does not end in a full stop"
    :endif

You might try your test cases again.  I get, for example, inconsistent with yours:
echo ".pctestp" =~ "\.pc"             1

And double-quotes vs single quotes seem to affect how the backslash is interpreted:
echo "test.pc" =~ "\.c"               1
echo "test.pc" =~ '\.c'               0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows 10 executes everything as an Admin I noticed that my computer runs everything as an Admin by default,
I am aware that this is an major security issue and I already reenabled UAC and deleted all register entry's for run as admin @ Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers
I am kindly and in despair asking for your help!

A: sfc /scannow
and
dism /online /cleanup-image /restorehealth
Fixed my issue,
Thanks!! Pimp Juice IT
Not sure how to mark a comment as an awnser... sorry


text:
Q: VIM: combine two searches Often I do a search for something (using hotkeys, menu command or commandline) and after that I want to keep the first search and add another search..
p.e.
- First I search doubles spaces in my text.
- Then I want to keep the matches and add the search all end of line spaces
Is there a way to combine 2 searches?
1) search 1
2) press F9 or other key: ADD
3) search 2

A: You can do this:
exe '/\('.histget('/',-1).'\)\|\('.newSearch.'\)'

where newSearch is your new search string.  A nice way of doing it is just do the searches separately to make sure you get what you want and then combine them with:
exe '/\('.histget('/',-1).'\)\|\('.histget('/',-2).'\)'

You can do this repeatedly to build quite long search strings, since it builds a new search string in the history.
This just or's the searches together, which isn't quite the same as what you asked, (since it doesn't keep the same matches).  It just concatenates the search criteria--but I suspect it's what you meant.

A: You could just press Esc then \ then Up-Arrow to scroll back through your searches and edit your previous search to include the extra term.  So the first Up-Arrow will show your last search.
Example
You wanted to search for the text _pipe( so you typed:
Esc /_pipe(
You now want to add to that search and decide that as well as _pipe( it would be useful to only include the ones with the argument option so you type:
Esc / Up-Arrow
and then edit your previous search to read /_pipe(.*option.*)
This now uses the new search which is updated from the previous search.

A: In Normal mode, you can use the last search register ("/)to recall your last search pattern:
/<C-r>/\|\(\[ ]\+$\)

Breaking it down:

*

*<C-r> is CTRL + r, it will bring up a " so you can choose a register,

*/ to choose the search register,

*\| to add another pattern in your search (OR),

*\(\[ ]\+$\) search for and group trailing spaces.


text:
Q: Can tags be used as bookmarks under semantic versioning? Shameless plug: this question is for StackMode – a StackExchange client for GNU Emacs 24+.
The product I'm working on, version-controlled with git, is a desktop application with an innately exposed API. Naturally, we want to adopt Semantic Versioning to the best of our ability. (Hopefully, perfectly and without error.)
As I understand it, semantic versions are implemented in git as tagged commits.  This is a convenient way to see all releases of a project, etc. etc.  However, we are still fairly early on in development.  Prototype functionality was implemented and committed that did not survive review (for reasons that are irrelevant here), but the functionality will almost certainly be requested in the future. We wish to bookmark the state of the repository at that time.
Are any patterns just ignored by semantic versioning tools? What patterns are allowed as these bookmarks, or is there a better way to achieve the same goal?

A: Especially when using git I would suggest using different branches for implementing prototype functionality (feature branches).
The review process could then be executed on the different branches and in case the new prototype will be needed later in the master branch, it can easily be merged to the main development branch.
The main versioning would still only happen by tagging the master branch, while tagging the prototype branches could also be possible (in case a prototype would have different development stages).
The prototype branches could exist as long as the new features are either integrated in the master branch or thrown away.


text:
Q: Transposing Specific Data in CSV I have a csv file which looks like this:
Month     Day   Year  Tmax
   4       1    1912    56
   4       2    1912    56
   4       3    1912    74
   4       4    1912    82
   4       5    1912    79
   4       1    1913    73
   4       2    1913    60
   4       3    1913    67
   4       4    1913    81
   4       5    1913    77

and I want it to look like this:
Year  Month   1     2     3      4     5
 1912   4     56     56    74     82    79
 1913   4     73     60    67     81    77

So each Day is now a column header and Tmax are displayed as columns instead of rows.  I have played around with unstacking and transposing but can't seem to quite get it.  Any help would be appreciated.

A: You could use pd.pivot_table() with index as ['Year', 'Month'] and columns as 'Day' on 'Tmax' values.
In [10]: pd.pivot_table(df, values='Tmax',
                        index=['Year', 'Month'],
                        columns='Day')
Out[10]:
Day          1   2   3   4   5
Year Month
1912 4      56  56  74  82  79
1913 4      73  60  67  81  77


text:
Q: PHP fopen filename. Is it relative or absolute? I'm having problems with my paths and fopen with reference to my web server.
I have a file saved in public/dan/new/apps/lovescopes/thisfile.php.
thisfile.php will create a new file in public/internalServer/lovescopes/xml/2009/12 using fopen "x+".
Now my errors show in the line where fopen is:

*

*If I type in the path as relative like ../../../../internalServer/lovescopes/xml/2009/12 I end up with a Permission Denied error.

*If I type an absolute path like /public/internalServer/lovescopes/xml/2009/12 I end up with "Failed to open Stream: No such File or Directory"
I'm still confused if I should use relative or absolute paths. I have a ftp_nlist and it worked perfectly well with #2. Is Fopen the same?
Also with the different error messages which I believe points to the same path, I don't know which way am I doing it right 1 or 2?

A: Why not use use realpath() with your relative paths.
Also permission denied indicates that the folder you are trying access to is not readable and/or writable by the webserver or whatever user your PHP process runs under.
In addition, if you want to read/write files in one go from/to a variable, you might want to use file_get_contents() and file_put_contents().

A: The PHP function itself is neither absolute nor relative, that depends on the path.
Both the errors you're getting are related to that specific path, either permissions or existence, so I'd recommend getting a path you know exists and you have access to and trying that (the current directory may be a good place). You may also temporary chmod the file and path, just to make sure you have read access. Print the results and any errors.
fopen("public/dan/new/apps/lovescopes/test.php");
fopen("./test.php");

If neither of those return errors, you'll know it was just a path issue.
Also, your PHP process may have different permissions than your user, so watch out for that.

A: Also, make sure that you're relative path is specified relative to the file where the function is being called (not necessarily where the actual code is).
In PHP use getcwd()(get current working directory; manual) to figure out which directory to base your relative path off of.

A: You have to make sure your script has permission to access that file


text:
Q: WAR web app redeploying dependencies I'm new to Java. Having some trouble deploying a web app.
I have an EJB project which I deploy on Glassfish (4.1).
I also have a second, JSF WEB application that I deploy to the same server.
Though I am making it with the consideration that it will be deployed to a separate server, so it creates it's own InitialContext and so on to access the EJBs.
The web application depends on the EJB project. The dependency is declared in the pom of the web app.
When deploying the web app it also tries to deploy the EJBs from the other project for some reason.
That fails with errors like javax.naming.NameAlreadyBoundException because the EJBs are already deployed separately on this server.
How can this be fixed, so the EJB dependencies from the WEB app wouldn't be attempted to be deployed?
Update: the solution needed refactoring, so the EJBs wouldn't be depended on.
            Original

   Project A                 WEB app
 ________________         ____________
| + EJBs         |<------| WEB stuff  |
| + Domain cl.   |        ------------
| + Remote intf. |
 ----------------

===========================================
            Refactored

  _______        ____________
 |  EJBs |----->| Domain cl. |
  -------        ------------
     |                  ^
     |                  |
     |                  |
     v                  |   WEB app
  ______________       ____________
 | Remote intf. | <---| Web stuff  |
  --------------       ------------

A: You could give the dependency a scope of provided:
<dependency>
    <groupId>group.id</groupId>
    <artifactId>artifact.some.id</artifactId>
    <version>1.0</version>
    <type>ear</type>
    <scope>provided</scope>
</dependency>

This means that at runtime, the dependency will be provided by the container.
see maven doc:

This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.


text:
Q: Why does my reputation decrease if I downvote another post? Hi,
I am wondering why do my reputation points go down if I downvote someone else's post?
Thank you for your time.

A: This happens because your down vote will remove 2 rep from that user. You lose 1 rep as well to prevent you from gaming the system. We couldn't let you go around taking rep away from others without making you consider if it's really worth it, could we?
If you can't justify the small loss to express your opinion on the particular post, then there's no need to down vote. If other people feel more strongly than you, they'll take care of it.


text:
Q: Group subsets of data in 3-level array by identifying column I've this type of array in PHP:
Array(
     [100] => Array(
          [1] => Array (
               [AVA_Date] => 2019-04-18
               [ROO_Id] => 100
               [RAT_Id] => 9
          )
          [2] => Array (
               [AVA_Date] => 2019-04-20
               [ROO_Id] => 100
               [RAT_Id] => 10
          )
          [4] => Array (
               [AVA_Date] => 2019-04-21
               [ROO_Id] => 100
               [RAT_Id] => 10
          )
          [7] => Array (
               [AVA_Date] => 2019-04-22
               [ROO_Id] => 100
               [RAT_Id] => 9
          )
     )
)

I would like to merge items on ROO_Id and RAT_Id.
Then, for the AVA_Date, I need to list them under a new array in the current array.
So, the desired output is:
Array(
     [100] => Array(
          [0] => Array (
               [AVA_Date] => Array (
                    [0] => 2019-04-18
                    [1] => 2019-04-22
               )
               [ROO_Id] => 100
               [RAT_Id] => 9
          )
          [1] => Array (
               [AVA_Date] => Array (
                    [0] => 2019-04-20
                    [1] => 2019-04-21
               )
               [ROO_Id] => 100
               [RAT_Id] => 10
          )
     )
)

Here what I have tried:
$newArrOtherRooms  = array_reduce($newArr, function($acc, $val) {
    $room = array_search($val['ROO_Id'], array_column($acc, 'ROO_Id'));
    $rate = array_search($val['RAT_Id'], array_column($acc, 'RAT_Id'));
    if($rate == $room && $room > -1) {
        array_push($acc[$room]['AVA_Date'], $val['AVA_Date']);
    }
    else {
        $new_arr = $val;
        $new_arr['AVA_Date'] = [$val['AVA_Date']];
        array_push($acc, $new_arr);
    }
    return $acc;
},[]);

But it doesn't work like I want.

A: There are a couple of issues with your code. Firstly, you need to wrap the array_reduce with a foreach over the outer level of $newArr. Secondly, your call to array_search doesn't consider the fact that a ROO_Id or RAT_Id value might exist more than once in the array, as it only returns the first key at which it finds the value. To work around this, you can use array_keys to get an array of key values for each ROO_Id and RAT_Id value, and then take the intersection of those two arrays using array_intersect to see if both are present in the same element. If so, you update that element, otherwise you create a new one:
foreach ($newArr as $key => $array) {
    $newArrOtherRooms[$key]  = array_reduce($array, function($acc, $val) {
        $room = array_keys(array_column($acc, 'ROO_Id'), $val['ROO_Id']);
        $rate = array_keys(array_column($acc, 'RAT_Id'), $val['RAT_Id']);
        $common = array_intersect($room, $rate);
        if(!empty($common)) {
            array_push($acc[current($common)]['AVA_Date'], $val['AVA_Date']);
        }
        else {
            $new_arr = $val;
            $new_arr['AVA_Date'] = [$val['AVA_Date']];
            array_push($acc, $new_arr);
        }
        return $acc;
    },[]);
}
print_r($newArrOtherRooms);

Output:
Array(
     [100] => Array(
          [0] => Array (
               [AVA_Date] => Array (
                    [0] => 2019-04-18
                    [1] => 2019-04-22
               )
               [ROO_Id] => 100
               [RAT_Id] => 9
          )
          [1] => Array (
               [AVA_Date] => Array (
                    [0] => 2019-04-20
                    [1] => 2019-04-21
               )
               [ROO_Id] => 100
               [RAT_Id] => 10
          )
     )
)

Demo on 3v4l.org

A: There is absolutely no reason to be making all of those iterated function calls.
Use a nested loop to iterate the subset of data for each room, group on the room "rate id", and push all "available date" values into a subarray in the respective group.  When the subset of data is fully iterated, push its grouped data into the result array.
Code: (Demo)
$result = [];
foreach ($newArr as $rooId => $rows) {
    $groups = [];
    foreach ($rows as $row) {
        if (!isset($groups[$row['RAT_Id']])) {
            $row['AVA_Date'] = (array) $row['AVA_Date'];
            $groups[$row['RAT_Id']] = $row;
        } else {
            $groups[$row['RAT_Id']]['AVA_Date'][] = $row['AVA_Date'];
        }
    }
    $result[$rooId] = array_values($groups);
}
var_export($result);

Output:
array (
  100 =>
  array (
    0 =>
    array (
      'AVA_Date' =>
      array (
        0 => '2019-04-18',
        1 => '2019-04-22',
      ),
      'ROO_Id' => 100,
      'RAT_Id' => 9,
    ),
    1 =>
    array (
      'AVA_Date' =>
      array (
        0 => '2019-04-20',
        1 => '2019-04-21',
      ),
      'ROO_Id' => 100,
      'RAT_Id' => 10,
    ),
  ),
)


text:
Q: Data-defined override in SLD possible? In QGIS I can adjust the width of a linestring layer by data-defined override using the values (in meters) of the attirbute table.

I'd like to the same thing in GeoServer in  a SLD file. Is that possible? I didn't find anything on the web so far...

A: You can use math functions in your SLD, technically the standard restricts the places but GeoServer is very relaxed about it, so:
     <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#0000FF</CssParameter>
          <CssParameter name="stroke-width">
            <ogc:Mul><ogc:PropertyName>cat</ogc:PropertyName>
              <ogc:Literal>5</ogc:Literal>
            </ogc:Mul>
          </CssParameter>
        </Stroke>
      </LineSymbolizer>

Produces a map like this:

That's sized in pixels, but you can specify map units of Metres or Feet if you prefer.

A: If the WMS is SLD enabled (GeoServer supports this, but must be enabled by the service provider), then you can pass SLD as part of a GetMap request using either SLD_BODY (passing the SLD as url encoded content) or SLD (passing a URL pointing to an SLD file accessible to the WMS server).
You can append to existing style, or replace the style.


text:
Q: How to make a sudoku grid using HTML and CSS? Excuse me for this simple question. I have designed a sudoku grid in the following way.
Edited(Using Tables):

                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">

                     ---------------------------------------------------------
                     ---------------------------------------------------------

                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">
                    <input type="text" maxlength="1">

The CSS for the document is

#game {
    width: 600px;
    height: 600px;

    margin-top: 20px;
    margin-bottom: 100px;
    margin-left: 30px;

    position: absolute;
    display: block;
    background-color: white;
}

#grid {
    width: 378px;
    height: 395px;

    margin-left: 20px;
    margin-top: 50px;

    border: 3px solid #000000;
}

.cell input {
    display: inline-block;
    float: left;

    border: 1px solid black;
    width: 40px;
    height: 40px;

    text-align: center;
    font-size: 30px;
}

But I am unable to make every third column and third row thick so that each 3 * 3 cell block appears distinctly. Can anyone guide me? Thanks in advance.

A: Look at this answer
https://stackoverflow.com/a/19699482/1897572
And check the result here http://jsfiddle.net/plinuxke/j6t5c/

Sudoku of the day

  <colgroup><col><col><col>
  <colgroup><col><col><col>
  <colgroup><col><col><col>

 1   3 6   4 7   9

   2     9     1

 7               6

 2   4   3   9   8

 5     9   7     1

 6       5       2

         7

 9     8   2     5

A: You can use :nth-child(n) selector to thicker some of your borders : DEMO

as for a table , you can use these CSS rules :
table {
  margin:1em auto;
}
td {
  height:30px;
  width:30px;
  border:1px solid;
  text-align:center;
}
td:first-child {
  border-left:solid;
}
td:nth-child(3n) {
  border-right:solid ;
}
tr:first-child {
  border-top:solid;
}
tr:nth-child(3n) td {
  border-bottom:solid ;
}

A: First of all you need to move the floating logic to the cell class, not the input, and you need to set the display property to block, inline blocks have unstyleble margins, which in this case are not convenient at all
.cell{
  display: block;
  float: left;
  width: 40px;
  height: 40px;
}

Then you can use :nth-child(3n+1) to clear the floats after every third element
.cell:nth-child(3n+1){
  clear:both;
}

.cell input {
  text-align: center;
  font-size: 30px;
  width:40px;
  height:40px;
  display:block;
  border: 1px solid black;
}

http://jsfiddle.net/jcferrans/G5U8s/1/
Hope it helps!

A: Here is another way:


text:
Q: Finding basis for image and kernel of A = [x+y,x-y,x+z,x-z,x+y+z] Here is a problem I'm trying to solve:
Knowing that vectors $\mathbf{x}, \mathbf{y}, \mathbf{z} \in \Bbb{R}^{2013}$ are linearly independent, find basis for image and kernel of
$$A=[\mathbf{x+y},\mathbf{x-y},\mathbf{x+z},\mathbf{x-z},\mathbf{x+y+z}]$$
I've been able to find the basis for image of $A$: The columns in $A$ are linear combinations of $\mathbf{x,y,z}$, ($\mathbf{x}=\frac{1}{2}((\mathbf{x+y})+(\mathbf{x-y}))$, and then $\mathbf{y} = \mathbf{x+y-x}, \mathbf{z}=\mathbf{x+z-x}$, so $im (A) = span (\mathbf{x,y,z})$.
But when it goes to the kernel I have no idea what to do - vectors are abstract so the algorthm doesn't work. All I've came up with is that it's dimension must be $5-rank A=5-3=2$, but what to do next?

A: $u = [u_1,u_2,u_3,u_4,u_5]^T \in ker(A)$ if and only if
$$ u_1 (\mathbf{x+y}) + u_2 (\mathbf{x-y}) + u_3 (\mathbf{x+z}) + u_4 (\mathbf{x-z})
   +u_5 (\mathbf{x+y+z}) = 0. $$
Now you can rearrange the left hand side by $\mathbf{x}, \mathbf{y}, \mathbf{z}$, i.e.
$$ (u_1+u_2+\dots+u_5)\mathbf{x} + (u_1-u_2+u_5)\mathbf{y} + (u_3-u_4+u_5)\mathbf{z} = 0. $$
As $\mathbf{x}, \mathbf{y}, \mathbf{z}$ are linearly independent, you get
$$ u_1 + \dots + u_5 = 0, \quad u_1-u_2+u_5=0, \quad u_3-u_4+u_5 = 0. $$
Now you need to find a basis for the subspace of $R^5$ defined by this
system of equations.

A: Consider the linear map $f\colon\mathbb{R}^3\to\mathbb{R}^{2013}$ defined by $f(e'_1)=x$, $f(e'_2)=y$ and $f(e'_3)=z$, where $\{e'_1,e'_2,e'_3\}$ is the standard basis of $\mathbb{R}^3$. Then $f$ is injective, because its image has dimension $3$.
Consider also $g\colon\mathbb{R}^5\to\mathbb{R}^3$ defined by
\begin{align}
g(e_1)&=e'_1+e'_2\\
g(e_2)&=e'_1-e'_2\\
g(e_3)&=e'_1+e'_3\\
g(e_4)&=e'_1-e'_3\\
g(e_5)&=e'_1+e'_2+e'_3
\end{align}
where $\{e_1,e_2,e_3,e_4,e_5\}$ is the standard basis of $\mathbb{R}^5$.
Then the matrix of $f\circ g$ with respect to the standard bases on $\mathbb{R}^3$ and $\mathbb{R}^{2013}$ is $A$. Since $f$ is injective, the kernel of $f\circ g$ is the same as the kernel of $g$ and the matrix of $g$ (with respect to the standard bases) is
$$
B=\begin{bmatrix}
1 & 1 & 1 & 1 & 1\\
1 & -1 & 0 & 0 & 1\\
0 & 0 & 1 & -1 & 1
\end{bmatrix}
$$
An easy elimination gives the RREF
$$
U=\begin{bmatrix}
1 & 0 & 0 & 1 & 1/2\\
0 & 1 & 0 & 1 & -1/2\\
0 & 0 & 1 & -1 & 1
\end{bmatrix}
$$
which corresponds to the equations
$$
\begin{cases}
x_1=-x_4-\frac{1}{2}x_5\\
x_2=-x_4+\frac{1}{2}x_5\\
x_3=x_4-x_5
\end{cases}
$$
so a basis for the kernel is
$$
\left\{
\begin{bmatrix}
-1\\
-1\\
1\\
1\\
0
\end{bmatrix},
\begin{bmatrix}
-1/2\\
1/2\\
-1\\
0\\
1
\end{bmatrix}
\right\}
$$


text:
Q: MapReduce on Hadoop - sending data from the Mapper to the Reducer I'm trying to implement a MapReduce algorithm for a specific problem. Let's say that in my Mapper I need to handle a large-sized Text Object. My question is summarised in the following example. I have the Text Object: Today is a lovely day and I need to do some processing on the words. So I have two options:

*

*I can send to the Reducer key-value pairs of the form:
<1,Today>

<1,is>

<1,a>

<1,lovely>

<1,day>

*I can send the key-value pair <1,Today is a lovely day> to the reducer and then process it, e.g. tokenise the String object.
What is the best approach for this case? In the first case I have to send more data to the reducer but I have no String Object to tokenise as in the second case. However in the second case, I have a smaller amount of data sent by the Mapper.

A: I don't think that you will heavily improve your performance by reducing traffic that way. What is really matter here is that in first case all your data will be grouped before entering to the reducer by word resulting a completely different set of key-value pairs comparing to the second option. I'm not sure you will be able to perform the same operations upon them. Lets say you will have:
<Today is a lovely day>
<Today is another lovely day>

In first case your reducer would operate with grouped  pairs of words (assuming that key is word but not a number):
<a, 1>

<another, 1>

<day, 2>

<is, 2>

<lovely,2>

<Today, 2>

As you can see reducer input is grouped and sorted, in more advanced scenarios you perform your logic upon values of such input, like finding maximum or searching average.
In second case your keys would be sentences:
<Today is a lovely day, 1>

<Today is another lovely day, 1>

So there is a chance that two different reducers would handle these two pairs. The operations which you can perform upon it would be slightly different from the first one as it would be a different set of data. There is no way how you will be able to perform key-based maximums or average of values like it is done in first case


text:
Q: Undefined reference in single file? So I understand that usually this error occurs when files aren't linked propely. The problem is I'm getting this from a single file, where things are being declared (no external files related to the function, this is all in one file):
For example:
inline SDL_Surface *ImgLoader(char *file,bool bCKey, int r , int g , int b , int alpha)
{
    SDL_Surface *pic;
    pic = IMG_Load(file); // From SDL_image.h , load the image to pic
    if(pic==NULL) fprintf(stderr,"Missing image %s : %s\n",file,IMG_GetError());
    if( bCKey ) {
        SDL_SetColorKey(pic,SDL_SRCCOLORKEY|SDL_RLEACCEL,SDL_MapRGB(pic->format,r,g,b));
        }
    if(alpha) SDL_SetAlpha(pic, SDL_SRCALPHA|SDL_RLEACCEL , 255 - alpha);
    pic = SDL_DisplayFormat(pic);
    return (pic);
}

Its usage:
anim[0] = ImgLoader("./anim/justice1.gif",1,255,255,255,230);

Why is this  occuring if the declaration of there?
EDIT: Sorry the error:

undefined reference to `ImgLoader'

P.S. I know this is related to SDL, but I think this is more of a C related query than for games specifically.


text:
Q: Object Oriented Python for area of triangle enter image description hereWrite a Python Program(with class concepts) to find the area of the triangle using the below
formula.
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

Function to take the length of the sides of triangle from user should be defined in the parent
class and function to calculate the area should be defined in subclass.
in the image the code that i have tried. but getting error. please help.``
`
class poly:
    def _init_(self,a,b,c):
        self.a = float(a)
        self.b = float(b)
        self.c = float(c)
a= input("a=")
b= input("b=")
c= input("c=")

class triangle(poly):
    def get_area(self):
        s = (a + b + c) / 2
        return (s*(s-a)*(s-b)*(s-c)) ** 0.5

t = triangle(a,b,c)
print("area : {}".format(t.area()))

`

A: w = 2
h = 4
area = 0.5 * (w * h)
print('the area of a triangle with a width of 2 and a height of 4 is ' + area)

that is how to make python find the area of a triangle

A: class poly:
    def __init__(self,a,b,c):
        self.a = float(a)
        self.b = float(b)
        self.c = float(c)
a= int(input("a="))
b= int(input("b="))
c= int(input("c="))

class triangle(poly):
    def __init__(self,a,b,c):
        super().__init__(a,b,c)

    def get_area(self):
        s = (a + b + c) / 2
        return (s*(s-a)*(s-b)*(s-c)) ** 0.5

t = triangle(a,b,c)
print("area : {}".format(t.get_area()))

I noticed a lot of errors. First __init__ has two underscores( _ ) and not one. In python 3 input returns a string so you need to typecast to int before doing arithmetic operations,else you will get TypeError. Third you did not call init method to reference the superclass. Last the function you wrote is get_area and not area.
Hope so it solves your problem. Welcome to Stackoverflow!!

A: Try this
class poly:
    def __init__(self, a, b, c):
        self.a = float(a)
        self.b = float(b)
        self.c = float(c)
        self.area = 0

class triangle(poly):
    def __init__(self, a, b, c):
        poly.__init__(self, a, b, c)

    def calculate_area(self):
        s = (self.a + self.b + self.c) / 2
        self.area = float((s * (s - self.a) * (s - self.b) * (s - self.c))) ** 0.5

    def get_area(self):
        return self.area

a, b, c = input("a = "), input("b = "), input("c = ")

t = triangle(a, b, c)
t.calculate_area()
print("area : {}".format(t.get_area()))

A: Try this one
class geometry:
    def __init__(self, a, b, c):
        self.a = float(input("a = "))
        self.b = float(input("a = "))
        self.c = float(input("a = "))

class triangle(geometry):
    def __init__(self, a, b, c):
        super().__init__(a, b, c)

    def area_triangle(self):
        s = (self.a + self.b + self.c) / 2
        return  float((s * (s - self.a) * (s - self.b) * (s - self.c))) ** 0.5

t = triangle(a, b, c)
print("area : {}".format(t.area_triangle()))

A: class Sides:
    def __init__(self,a, b, c):
        self.a = a
        self.b = b
        self.c = c

class A(Sides):
    def area(self):
        s = (self.a + self.b + self.c)/2
        return (s*(s-self.a)*(s-self.b)*(s-self.c)) ** 0.5

t = A(20,30,40)

print("area of Triangle : {}".format(t.area()))

A: class sides:
    def __init__(self,a,b,c):
        self.a=a
        self.b=b
        self.c=c

class triangle(sides):
    def area(self):
        s=(self.a+self.b+self.c)*0.5
        return float((s * (s - self.a) * (s - self.b) * (s - self.c))) ** 0.5

a, b, c = float(input("a = ")), float(input("b = ")), float(input("c = "))
t=triangle(a,b,c)
print('area of triangle is ', t.area())

A: class poly:
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c

class triangle(poly):
    def get_area(self):
        s = (self.a + self.b + self.c) / 2
        return float((s*(s-self.a)*(s-self.b)*(s-self.c))) ** 0.5

a, b, c = float(input("a = ")), float(input("b = ")), float(input("c = "))
t = triangle(a,b,c)
print("area : {}".format(t.get_area()))


text:
Q: KDE is not running script at start I created a .sh file to mount my drives via rclone.
The script has a shebang, correct permissions and works in terminal when I execute it directly.
Yet even if I add it to the autostart, login scripts in settings it does not get executed. While something like my browser does.
#!/bin/bash

rclone mount drive: ~/Documents/drive/ --vfs-cache-mode full &

Any ideas as to why kde is not running it properly?
Fedora 35 KDE spin.


text:
Q: Hadoop rack topology In Hadoop I've read that the rack topology can be configured by supplying IP addresses of the racks or their associated host names.
Does that mean that within one Hadoop cluster you could theoretically have different racks in completely separate geographical locations as long as they are reachable (can be pinged) from the NameNode?
If that is the case I would assume the replication strategy of the blocks defined by the rack awareness algorithm would be the same.

A: Hadoop is rack-aware by default, and all nodes fall under a single rack called as the /default-rack. If the cluster has multiple racks, within a datacenter or spanning across datacenters, hadoop components (especially Namenode) must be made aware of these different racks.

In Hadoop I've read that the rack topology can be configured by
  supplying IP addresses of the racks or their associated host names.

Yes, a script that can generate the mapping between the datanode's IP or hostname to a maximum of one rack will be required to configure rack topology.

Does that mean that within one Hadoop cluster you could theoretically
  have different racks in completely separate geographical locations as
  long as they are reachable (can be pinged) from the NameNode?

Yes, they should be reachable by all nodes in the cluster. But as a best practice, it is not recommended to have nodes across different geographical locations as this could increase the network latency between the nodes.

If that is the case I would assume the replication strategy of the
  blocks defined by the rack awareness algorithm would be the same.

Yes. The block placement policy is same for all variations in rack topology.


text:
Q: How to disable chrome "new window animation"? Chrome used to open new window just like that:
new window appears.
Now new windows appear with animation:
it starts with a smaller window (~80%), then it increases to full screen.
How to disable this animation?
Chrome Version 58.0.3029.81 (64-bit) on Ubuntu
(other windows appear without animations)

A: You can disable the animation by adding the --wm-window-animations-disabled command-line flag.
For Linux/Ubuntu you can make this permanent by editing the Chrome shortcut at /usr/share/applications/google-chrome.desktop. There are 3 Exec= lines where you will need to add --wm-window-animations-disabled immediately after the executable name.
If you find that this is no longer working, re-check your shortcuts as some Chrome updates (via a package manager) could have overwritten the shortcut(s), so you may need to re-edit them.

A: You can add the flag --wm-window-animations-disabled to all shortcuts used to launch Chrome with the following command:
sudo replace "Exec=/usr/bin/google-chrome-stable" "Exec=/usr/bin/google-chrome-stable --wm-window-animations-disabled" -- /usr/share/applications/google-chrome.desktop


text:
Q: Left joining only one result of corresponding table I have the following tables:

products:
id INT
title VARCHAR

offers:
id INT
product_id INT
price INT

A product can have many offers. I need to get all products with the corresponding offers with lower and higher prices, what I have is:
SELECT products.id, products.title, lowOffer.price, highOffer.price
FROM products

LEFT JOIN (SELECT offers.product_id, MIN(offers.price) AS price FROM offers GROUP BY offers.product_id) AS lowOffer ON (lowOffer.product_id = products.id)

LEFT JOIN (SELECT offers.product_id, MAX(offers.price) AS price FROM offers GROUP BY offers.product_id) AS highOffer ON (highOffer.product_id = products.id)

Now, I'm doing two subqueries, and I think I could have only one, because the two joins are working on the same set of offers. How can I do this?
My business logic is a little more complicated than this and the offers itself have relations and I'm gonna have to bring them too. How can I do this in a efficient way? I don't want to make the joins without needing to.

A: You can left join, and then use GROUP BY on the top level:
SELECT
    p.id
,   p.title
,   MIN(o.price) as min_price
,   MAX(o.price) AS max_price
FROM products p
LEFT JOIN offers o ON o.product_id = p.id
GROUP BY p.id, p.title


text:
Q: igraph graph.lattice for all combinations (in R) Greetings:  This graph seems like something that should be pretty straightforward using the igraph package for R.  I am trying to figure out which arguments I need to pass to obtain the edges between sub-patterns and super-patterns.  In this example, a item set of 5 items is represented.

I am sure this is solved with the graph.lattice function in igraph but I haven't figured out the arguments to pass.  Please note that the graph presented comes from Data Mining: Concepts and Techniques (Han, Kamber, & Pei, 2011).
Thanks in advance for any guidance.

A: I don't think the graph.lattice is capable of creating this kind of graph. But you can define a new function:
graph.comb <- function(word) {
  # creates graph objects from character combination in word
  # example graph.comb("abc")

  do_layer <- function(words) {
    do.call( rbind, lapply(words, function(word){
      l_vec <- sapply(seq_len(nchar(word)), function(l) substring(word, l, l))
      w_comb <- apply(combn(l_vec, nchar(word)-1), 2, paste, collapse = "")
      w_df <- expand.grid(from = w_comb, to = word, stringsAsFactors = FALSE)
    }))
  }

  df_edges <- data.frame(from = word, to = NA, stringsAsFactors = FALSE)
  df2 <- df_edges
  while( min(nchar(df_edges$from)) > 0) {
    df2 <- do_layer(df2$from)
    df_edges <- rbind(df_edges, df2)
  }
  df_edges <- df_edges[complete.cases(df_edges), ]
  df_edges <- df_edges[!duplicated(df_edges), ]
  return(graph.data.frame(df_edges ))
}

Use it with any character string:
g1 <- graph.comb("abcd")
plot(g1, layout = layout.sugiyama(g1)$layout )

Result:


text:
Q: 'More hot questions' JS is broken in the new nav When I try to click the 'more hot questions' link at the bottom of the sidebar on SO or mSE (with the new navigation), it just bumps me to the top of the page and doesn't do anything. Nothing in the error console. This only seems to affect the front page of sites, upon further testing.
Safari 9 on OS X 10.11.


text:
Q: How to wrap up a function with a refinement so the refinement isn't required? I am trying to wrap up functions with refinements in a generic way so they can be called without the refinement.  For instance, ARRAY-INITIAL size value instead of ARRAY/INITIAL size value
wrap: function [refined [path!] args [block!]] [
    function args compose [
        (refined) (args)
    ]
]

array-initial wrap 'array/initial [size value]

Not too fancy.  Seems to work in general, but this has something weird if you call it using a function:
>> n: 0 array/initial 4 does [++ n]
== [10 11 12 13]

>> n: 10 array-initial 4 does [++ n]
== [10 10 10 10]

When I source it I get this:
>> source array-initial
array-initial: make function! [[size value][array/initial size value]]

Okay, so what's happening is that the function is being called in the wrapper and the result of the call passed...not the function.  One workaround would be to use a get-word to avoid the evaluation:
>> array-initial-2: function [size value] [array/initial size :value]

>> array-initial-2: 10 array-initial-2 4 does [++ n]
[10 11 12 13]

But I was looking for a general approach.  What's the best way to proxy the parameters without having this happen?

A: I believe the general approach is that you do have to account for the way words are used within function arguments and as passed to functions.
wrap: func [
    'refined [path!]
    args [block!]
][
    func map-each arg args [
        either get-word? :arg [to word! arg] [:arg]
    ] compose [
        (refined) (
            map-each arg args [
                either lit-word? :arg [to get-word! arg] [:arg]
            ]
        )
    ]
]

There are two issues here—the words that define the function, and the words passed to the function. The former come in two main forms: word! for normal arguments and lit-word! for literal arguments. In our spec, if we have get-word! arguments, we want them to be normal arguments and convert to word!. When it comes to passing arguments, again we have two forms: word! to evaluate the argument and get-word! to pass the value the word points to. If our spec handles a lit-word!, we need to pass a get-word! as a word! will be passed literally.
Hopefully that all makes sense!
Anyway, how this plays out is:
wrapped-foobar: wrap foo/bar ['literal evaluated :referred]

We have our three types, the first allows you to pass values through literally—such as words without using lit-words; the second evaluates the argument before passing; and the third will pass the referred value—this form allows you to pass through functions. You end up with:
make function! [
    ['literal evaluated referred] [
        foo/bar :literal evaluated :referred
    ]
]

Now the likes of array/initial is on:
array-initial: wrap array/initial [size :value]
n: 1
array-initial 4 does [++ n]

A: This was a fascinating exercise, gotta love SO.
Turns out you actually need a "do reduce" to wrap functions with get-word arguments ...
R3 only at the moment:
unrefine: func [
  "Return an equivalent function with the given refinements wired in."
  refined [any-path! block!] "The function, with the refinements to include."
  /local ospec spec body found p s w b r
] [
  ospec: spec-of get first refined: to lit-path! :refined
  body: append copy spec: make block! length? ospec copy/deep [do reduce []]
  append/only body/3 :refined
  parse ospec [
    set s 0 1 string! (all [s append spec s])
    any [
      set w [word! | get-word! | lit-word!] (
        append spec :w
        append body/3 either word! = type? :w [reduce ['quote to get-word! w]][w])
      set b 0 1 block! (
        all [b append/only spec copy b])
      set s 0 1 string! (
        all [s append spec copy s])
    |
      /local to end
    |
      set r refinement! (
        p: any [p tail spec]
        if not found: find next refined r [append spec r])
      set s 0 1 string! (all [not found s append spec copy s])
      any [
        set w [word! | get-word! | lit-word!] (
          either found [p: insert p :w][append spec :w]
          append body/3 either word! = type? :w [reduce ['quote to get-word! w]][w])
        set b 0 1 block! (
          all [b either found [p: insert/only p copy b][append/only spec copy b]])
        set s 0 1 string! (
          all [s either found [p: insert p copy s][append spec copy s]])
      ]
    ]
  ]
  func spec body
]

A: Simply put, you (a.k.a. me) cannot accomplish this without reflecting the function arguments block that you are wrapping.  There is no other way.
If a function uses the lit-word form or the get-word form of an argument, that distinction must be mirrored in your wrapper.  See this answer for the explanation of what the difference is between the :foo and 'foo form of parameter:
Why doesn't Rebol 3 honor quoted function parameters that are parenthesized?
Per @rgchris's comment, what you (a.k.a. I) need to do is parse the argument block.  A proper answer would contain code that does this, so people should feel free to add that.


text:
Q: ANDROID - Launch other application from a BroadcastReceiver I need to launch/open one installed apk in my device from a BroadcastReceiver.
Here is the code:
public class C2DMMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    Log.w("C2DM", "Message Receiver called");
    if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
        Log.w("C2DM", "Received message");
        ComponentName toLaunch = new ComponentName("es.mypackage","es.mypackage.myapplication");
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setComponent(toLaunch);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);

My device receives the broadcast but fails with an unexpected problem.
The code to launch other apk works fine in other part of the application.
Is possible to launch other application from a broadcast?
Thank you very much.

A: As per my experience , you can not start activity from the C2DM Receiver, I found work around for that, Create one service and start activity from that service, stop service after you start the activity.
Thank You,


text:
Q: Compiled query returns the same thing every time I have this compiled query:
private static Func<DBContext, Foo> FooQuery = CompiledQuery.Compile<DBContext, Foo>(
    _db => _db.FooTable.SingleOrDefault(f => f.DeletionDate == null || f.DeletionDate > DateTime.UtcNow)
);

When I run it once, it returns the expected Foo object.
But then, even after that object's DeletionDate is set in the db, it still returns the same object -- I am expecting null. (It returns null, as expected, after recycling the app pool.)
For some reason, it works when I use the following compiled query instead (and pass in DateTime.UtcNow), but I'm not sure why.
private static Func<DBContext, DateTime, Foo> FooQuery = CompiledQuery.Compile<DBContext, DateTime, Foo>(
    (_db, now) => _db.FooTable.SingleOrDefault(f => f.DeletionDate == null || f.DeletionDate > now)
);

A: When you pass in DateTime.UtcNow in the compiled query, you are setting a constant date as part of the SQL. But when you pass in a parameter, you are creating a parameterized query in which the parameter (i.e. the date) can change each time you call it.
When you recycle the App Pool, you're recompiling the query all over again.
Check out the generated SQL and you'll see what I'm talking about.


text:
Q: In C++ is there an idiomatic way to guard against the situation in which running a collection of actions causes the collection to be mutated? Say you have a class foo that wraps a collection of some kind of callable objects. foo has a member function run() that iterates over the collection and calls each function object. foo also has a member remove(...) that will remove a callable object from the collection.
Is there an idiomatic, RAII-style guard you can put in foo.run() and foo.remove(...) such that the removes that were driven by a call to foo.run()
 will be deferred until the guard's destructor fires? Can it be done with something in the standard library? Does this pattern have a name?
My current code seems inelegant so am looking for a best practice type solution.
Note: this is isnt about concurrency. A non thread-safe solution is fine. The issue is with re-entrancy and self-reference.
Here is an example of the problem, sans the inelegant "defer remove" guard.
class ActionPlayer
{
private:
    std::vector<std::pair<int, std::function<void()>>> actions_;
public:
    void addAction(int id, const std::function<void()>& action)
    {
        actions_.push_back({ id, action });
    }

    void removeAction(int id)
    {
        actions_.erase(
            std::remove_if(
                actions_.begin(),
                actions_.end(),
                [id](auto& p) { return p.first == id; }
            ),
            actions_.end()
        );
    }

    void run()
    {
        for (auto& item : actions_) {
            item.second();
        }
    }
};

then elsewhere:
...

ActionPlayer player;

player.addAction(1, []() {
    std::cout << "Hello there" << std::endl;
});

player.addAction(42, [&player]() {
    std::cout << "foobar" << std::endl;
    player.removeAction(1);
});

player.run(); // boom

Edit ... okay this is how I can see to do this via an RAII lock object. The following should handle actions throwing and re-entrant calls to run within run assuming the recursion eventually terminates (if not that is the user's fault). I used cached std::functions because in the real version of this code the equivalent of addAction and removeAction are template functions which cant just be stored in a vanilla homogeneously typed container.
class ActionPlayer
{
private:

    std::vector<std::pair<int, std::function<void()>>> actions_;
    int run_lock_count_;
    std::vector<std::function<void()>> deferred_ops_;

    class RunLock
    {
    private:
        ActionPlayer* parent_;
    public:
        RunLock(ActionPlayer* parent) : parent_(parent) { (parent_->run_lock_count_)++; }
        ~RunLock()
        {
            if (--parent_->run_lock_count_ == 0) {
                while (!parent_->deferred_ops_.empty()) {
                    auto do_deferred_op = parent_->deferred_ops_.back();
                    parent_->deferred_ops_.pop_back();
                    do_deferred_op();
                }
            }
        }
    };

    bool isFiring() const
    {
        return run_lock_count_ > 0;
    }

public:
    ActionPlayer() : run_lock_count_(0)
    {
    }

    void addAction(int id, const std::function<void()>& action)
    {
        if (!isFiring()) {
            actions_.push_back({ id, action });
        } else {
            deferred_ops_.push_back(
                [&]() {
                    addAction(id, action);
                }
            );
        }
    }

    void removeAction(int id)
    {
        if (!isFiring()) {
            actions_.erase(
                std::remove_if(
                    actions_.begin(),
                    actions_.end(),
                    [id](auto& p) { return p.first == id; }
                ),
                actions_.end()
            );
        } else {
            deferred_ops_.push_back(
                [&]() {
                    removeAction(id);
                }
            );
        }
    }

    void run()
    {
        RunLock lock(this);
        for (auto& item : actions_) {
            item.second();
        }
    }
};

A: Usual way is to create a copy of the vector. But this may cause the removed actions to be run again.
void run()
{
    auto actions_copy{actions_};
    for (auto& item : actions_copy) {
        item.second();
    }
}

Other options if running removed action is not allowed

*

*Add a bool to store if some action is removed

*Use shared/weak ptr

*use std::list if it is known that the current action will not be removed.

A: Add a flag to run that says you're enumerating thru actions_.  Then if removeAction is called with that flag set, you store the id in a vector for later removal.  You might also need a separate vector to hold actions that are added while enumerating.  Once you're all done iterating thru actions_, you remove the ones that want removed and add the ones that got added.
Something like
// within class ActionPlayer, add these private member variables
private:
    bool running = false;
    std::vector<int> idsToDelete;

public:
    void run() {
        running = true;
        for (auto& item : actions_) {
            item.second();
        }
        running = false;
        for (d: idsToDelete)
            removeAction(d);
        idsToDelete.clear();
    }

    // ...

You can make a similar change for deferred addAction calls (which you'll need to do if any of the actions can add an action, since the add might cause the vector to allocate more storage, invalidating all iterators to the vector).

A: I would modify the structure slightly. Instead of allowing ActionPlayer to be modified directly, I would force all modifications through an external modifier class. In this example I made it an abstract Modifier class which can have different concrete implementations (e.g. DeferredModifier, InstantModifier, NullModifier, LoggedModifier, TestModifier .etc.). Your actions now only need to take a reference to the abstract base class of a modifier and call any add/remove .etc. function on that as necessary.. This allows separation of modification policy from the action implementation, and injection of different modification policies into actions.
This should also allow simpler support for concurrent modification, as you no longer need to toggle the run /  not running state to defer modifications.
This example shows a simple way of replaying the actions in order (which is a property I assume you want to maintain). A more advanced implementation could scan the modification list backwards removing all add/remove pairs and then group modifications / removals to minimise copying when modifying the actions list.
Something like:
class ActionPlayer {
friend class Modifier;
...

    void run(Modifier &modifier) { }
private:
    void addAction(...) { ... }
    void removeAction(...) { ... }
}

class Modifier
{
public:
    virtual ~Modifier() {}
    virtual addAction(...) = 0;
    virtual removeAction(...) = 0;
}

class DelayedModifier : public Modifier
{
    struct Modification { virtual void run(ActionPlayer&) = 0; }

    struct RemoveAction : public Modification
    {
        int id;

        Removal(int _id) : id(_id) {}
        virtual void run(ActionPlayer &player) { player.removeAction(id); }
    }

    struct AddAction : public Modification
    {
        int id;
        std::function<void(Modifier&)>> action;

        AddAction(int _id, const std::function<void(Modifier&)> &_action) : id(_id), action(_action)  {}
        virtual void run(ActionPlayer &player) { player.addAction(id, action) };
    }

    ActionPlayer &player;
    std::vector<Modification> modifications;

public:
    DelayedModifier(ActionPlayer &_player) player(_player) {}
    virtual ~DelayedModifier() { run(); }

    virtual void addAction(int id, const std::function<void(Modifier&)> &action) { modifications.push_back(AddAction(id, action)); }
    virtual void removeAction(int id) { modifications.push_back(RemoveAction(id)); }

    void run()
    {
        for (auto &modification : modifications)
            modification.run(player);
        modifications.clear();
    }
};

So you now write:
ActionPlayer player;

{
    DelayedModifier modifier(player);

    modifier.addAction(...);
    modifier.addAction(...);
    modifier.run();
    actions.run(modifier);
}


text:
Q: Python: IP rotation for scraping a website I have been scraping a website with BeatifulSoup. However, after a high number of queries (around 110 thousand) my IP address got blocked. With this in mind, I have been looking into IP rotation. I tried to implement the following code that I found here:
import requests
from bs4 import BeautifulSoup
from random import choice

def proxy_generator():
    response = requests.get("https://sslproxies.org/")
    soup = BeautifulSoup(response.content, 'html5lib')
    proxy = {'https': choice(list(map(lambda x:x[0]+':'+x[1], list(zip(map(lambda x:x.text, soup.findAll('td')[::8]), map(lambda x:x.text, soup.findAll('td')[1::8]))))))}

    return proxy

def data_scraper(request_method, url, **kwargs):
    while True:
        try:
            proxy = proxy_generator()
            print("Proxy currently being used: {}".format(proxy))
            response = requests.request(request_method, url, proxies=proxy, timeout=7, **kwargs)
            break
            # if the request is successful, no exception is raised
        except:
            print("Connection error, looking for another proxy")
            pass
    return response

As you can see, this solution uses the free IPs provided at https://sslproxies.org/. However, I am just obtaining the following output:
Proxy currently being used: {'https': ' FR:118'}
Connection error, looking for another proxy
Proxy currently being used: {'https': '84.53.243.83:3128'}
Connection error, looking for another proxy
Proxy currently being used: {'https': ' IS:10'}
Connection error, looking for another proxy
Proxy currently being used: {'https': '139.180.194.41:80'}
Connection error, looking for another proxy
Proxy currently being used: {'https': '139.155.172.148:8889'}
Connection error, looking for another proxy
Proxy currently being used: {'https': ' LT:21'}
Connection error, looking for another proxy
Proxy currently being used: {'https': '186.152.139.187:10809'}
Connection error, looking for another proxy
Proxy currently being used: {'https': '213.230.69.33:8080'}
Connection error, looking for another proxy
Proxy currently being used: {'https': '169.57.1.85:80'}
Connection error, looking for another proxy

Ad infinitum! My guess is that this is happening because the IPs provided are used by a high quantity of users and hence become useless quite fast. Do you know any good alternatives for IP providers? Ideally, if they are free that´s better, but I have also seen some paid ones like Zyte.
PD: if you think that there is no need for IP rotation (e.g: I could just delay my code intentionally in order for it to appear human-like) let me know in the comments :)


text:
Q: Changing a background image upon 1st click - then changing it back again on the 2nd click with jquery I have a div element who's background image I want to change upon clicking the div - and then have the image change back to the original upon clicking once more. Div CSS code is below, showing its Class and ID:
.tab_box
{
width:2%;
height:20%;
position:absolute;
left:100%;
}

#tab_box1
{
background:url('cars.png') no-repeat center center;
background-size:120%;
-moz-background-size:120%;
-o-background-size:120%;
-ms-background-size:120%;
}

I have 3 other divs all using the same "class", then each has an individual "id" to give them seaprate images.
I tried the following j-query/css using toggleClass but its does not seem to work:
.one
{
width:2%;
height:20%;
background:url('mots.png') no-repeat center center;
background-size:120%;
position:absolute;
left:100%;
}

Any suggestions as to where I am going wrong, or what method other than toggleClass could be used to switch the image to and fro?

A: it is because of css rule precedence, the id rule has precedence over class rule.
In your case the id rule #tab_box1 is having background image set, then you are trying to change it using a class rule .one.
One nasty fix is to use !important in the class rule like
.one {
    width:2%;
    height:20%;
    background:url('http://placehold.it/32/f00000') no-repeat center center !important;
    background-size:120%;
    position:absolute;
    left:100%;
}

Demo: Fiddle
The right fix will be is to use classes instead of id here, like

sadfsdf

instead of

sadfsdf

then
.tab_box1
{
background:url('cars.png') no-repeat center center;
background-size:120%;
-moz-background-size:120%;
-o-background-size:120%;
-ms-background-size:120%;
}

Demo: Fiddle

A: This will make the div behave like a button, swapping to a different image when mouse is held down, and reverting back to the original image when mouse button is released.
$("#button1").mousedown(function() {
    $(this).css({'background-image': 'url(image2.jpg)'})
}).mousedown(function(){
    $(this).css({'background-image': 'url(image1.jpg)'})
});

HTML:

Sources/References:
CSS background-image - What is the correct usage?
changing the background image on mouse down


text:
Q: performance of calling index operator many times If we have the following code:
my_struct {
   string word;
   int num;
}

vector<my_struct> vec1;

//initialize vec1 to 1000 my_struct's

for (int i = 0; i < 1000; i++) {

   // in the loop body, is it faster to use vec1[i].word directly, or
   //store it in a variable, like so (string temp = vec1[i].word)
   //and use the variable to refer temp to instead refer to the word?
}

**edit: the above is assuming that the word at the specific index of the word will have to be accessed many times within each iteration of the loop

A: With: string temp = vec1[i].word you make a copy, so it would be slower.
Use a reference : string& temp = vec1[i].word instead to prevent the performance impact of a copy (I would do it if it can make further code easier to read).
Depending on what you actually do, a compiler might optimize these versions the exact same way. I would focus on writing readable code before optimal code (but still try not to make unnecessary copies).
Edit (bonus)
As pointed out in a comment, if you don't intent to modify the string, it is even better to write const string& temp = vec1[i].word. It will give the compiler and the future reader a hint about what you can do with your reference.

A: Check the experiment, which proves that vec1[i].word directly is faster than using a temporary variable:
linux16:/home/users/grad1459/Desktop>g++ -o foo -O3  main.cpp
linux16:/home/users/grad1459/Desktop>./foo
Without temp 1.918358000 seconds wall clock time.
With temp 2.170181000 seconds wall clock time.

Here is the minimal code, which should be compiled with optimization flag(s):
int main()
{
    const int N = 10000000;
    my_struct mystruct = { "foo", 1 };
    for (int i = 0; i < N; i++)
        vec1.push_back(mystruct);

    wallclock_t t;
    double s;

    wallclock_mark(&t);
    for (int i = 0; i < N; i++)
        vec1[i].word = "bla";
    s = wallclock_since(&t);
    printf("Without temp %.9f seconds wall clock time.\n", s);

    wallclock_t t1;
    double s1;

    wallclock_mark(&t1);
    for (int i = 0; i < N; i++) {
        string tmp = vec1[i].word;
        tmp = "bla";
    }
    s1 = wallclock_since(&t1);
    printf("With temp %.9f seconds wall clock time.\n", s1);

    return 0;
}

I minified the example, I have the time measurement approach in Time measurements.

However, I use the answer suggested by Gris, it's faster with a temporary:
Without temp 1.967400000 seconds wall clock time.
With temp 0.864647000 seconds wall clock time.

A: A good optimizing compiler may hoist the vec1[i] expression into a register, so it may not matter at all.
Or you could just write your code and profile it thus definitively answering your question.

A: Using vec1[i].word is faster as you do not need to assign a value to a new location in memory, you are simply referencing an existing location instead of adding/modifying anything.
However, the performance difference is very minute.


text:
Q: Data is not saved to the database when modified I am saving a record in a global variable so that later I can modify some fields and then update that record that is in my db with .save but it does not update them
Do not update them:
SQL (0.5ms)  UPDATE `workshop_managers` SET `updated_at` = '2019-01-05 22:42:56' WHERE `workshop_managers`.`id` = 11

My code:
I get the data:
            workshop = concept_payment.concept
            @workshop_manager = WorkshopManager.lock(true).find(workshop[:id])
            if (@workshop_manager.available_quantity - concept_payment.amount) >= 0
              used_quantity = @workshop_manager.used_quantity + concept_payment.amount
              available_quantity = @workshop_manager.available_quantity - concept_payment.amount

              @workshop_manager.used_quantity = used_quantity
              @workshop_manager.available_quantity = available_quantity

              @workshop_manager.save

            end

I tried this but it does not work either:
@workshop_manager.update_attributes(used_quantity: used_quantity, available_quantity: available_quantity)

A: It looks that no @workshop_manager attribute is changed before saving. The most probably reason is that  concept_payment.amount is 0, so you don't change the quantities, so they're not saved. Ensure that concept_payment.amount is nonzero.


text:
Q: Duplicate disk shows in explorer, not in disk management I have a case where a duplicate of one of my drive somehow gets listed in my file explorer.
As per below, the file explorer and get-psdrive will show an H: drive that is the same as K:
Also this H: drive doesn't show in HKLM>SYSTEM>MountedDevices
I logged in with a new users and the letter doesn't appear right away, somehow this H: drive will show up after a few minutes after log in.
Also doing file activities, on one or the other does show up on the other...so yes it is the same drive.
FYI, this computer is a windows 2008R2
What could this be?!?

> get-psdrive -PSProvider filesystem

WARNING: column "CurrentLocation" does not fit into the display and was removed
.

Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
A                                      FileSystem    A:\
C                  78.46         57.51 FileSystem    C:\
D                  31.38        268.61 FileSystem    D:\
E                                      FileSystem    E:\
F                 521.57        178.43 FileSystem    F:\
H                 127.25         72.75 FileSystem    H:\
K                 127.25         72.75 FileSystem    K:\
L                1125.65        174.35 FileSystem    L:\

PS C:\Users\Administrator> diskpart

Microsoft DiskPart version 6.0.6002
Copyright (C) 1999-2007 Microsoft Corporation.
On computer: XXXXX

DISKPART> list disk

  Disk ###  Status      Size     Free     Dyn  Gpt
  --------  ----------  -------  -------  ---  ---
  Disk 0    Online       136 GB      0 B
  Disk 1    Online       300 GB      0 B
  Disk 2    Online      1300 GB      0 B
  Disk 3    Online       700 GB      0 B
  Disk 4    Online       200 GB      0 B

DISKPART> list volume

  Volume ###  Ltr  Label        Fs     Type        Size     Status     Info
  ----------  ---  -----------  -----  ----------  -------  ---------  --------
  Volume 0     E                       CD-ROM          0 B  No Media
  Volume 1     C                NTFS   Partition    136 GB  Healthy    System
  Volume 2     D   Shadow_Copi  NTFS   Partition    300 GB  Healthy
  Volume 3     L   Clients   NTFS   Partition   1300 GB  Healthy
  Volume 4     F   Files_Se  NTFS   Partition    700 GB  Healthy
  Volume 5     K   VM        NTFS   Partition    200 GB  Healthy


text:
Q: My promise returns the same value every time it's called despite having different data? So first the getCart function is called in b-navbar.component.ts:
export class BNavbarComponent implements OnInit{
  appUser: any;
  cart$ : Observable<ShoppingCart | null>;

  constructor(private auth : AuthService, private shoppingCartService : ShoppingCartService) {}

  async ngOnInit() {
    this.auth.appUser$.then(dataObservable => {
      dataObservable?.subscribe(data => {
        this.appUser = data
      });
    });

    this.getCart()
  }

  async getCart() {
    this.cart$ = await this.shoppingCartService.getCart()

    this.cart$.subscribe(data => {
      console.log("Nav Observable data: ", data);
    })
  }

Which looks in shopping-cart.service.ts and gets a promise of an observable:
export class ShoppingCartService {

  constructor(private db : AngularFireDatabase) { }

  private create(){
    return this.db.list("/shopping-carts").push({
      // dateCreated : new Date().getTime()
      date: "date"
    });
  }

  async getCart(): Promise<Observable<ShoppingCart>>{
    let cartId = await this.getOrCreateCartId();
    let cart = this.db.object("/shopping-carts/" + cartId);

    return new Promise((resolve) => {
      cart.valueChanges().subscribe(x => {
        let newX = x as ShoppingCart
        let items = newX.items
        resolve(of(new ShoppingCart(items)))
      })
    })
  }

  private async getOrCreateCartId() : Promise<string> {
    let cartId = localStorage.getItem("cartId");

    if (cartId) return cartId;

    let result = await this.create();
    localStorage.setItem("cartId", result.key as string);
    return result.key as string;
  }
}

Now the issue arises when interpolate the values in my html, since the observable returned in the getCart promise resolves a "static" observable, meaning it terminates the observable when resolved, thus the data is never updated. Please help :))
<a class="navbar-item" routerLink="/shopping-cart">
    Shopping Cart
    <span *ngIf = "cart$ | async as cart" class="tag is-warning is-rounded" >
        {{ cart.totalItemsCount }}
    </span>
</a>

A: Once your promise gets resolved, it doesn't "emit" anything after that. This is one key difference between promises and obsevables. Observables can emit more values even after they emit the first.
So, you should make your getCart return just the observable stream:
import { map } from 'rxjs';

// rest of your code

async getCart(): Promise<Observable<ShoppingCart>>{
  let cartId = await this.getOrCreateCartId();
  let cart = this.db.object("/shopping-carts/" + cartId);
  return cart.valueChanges()
    .pipe(map(x => {
      let newX = x as ShoppingCart
      let items = newX.items
      return new ShoppingCart(items)
    }))
}

This way, your promise resolves to the observable stream instead of a single value.


text:
Q: system() not working in php using windows server 2003 i have to extract the cabfile(.cab) on the server.
i am Finding such script which extract cab file but i didn't get it yet.
So now i am try to extract using cabarc.exe.
But i face the problem that when i run command throuw commandline its work fine but when i give same command to system() or exec() function in php it is not work.
code is as follow:
    $command = "c:\\exe\\cabarc X c:\\cab\\data.cab c:\\data\\";
if(($output = system($command,$return) != false)
{
  echo "$return";
}

it is not working when i use same string in commandline it works fine.
please any body help me to why it not working what to do tomake it work is ther any rights issue.
I had give the execute permission to the site.
thanks

A: The 2nd argument to the system function is passed by reference so it needs to be initialized by your code. Also, you should check for false using !== not != because it validates type in addition to value. Additionally, it looks like you've got an unbalanced parenthesis in your if statement. Try this:
$command = "c:\\exe\\cabarc X c:\\cab\\data.cab c:\\data\\";
$return = -1;
$output = system($command, $return);
if($output !== false)
{
    echo "Return value is: " . $return . "\r\n";
    echo "Output is:\r\n" . $output . "\r\n";
}

If that doesn't fix your issue, make sure the PHP user has permissions to access the file.

A: If you're using NTFS, check your file permissions and make sure the web server can run that executable, open the source file, and write the destination.

A: Another problem might be that the program is not allowed to run cmd.exe, maybe see if the IUSR account can execute this program as system needs to invoke a shell.


text:
Q: Javascript Content doesn't display until second click When I first load the page it takes two clicks to show the content but then after that, every click will either show or hide. So it works... just not right away.

function navClick() {
  var content = document.querySelector('.dropdown-content');

  if (content.style.display == 'none') {
    content.style.display = 'block';
  } else {
    content.style.display = 'none';
  }
};
.dropbtn {
  position: relative;
  float: right;
  font-size: 35px;
  color: #fff;
  margin-top: -50px;
  padding-bottom: 15px;
  ;
  margin-right: 30px;
  cursor: pointer;
  z-index: 2;
  display: nne;
}

Guitars

Drums

Amps

Gear

Featured

Find Us

What is happening here and how can I make the function work the first time a user clicks?

A: The problem is that content.style.display isn't defined, so it isn't none when you click, so it is set as none, next time through it is none so it changes to block. I would recommend using classList.toggle instead though:

function navClick() {
  var content = document.querySelector('.dropdown-content');
  content.classList.toggle('hidden');
};
.hidden {
  display: none;
}
Toggle Menu

Guitars

Drums

Amps

Gear

Featured

Find Us

A: I think it happens because ul tag doesn't have style attribute, so you can add it as follow:

You can also change in css:
display: nne;

to
display: none;


text:
Q: Introduction page for exams2nops (r-exams) I would like to use your excellent r-exams package to create a paper and pencil exam with automatic grading. I have used exams2nops in the past for a series of schoice and mchoice questions.
However, I now need to have an exam with an introduction page where I give a table with data and some outputs from statistical software (say normality tests, Levene, etc... I can generate that with Rmd)and tell a small history about the data and the experiments involved in gathering the data.
So My Exam structure would be:
Page 1. Box for student's name and number and Answer sheet
Page 2. Introductory page with dataset and selected figures/outputs for testing assumptions (and no questions)
Page 3. Question 1.1
Page 4. Question 1.2.
...
Page k: Question n.
Would this be possible. I guess the novelty is the "intro" page ... after that is just an exams2nops file....
Thanks in advance for any ideas or thoughts...
João

A: Our solution for - let's say - 5 different versions:
Prepare your own intro with randomly generated data (i.e. Intro.Rmd). Our Intro.Rmd also saves the generated data frames in a folder named Databases. Which is then called by each exercise of the correspondent loop (i).
When rendering rmd files to pdf you must call the right LaTeX packages in your rmd's yaml header. Our case:
  - \usepackage{booktabs}
  - \usepackage{longtable}
  - \usepackage{array}
  - \usepackage{multirow}
  - \usepackage{wrapfig}
  - \usepackage{float}
  - \usepackage{colortbl}
  - \usepackage{pdflscape}
  - \usepackage{tabu}
  - \usepackage{threeparttable}
  - \usepackage{threeparttablex}
  - \usepackage[normalem]{ulem}
  - \usepackage{makecell}
  - \usepackage{xcolor}

Several folders were created:

*

*one for the generated Intros (i.e., Intros);

*one for the exams2nops generated PDFs (i.e., nops_pdf);

*one for the spitted files (i.e., subsets);

*one for the final merged versions (i.e., exams).

The loop:
for (i in 1:5) {

rmarkdown::render(input = "Intro.Rmd",output_file = paste0("Intros/Intro_v",i,".pdf"))

exams2nops(questions, n = 1, nsamp = 1, intro = "Leia as questões com atenção e MARQUE TODAS AS SUAS RESPOSTAS NA FOLHA DE RESPOSTAS! Este exame tem a duração de 60 minutos. Boa sorte!", language = "pt-PT", institution = "Análise Estatística II", title = "Época Normal: Métodos Tipo I - ",dir = "nops_pdf", name = paste0("Ex_AEII_MTI_v",i,"_"), date = "2020-12-01",encoding = "UTF-8",  blank = 0,  nchoice = 5, duplex = T, reglength = 7L, points = 4, replacement = T,schoice = list(eval = ee))

pdf_subset(input = paste0("nops_pdf/Ex_AEII_MTI_v",i,"_1.pdf"),pages = c(1,3),
           output = paste0("subsets/subset_",i,"_part1.pdf"))

pdf_subset(input = paste0("nops_pdf/Ex_AEII_MTI_v",i,"_1.pdf"),pages = c(5:pdf_length(paste0("nops_pdf/Ex_AEII_MTI_v",i,"_1.pdf"))),
           output = paste0("subsets/subset_",i,"_part2.pdf"))

pdf_combine(input = c(paste0("subsets/subset_",i,"_part1.pdf"),
                      paste0("Intros/Intro_v",i,".pdf"),
                      paste0("subsets/subset_",i,"_part2.pdf")),
            output = paste0("exams/exams_v",i,".pdf"))

}

Achim, you say that the pdf generated by the Intro.Rmd can be merged using exams2nops, can you exemplify how?

A: How to implement this depends on whether the introductory page is the same for all participants or whether it should contain different data/graphics/information for every exam.
Same information for everyone
You can use exams2pdf(..., intro = ...).

intro: character. Either a single string with the path to a .tex
file or a vector with with LaTeX code for optional
introduction text on the first page of the exam.

Note that if this LaTeX code includes graphics (or other files) these need to be included with the full path because the LaTeX code is compiled in a different (temporary) directory.
Randomized information
If different data/graphics/information should be randomly generated for every exam, then the best way to implement this is to put it into the first question. You can emphasize the different roles of the materials by structuring the content of the "Question" environment in the first exercise, say:

*

*Starting with "General information" in bold.

*Then data/graphics/information.

*Then including "First question" in bold and/or a pagebreak, e.g., via \newpage.

*Then the actual first question.

If you do so, then the main deviation from your ideal structure is that the first itemized point "1." is at the beginning of the general information and not the actual first question. But I don't think it would be worth going through setting up a completely new type of "random intro text" for exams2nops().
If you want to emphasize this to the participants so that no one overlooks the first question, you can couple it with a general intro such as:
intro <- paste(c(
  "\\textbf{\\large Important information}",
  "",
  "Please note that the first question a data set is introduced that is also used in subsequent questions. The actual first question is included below the general introducation.",
  "\\newpage"),
  collapse = "\n")
exams2nops(..., intro = intro)


text:
Q: Getting the last modification time of a directory I understand this isn't the actual "modification" time of a directory, but I need the timestamp and I'm struggling to determine how to get it.  I'm actually going to use the output of this command in a PHP script, but I can't get the time.
stat -f "%y" zip

I keep getting the message stat: cannot read file system information for '%y': No such file or directory

A: %y is used for defining the output format. You can only set the output format after the -c flag. What you want is:
stat -c %y zip

A: you could use the SplFileInfo class to get the modification time of the directory
$test = new SplFileInfo(__DIR__); //use a path to your directory
echo  $test->getMTime();
echo date('Y-m-d',$test->getMTime());

A: I prefer find over stat. Find may have better formatting options and may be more consistent and available across platforms.
find zip -maxdepth 0 -printf "%TY/%Tm/%Td %TH:%TM:%.2TS\n"
2011/11/21 13:41:36

Be sure to include -maxdepth, otherwise find will dig out all the files under the directory.


text:
Q: The output from SetTimeout function is inconsistent I am trying to create something like a Grid-Image-Box-Slider. Now what I am trying to achieve is that after a period of time (e.g 5 seconds) one of the images will be changed randomly. So, my script follows:
var currentImages = [1, 2];

(function imgCarousel() {
    var min = 1;
    var max = 6;
    currentImgSlot = pickImageSlot();
    var pickedImage = pickImage();

    setTimeout(function () {
        console.log("Image Slot: " + currentImgSlot + "
 Image: " + pickedImage);
        //var bgImgElem = document.getElementsByClassName('bg1');
        var sheet = new CSSStyleSheet();
        sheet.replaceSync('.bg' + currentImgSlot + ' {background-image: url("assets/img/' + pickedImage + '.jpg") !important}');
        document.adoptedStyleSheets = [sheet];
        return imgCarousel();
    }, 5000)
})()

function pickImageSlot() {
    var min = 1;
    var max = 2;
    var generatedImgSlot = generateRandomNumber(max, min);
    if (generatedImgSlot == currentImgSlot) {
        return pickImageSlot();
    }
    return generatedImgSlot;
}

function pickImage() {
    var min = 1;
    var max = 6;
    var generatedImg = generateRandomNumber(max, min);
    if (currentImages[currentImgSlot] == generatedImg) {
        return pickImage();
    }
    currentImages[currentImgSlot] = generatedImg;
    return generatedImg;
}

function generateRandomNumber(max, min) {
    return Math.round(Math.random() * (max - min) + min)
}

So, here you can see that inside the imgCarousel() function I am using the setTimeout to change the background-image randomly after 5 seconds and then calling the same function again recursively. So, according to this code after each five seconds only one image should be changed. But, in reality, sometimes both of the images get changed at the same time. I don't know what is causing this issue.
Any help would be much appreciated. For your convenience I am sharing my code repo here:
Git Repo
Live Demo

A: It's a bit difficult to notice, but if you pay attention, in your live demo you'll actually see that each time they both change, one returns to the default. This is because you're actually just overriding the adoptedStyleSheets property with a new array consisting only of the latest override, so your other image will simultaneously return to the primary style sheet's image (the default).
There is no problem with the setTimeout, the issue is just that you need to be able to support both images being different from the default, instead of exactly one. You already keep both images in currentImages, so each time the timeout runs you can iterate over them and set each one's image in the new adopted style sheet.
Naively, something like this might work:
    setTimeout(function () {
        console.log("Image Slot: " + currentImgSlot + "
 Image: " + pickedImage);
        //var bgImgElem = document.getElementsByClassName('bg1');
        var sheet = new CSSStyleSheet();
        for(var i = 1; i < 2; i++) {
            sheet.replaceSync('.bg' + i + ' {background-image: url("assets/img/' + currentImages[i]+ '.jpg") !important}');
        }
        document.adoptedStyleSheets = [sheet];
        return imgCarousel();
    }, 5000)

Your currentImages seems to be used with a random number between 1 and 2, but arrays are 0-based, so I'm not sure what your intended usage is there, but this should get you on the right track.


text:
Q: Prime divisors of values of a polynomial on an infinite set This may be a well known problem:
Let $f$ be a  polynomial with integer coefficients. Is it possible for the set of prime divisors of values of $f$ on an infinite set of integers, to be finite?
I  guess such a set exists  only for polynomials $f$ of the form $f(x) = c(ax+b)^n, a,b,c\in \mathbb{Z}, c\neq 0$. But I can't give a proof.
I'm specially interested in the case $f(x) = x^2+1$.
Thanks!

A: The answer is no for irreducible $f(x) \in \mathbb{Z}[x]$ of degree at least $3$. In this case, let $F(X,Y)$ be the homogenization of $f$, so that $f(x) = F(x,1)$. Let $\{p_1, \cdots, p_k\}$ be a fixed set of distinct rational primes. Then it was shown by Mahler and many subsequent authors that the equation
$$\displaystyle F(x,y) = p_1^{z_1} \cdots p_k^{z_k}$$
where $z_i$ range over all integers and $x,y$ are integers, has at most finitely many solutions, with the record
$$\displaystyle (5 \times 10^6 \deg f)^k$$
being obtained by Evertse; see
J.-H. Evertse, "The number of solutions of the Thue–Mahler equation" J. Reine Angew. Math. , 482 (1997) pp. 121–149.
Therefore, this also gives an upper bound for the number of solutions to the equation $f(x) = n$, where $n$ is a number all of whose prime divisors come from some finite set.

A: Another way would be to appeal to Faltings theorem. Indeed, if $f(n)$ has finitely many prime factors $p_1,\dots p_k$ for infinitely many $n,$ then the equation, say $$f(x)=Dy^3$$ would have infinitely many solutions for some fixed $D,$ which is a product of $\prod_{i=1}^kp_i^{\alpha_i}$ for $0\le \alpha_i\le 2.$
EDIT: since OP is interested in the case of quadratics, one can use the same reasoning as above to reduce everything to the equation
$$x^2+D=Ay^n$$
for fixed $A.$ This is Ramanujan-Nagel type equation. See https://en.wikipedia.org/wiki/Ramanujan–Nagell_equation for the description of solution.

A: Assume that it holds for, say, $x^2+1$ with given primes $p_1,\dots,p_m$. Consider factorization of $x^2+1=(x+i)(x-i)$ in Gaussian integers. For inifinitely many $x$ we have $x+i=A y^7$ for the same $A$. That is, $2i=A y^7-\bar{A} {\bar y}^7$, factor RHS in 7 multiples $A^{1/7}y-\bar{A}^{1/7}\bar{y}$. All but 1 are about $|y|$ by absolute value, hence another is about $1/|y|^6$. It means that algebraic number $(A/\bar{A})^{1/7}$ is approximated by $\bar{y}/y$ with accuracy $|y|^{-7}$. Taken real part we get approximation with the same accuracy by rational with denominator $|y|^2$. This may happen only finite number of times by Roth's theorem.

A: For $f(x)=x^2+1$, one can reach the desired conclusion by applying an elementary method of Stormer. "Elementary" means that nothing as deep as Siegel's theorem is used, just some theory of Pellian equations. Stormer's method is discussed on Wikipedia:
https://en.wikipedia.org/wiki/St%C3%B8rmer%27s_theorem
(However, there the method is explained in terms of a slightly different problem: Finding all $n$ with $n, n+1$ supported on a given finite set of primes.)
A nice reference is the paper of Lehmer cited there. You might also want to look at the following:
Najman, Filip(CT-ZAGR)
Smooth values of some quadratic polynomials.
Glas. Mat. Ser. III 45(65) (2010), no. 2, 347–355.


text:
Q: C++ I cant get my function to run in my program The Function won't initiate can someone help? When I run it in the debugger program skips over function and I don't know why?
#include <iostream>

 using namespace std;

int size_array= 0;
int *data_array;
void sorting(int *[], int);

int main()
{
cout<<"enter in array size \n";
 cin>>size_array;
int *data_array=new int(size_array);

 for(int i=0;i<size_array;i++)
  {
   cout<<"enter number "<<i+1<<endl;
   cin>>data_array[i];
  }
 **int sorting(int data_array, int size_array);**

for (int i=0; i<size_array;i++)
  {
    cout<<data_array[i]<<endl;
  }

return 0;
}

A: The marked code is simply declaring the function, not calling it.
Also, your data_array is a pointer to a single int whose value is initialized as size_array. But you want an array of size_array number of ints instead.
Try this:
#include <iostream>
using namespace std;

void sorting(int[], int);

int main()
{
    int size_array = 0;
    cout << "enter in array size \n";
    cin >> size_array;
    int *data_array = new int[size_array];

    for(int i = 0; i < size_array; i++)
    {
        cout << "enter number " << i+1 << endl;
        cin >> data_array[i];
    }

    sorting(data_array, size_array);

    for (int i = 0; i < size_array; i++)
    {
        cout << data_array[i] << endl;
    }

    delete[] data_array;
    return 0;
}

void sorting(int data_array[], int size_array)
{
    // sort data_array as needed...
}


text:
Q: Imap headerinfo multiple from addresses? In what scenario is it possible for the imap_headerinfo method to return an array with multiple from objects?
As far as i know theres only one sender right?
Example:
[from] => Array(
    [0] => stdClass Object
        (
            [mailbox] => exampel
            [host] => test.com
        )
    [1] => stdClass Object
        (
            [mailbox] => exampel2
            [host] => test.com
        )
)


text:
Q: Date format logic i got this codes for the date format. My examDateFormat is print out like this :
Jan   01 = 1
Feb   02 = 11
March 03 = 21
April 04 = 31

For example in Feb, it should show 02 but it show 11. I don't know how to fix that logic. Please help me take a look.Thanks!
    for (ExamTimetable exam: listOfExam) {
            Calendar cal = Calendar.getInstance();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
            Date date = null;

            date = format.parse(exam.getM_scheduledDate());
            cal.setTime(date); //correct date
            String examDateFormat = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + 1 + "/" + cal.get(Calendar.YEAR);

            int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
            String day = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];

            if (examDateFormat.equals(mDates)) {
                dataList.add(new ExamInfo(exam.getM_subjectFullName(), exam.getM_subjectCode(), examDateFormat + " " + "(" + day + ")", exam.getM_startTime(), exam.getM_endTime(), exam.getM_venueId(), exam.getM_seatingNo()));
            }

        }


text:
Q: Create indexed array of two-element subarrays from flat associative array Is it possible to convert this array:
array(
  'A' => 'B',
  'C' => 'D',
)

To this array:
array(
  array(
    'A',
    'B',
  ),
  array(
    'C',
    'D',
  ),
)

A: You are probably looking for the array_map (builds pairings based on existing arrays, see Example #4 Creating an array of arrays on the manual page) and the array_keys (all keys of an array) functions:
array_map(null, array_keys($array), $array));

A: $source = array(
  'A' => 'B',
  'C' => 'D',
)

foreach ($source as $key => $value){
  $result[] = array($key, $value);
}

var_dump($result);


text: Q: HTML Email Displays Incorrectly In Outlook We have been using MyEmma to do email campaigns. Everything had been work but about 2 weeks ago HTML emails have not been displaying correctly within our organization. So when I look at an email sent to my work email address using Outlook it does not display correctly. If I have the same email sent to my Gmail or Hotmail account it displays correctly. If I forward the email to my work email address from my Gmail or Hotmail it displays correctly. Everyone at work has the same display problem. Any ideas as to what would cause the problem or advice on troubleshooting would be helpful.


text:
Q: How to match a pattern, delete the pattern and also the next and the previous line on Solaris 10 How can I match a pattern, delete the pattern and also the next and the previous line on Solaris 10?
I'm hiting the wall because Solaris does not come with GNU sed.
Given the following file content:
    LinearFile(3F007F106F3B, FDN, 29, 20)
    LinearFile(3F007F106F40, XXX, 29, 1)
    {
        LinearRec(1, 12345)
    }
    LinearFile(3F007F106F3C, SMS, 176, 20)
    LinearFile(3F007F106F4F, ECCP, 15, 10)
    LinearFile(3F007F106F40, XXX, 29, 1)
    {
      LinearRec(1, FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
    }
    LinearFile(3F007F106F42, SMSP, 43, 3)
    BinaryFile(3F007F106F43, SMSS, 2)
    LinearRec(1, 12345)

I would like to remove the block that contain:
    {
      LinearRec(1, FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
    }

The file would be:
LinearFile(3F007F106F3B, FDN, 29, 20)
    LinearFile(3F007F106F40, XXX, 29, 1)
    {
        LinearRec(1, 12345)
    }
    LinearFile(3F007F106F3C, SMS, 176, 20)
    LinearFile(3F007F106F4F, ECCP, 15, 10)
    LinearFile(3F007F106F40, XXX, 29, 1)
    LinearFile(3F007F106F42, SMSP, 43, 3)
    BinaryFile(3F007F106F43, SMSS, 2)
    LinearRec(1, 12345)

To delete the next line I issued the following:
sed -e '/LinearRec(1\,\ FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)/{n;d;}' file.txt

What about the line that matchs and the previous line?
Maybe it can be achieved by using ed or vi?
Thx!

A: Here's an ed script:
ed <<\!
e file.txt
/LinearRec(1, FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
-1,+1d
w newfile.txt
!

It writes the output to file newfile.txt.

The "global" repeated version of this is
ed <<\!
e file.txt
g/LinearRec(1, FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)/-1,+1d
w newfile.txt
!

A: sed -ne'$p;N;/^ *{ *\n *LinearRec(1, *FF*) *$/n;/\n/P;D' <in >out

That gets sed a one-line look-ahead, and then only Prints to output any lines which don't fit your series, because it jumps one more and dumps the buffer when it matches the first two lines of it.

A: A perl approach (assuming your file is small enough to load into memory):
perl -0pe 's/.+?\n.*?LinearRec\(1, F{58}\).*?\n.*?\n//' file

The -0 makes perl slurp the entire file, and the -p tells it to print each input line after applying the script given by -e. The script itself matches 58 Fs and the surrounding two lines and removes them.


text:
Q: Why is my SQL Server Update stored procedure not updating my gridview? I am very new to C# so please be nice. I am doing a project where I want to create a gridview that will display records that you can search through, insert, update, cancel, and edit. The search, cancel, and edit buttons have been completed. Right now, I am struggling with the update.
I created a SQL Server stored procedure:
ALTER PROCEDURE [dbo].[_sp_Update]
    @UserNumId int,
    @UserName nvarchar,
    @UserNumber nvarchar,
    @StartDate date,
    @EndDate date
AS
BEGIN
    UPDATE USER_NUMBERS
    SET UserName = @UserName,
        UserNumber = @UserNumber,
        StartDate = @StartDate,
        EndDate =  @EndDate
    WHERE UserNumId = @UserNumId
END

Then, I created an update functionality that is not working. I click the update button, and what happens is the record is missing characters in the database, and it isn't really updated at all.
I have been doing hours long research, and I have no idea what to do.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    try
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();

            SqlCommand cmd_update = new SqlCommand("_sp_Update", con);
            cmd_update.CommandType = CommandType.StoredProcedure;

            cmd_update.Parameters.AddWithValue("@UserNumId", (GridView1.DataKeys[e.RowIndex].Value.ToString()));
            cmd_update.Parameters.AddWithValue("@UserName", (GridView1.Rows[e.RowIndex].FindControl("txtUserName") as TextBox).Text.Trim());
            cmd_update.Parameters.AddWithValue("@UserNumber", (GridView1.Rows[e.RowIndex].FindControl("txtUserNumber") as TextBox).Text.Trim());
            cmd_update.Parameters.AddWithValue("@StartDate", (GridView1.Rows[e.RowIndex].FindControl("txtStartDate") as TextBox).Text.Trim());
            cmd_update.Parameters.AddWithValue("@EndDate", (GridView1.Rows[e.RowIndex].FindControl("txtEndDate") as TextBox).Text.Trim());

            cmd_update.ExecuteNonQuery();

            GridView1.EditIndex = -1;

            PopulateGridview();

            con.Close();
        }
    }
    catch (Exception ex)
    {
        lblSuccessMessage.Text = "";
        lblErrorMessage.Text = ex.Message;
    }
}

******* I UPDATED THE CODE TO THIS - NOW NOTHING UPDATES AND I RECEIVE THIS ERROR MESSAGE - Object must implement IConvertible.
 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{
    using (SqlConnection con = new SqlConnection(connectionString))

        {

            con.Open();

            Label UserNumID =
GridView1.Rows[e.RowIndex].FindControl("lbl_UserNumID") as Label;
            TextBox UserName =
GridView1.Rows[e.RowIndex].FindControl("txtUserName") as TextBox;
            TextBox UserNumber =
GridView1.Rows[e.RowIndex].FindControl("txtUserNumber") as TextBox;
            TextBox StartDate =
GridView1.Rows[e.RowIndex].FindControl("txtStartDate") as TextBox;
            TextBox EndDate =
 GridView1.Rows[e.RowIndex].FindControl("txtEndDate") as TextBox;

            SqlCommand cmd_update = new SqlCommand("_sp_Update", con);
            cmd_update.CommandType = CommandType.StoredProcedure;

            cmd_update.Parameters.Add("@UserNumId",
SqlDbType.Int).Value=UserNumID;
            cmd_update.Parameters.Add("@UserName",
SqlDbType.VarChar).Value=UserName;
            cmd_update.Parameters.Add("@UserNumber",
SqlDbType.VarChar).Value=UserNumber;
            cmd_update.Parameters.Add("@StartDate",
SqlDbType.Date).Value=StartDate;
            cmd_update.Parameters.Add("@EndDate",
 SqlDbType.Date).Value=EndDate;

            cmd_update.ExecuteNonQuery();

            GridView1.EditIndex = -1;

            PopulateGridview();

            con.Close();

    }

        }
}


text:
Q: Is Σ* a context free language Is Σ∗ a context free grammar?
Because I wonder if I can use it to prove that if "For every language
A,if A is not context-free, then A is not context-free."

A: The language Σ* isn't a context-free grammar (a CFG is a set of rules that define a language; Σ* is a language), but it is a context-free language. There are a number of ways to see this:

*

*You could define a CFG for it. Create a simple grammar with production rules S → aS for each character a ∈ Σ, plus one last rule S → ε to stop the recursion.

*You could define a PDA for it. Have a single state which is accepting and which has a loop back to itself on any character, completely ignoring the stack.

*You can note that it's regular - Σ* is a regular expression for itself - and that all regular languages are context-free.
As to your follow-up question about whether you can use it to prove that particular statement, I assume there's a typo in what you've written there because as written it's the same statement implying itself. If you meant to say "if a language is not context-free, then it's not regular," that's true and follows from the contrapositive of the last bullet point.