text:
Q: Don't understand "assuming signed overflow" warning I am getting:

warning: assuming signed overflow does not occur when assuming that (X + c) < X is always false [-Wstrict-overflow]

on this line:
if ( this->m_PositionIndex[in] < this->m_EndIndex[in] )

m_PositionIndex and m_EndIndex of type itk::Index (http://www.itk.org/Doxygen/html/classitk_1_1Index.html), and their operator[] returns a signed long.
(it is line 37 here: https://github.com/Kitware/ITK/blob/master/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.hxx for context)
Can anyone explain what would cause that warning here? I don't see the pattern (x+c) < x anywhere - as this is simply a signed long comparison.
I tried to reproduce it in a self-contained example:
#include <iostream>

namespace itk
{
  struct Index
  {
    signed long data[2];

    Index()
    {
      data[0] = 0;
      data[1] = 0;
    }

    signed long& operator[](unsigned int i)
    {
      return data[i];
    }
  };
}
int main (int argc, char *argv[])
{
  itk::Index positionIndex;
  itk::Index endIndex;

  for(unsigned int i = 0; i < 2; i++)
  {
    positionIndex[i]++;
    if ( positionIndex[i] < endIndex[i] )
    {
      std::cout << "something" << std::endl;
    }
  }

  return 0;
}

but I do not get the warning there. Any thoughts as to what is different between my demo and the real code, or what could be causing the warning in the real code? I get the warning with both gcc 4.7.0 and 4.7.2 with the -Wall flag.

A: The compiler is telling you that it has enough static knowledge of that snippet to know that test will always succeed if it can optimize the test assuming that no signed operation will overflow.
In other words, the only way x + 1 < x will ever return true when x is signed is if x is already the maximum signed value. [-Wstrict-overflow] let's the compiler warn when it can assume that no signed addition will overflow; it's basically telling you it's going to optimize away the test because signed overflow is undefined behavior.
If you want to suppress the warning, get rid of the test.

A: Despite the age of your question, since you didn't change that part of your code yet, I assume the problem still exists and that you still didn't get a useful explanation on what's actually going on here, so let my try it:
In C (and C++), if adding two SIGNED integers causes an overflow, the behavior of the entire program run is UNDEFINED. So, the environment that executes your program can do whatever it wants (format your hard disk or start a nuklear war, assuming the necessary hardware is present).
gcc usually does neither, but it does other nasty things (that could still lead to either one in unlucky circumstances). To demonstrate this, let me give you a simple example from Felix von Leitner @ http://ptrace.fefe.de/int.c:
#include <assert.h>
#include <stdio.h>

int foo(int a) {
  assert(a+100 > a);
  printf("%d %d\n",a+100,a);
  return a;
}

int main() {
  foo(100);
  foo(0x7fffffff);
}

Note: I added stdio.h, to get rid of the warning about printf not being declared.

Now, if we run this, we would expect the code to assert out on the second call of foo, because it creates an integer overflow and checks for it. So, let's do it:
$ gcc -O3 int.c -o int && ./int
200 100
-2147483549 2147483647

WTF? (WTF, German for "Was täte Fefe" - "what would Fefe do", Fefe being the nick name of Felix von Leitner, which I borrowed the code example from). Oh, and, btw, Was täte Fefe? Right: Write a bug report in 2007 about this issue! https://gcc.gnu.org/bugzilla/show_bug.cgi?id=30475
Back to your question. If you now try to dig down, you could create an assembly output (-S) and investigate only to figure out, that the assert was completely removed
$ gcc -S -O3 int.c -o int.s && cat int.s
[...]
foo:
        pushq   %rbx             // save "callee-save" register %rbx
        leal    100(%rdi), %edx  // calc a+100 -> %rdx for printf
        leaq    .LC0(%rip), %rsi // "%d %d\n" for printf
        movl    %edi, %ebx       // save `a` to %rbx
        movl    %edi, %ecx       // move `a` to %rcx for printf
        xorl    %eax, %eax       // more prep for printf
        movl    $1, %edi         // and even more prep
        call    __printf_chk@PLT // printf call
        movl    %ebx, %eax       // restore `a` to %rax as return value
        popq    %rbx             // recover "callee-save" %rbx
        ret                      // and return

No assert here at any place.
Now, let's turn on warnings during compilation.
$ gcc -Wall -O3 int.c -o int.s
int.c: In function 'foo':
int.c:5:2: warning: assuming signed overflow does not occur when assuming that (X + c) >= X is always true [-Wstrict-overflow]
  assert(a+100 > a);
  ^~~~~~

So, what this message actually says is: a + 100 could potentially overflow causing undefined behavior. Because you are a highly skilled professional software developer, who never does anything wrong, I (gcc) know for sure, that a + 100 will not overflow. Because I know that, I also know, that a + 100 > a is always true. Because I know that, I know that the assert never fires. And because I know that, I can eliminate the entire assert in 'dead-code-elimination' optimization.
And that is exactly, what gcc does here (and warns you about).
Now, in your small example, the data flow analysis can determine, that this integer in fact does not overflow. So, gcc does not need to assume it to never overflow, instead, gcc can prove it to never overflow. In this case, it's absolutely ok to remove the code (the compiler could still warn about dead code elimination here, but dce happen so often, that probably nobody wants those warnings). But in your "real world code", the data flow analysis fails, because not all necessary information is present for it to take place. So, gcc doesn't know, whether a++ overflows. So it warns you, that it assumes that never happens (and then gcc removes the entire if statement).
One way to solve (or hide !!!) the issue here would be to assert for a < INT_MAX prior to doing the a++. Anyway, I fear, you might have some real bug there, but I would have to investigate much more to figure it out. However, you can figure it out yourself, be creating your MVCE the proper way: Take that source code with the warning, add anything necessary from include files to get the source code stand-alone (gcc -E is a little bit extreme but would do the job), then start removing anything that doesn't make the warning disappear until you have a code where you can't remove anything anymore.

A: To simply disable this warning, use -Wno-strict-overflow.  To instead disable the specific optimization that triggers this warning, use -fno-strict-overflow or -fwrapv.
The gcc manpage describes that this warning can be controlled with levels: -Wstrict-overflow=n.
If this is stopping your build due to -Werror, you can work-around without hiding the warnings by using -Wno-error=strict-overflow (or just -Wno-error to override -Werror).

Analysis and commentary...
I got the same warning and spent a couple of hours trying to reproduce it in a smaller example, but never succeeded.  My real code involved calling an inline function in a templated class, but the algorithm simplifies to the following...
int X = some_unpredictable_value_well_within_the_range_of_int();
for ( int c=0; c<4; c++ ) assert( X+c >= X ); ## true unless (X+c) overflows

In my case the warning was somehow correlated with the optimizer unrolling the for loop, so I was able to work-around by declaring volatile int c=0.  Another thing that fixed it was to declare unsigned int c=0, but I'm not exactly sure why that makes a difference.  Another thing that fixed it was making the loop count large enough that the loop wouldn't be unrolled, but that's not a useful solution.
So what is this warning really saying?  Either it is saying that the optimizer has modified the semantics of your algorithm (by assuming no overflow), or it is simply informing you that the optimizer is assuming that your code doesn't have the undefined behavior of overflowing a signed integer.  Unless overflowing signed integers is part of the intended behavior of your program, this message probably does not indicate a problem in your code -- so you will likely want to disable it for normal builds.  If you get this warning but aren't sure about the code in question, it may be safest to just disable the optimization with -fwrapv.
By the way, I ran into this issue on GCC 4.7, but the same code compiled without warning using 4.8 -- perhaps indicating that the GCC developers recognized the need to be a bit less "strict" in the normal case (or maybe it was just due to differences in the optimizer).

Philosophy...
In [C++11:N3242$5.0.4], it states...

If during the evaluation of an expression, the result is not
  mathematically defined or not in the range of representable values for
  its type, the behavior is undefined.

This means that a conforming compiler can simply assume that overflow never occurs (even for unsigned types).
In C++, due to features such as templates and copy constructors, elision of pointless operations is an important optimizer capability.  Sometimes though, if you are using C++ as a low-level "system language", you probably just want the compiler to do what you tell it to do -- and rely on the behavior of the underlying hardware.  Given the language of the standard, I'm not sure how to achieve this in a compiler-independent fashion.

A: In my case, this was a good warning from the compiler.  I had a stupid copy/paste bug where I had a loop inside a loop, and each was the same set of conditions.  Something like this:
for (index = 0; index < someLoopLimit; index++)
{
    // blah, blah, blah.....
    for (index = 0; index < someLoopLimit; index++)
    {
        //  More blah, blah, blah....
    }
}

This warning saved me time debugging.  Thanks, gcc!!!

A: I think that the compiler changed
positionIndex[i]++;
if ( positionIndex[i] < endIndex[i] )

into something more optimized like
if ( positionIndex[i]++ < endIndex[i] )   <-- see my comment below, this statement is wrong.

so
if ( positionIndex[i] + 1 < endIndex[i] )

that causes undefined behavior in case of overflow (thanks Seth).

A: This is almost certainly an error, even though I cannot tell which of three possible errors it is.
I believe, that gcc is somehow figuring out what the values in 'this->m_PositionIndex[in]' etc. are computed from, namely that both values are derived from the same value, one with an offset it can also prove to be positive. Consequently it figures, that one branch of the if/else construct is unreachable code.
This is bad. Definitely. Why? Well, there are exactly three possibilities:

*

*gcc is right in that the code is unreachable, and you overlooked that this is the case. In this case you simply have bloated code. Best of the three possibilities, but still bad in terms of code quality.

*gcc is right in that the code is unreachable, but you wanted it to be reachable. In this case, you need to take a second look at why it is not reachable and fix the bug in your logic.

*gcc is wrong, you have stumbled on a bug in it. Quite unlikely, but possible, and unfortunately very hard to prove.
The really bad thing is, that you absolutely need to either find out exactly why the code is unreachable, or you need to disprove that gcc is right (which is easier said than done). According to Murphy's law, assuming case 1. or 3. without proving it will make sure that it was case 2., and that you will have to hunt for the bug a second time...


text:
Q: Asymptotic character theory of unitary groups via shifted Schur functions In the paper "Shifted Schur Functions" http://arxiv.org/abs/q-alg/9605042 by Andrei Okounkov and Grigori Olshanski it is said that one of the motivations for that paper was the asymptotic character theory for the unitary groups $U(n)$ and symmetric groups $S(n)$ when $n\to\infty$ (this was first done by Vershik and Kerov). It is also said the detailed exposition of the main theorem of Vershik and Kerov regarding the characters of $U(\infty)$ via machinery of shifted Schur functions will be presented in the subsequent papers (see the part 4 of the introduction). However, I cannot find the exact paper (and not sure if it actually exists).
Thus, the question is: did Okounkov and/or Olshanski publish somewhere a paper with the proof of the Vershik-Kerov theorem that uses shifted Schur functions ($s^*$-functions in the notation of Okounkov and Olshanski)?
Here is the paper of Vershik and Kerov that Okounkov and Olshanski were referring to:
Vershik, A. M.; Kerov, S. V., Characters and factor representations of the infinite unitary group, Sov. Math., Dokl. 26, 570-574 (1982); translation from Dokl. Akad. Nauk SSSR 267, 272-276 (1982). ZBL0524.22017.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cognex Insight SetComment Not Persisting I have a job that stores cell locations as comments in particular cells, but I'm running into a situation where the CvsInsight::SetComment method is not persisting.
I'm displaying a form as a dialog wherein the user can change the cell locations that are stored in the comment cells and when the user clicks the save button I'm creating a new instance of a custom class, setting the properties to the new cell locations (set by the user), setting the DialogResult as OK, and then closing the form. Then in the form where I called ShowDialog, I call the SetComment method for each property in the custom class on their respective cell.
This is what I'm doing in the dialog's Save button:
Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
    ' Check if the name, username, password, pass, fail, total, reset, and results are all set
    Dim invalidFields As List(Of String) = New List(Of String)()
    For Each pair In _requiredFields
        If (String.IsNullOrWhiteSpace(DirectCast(Controls.Find(pair.Key, True).FirstOrDefault, TextBox).Text)) Then
            invalidFields.Add(pair.Value)
        End If
    Next

    If (invalidFields.Any()) Then
        MessageBox.Show($"The following required fields are missing a value: {String.Join(", ", invalidFields)}", "Invalid Form", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return
    End If

    ' Set the returned object's values, set the dialog result, and then close the dialog
    CameraSettings = New CameraSettings() With {
        .FailCell = FailCellLocation.Text,
        .FocusCell = FocusCell.Text,
        .IsVisible = Visibility.Checked,
        .PassCell = PassCellLocation.Text,
        .ResetCell = ResetCellLocation.Text,
        .ResultsCell = ResultsCellLocation.Text,
        .TotalCell = TotalCellLocation.Text
    }
    DialogResult = DialogResult.OK
    Close()
End Sub

And this is what I'm doing in the form that opens the dialog:
Private Sub Settings_Click(sender As Object, e As EventArgs) Handles Settings.Click
    Using cameraSettingsDialog As frmCameraSetting = New frmCameraSetting(InsightDisplay.InSight)
        With cameraSettingsDialog
            If (.ShowDialog = DialogResult.OK) Then
                InsightDisplay.InSight.SetComment(New CvsCellLocation(_focusCell), New CvsCellComment(.CameraSettings.FocusCell))
                InsightDisplay.InSight.SetComment(New CvsCellLocation(_passCell), New CvsCellComment(.CameraSettings.PassCell))
                InsightDisplay.InSight.SetComment(New CvsCellLocation(_failCell), New CvsCellComment(.CameraSettings.FailCell))
                InsightDisplay.InSight.SetComment(New CvsCellLocation(_totalCell), New CvsCellComment(.CameraSettings.TotalCell))
                InsightDisplay.InSight.SetComment(New CvsCellLocation(_resultCell), New CvsCellComment(.CameraSettings.ResultsCell))
                InsightDisplay.InSight.SetComment(New CvsCellLocation(_resetCell), New CvsCellComment(.CameraSettings.ResetCell))

                GetSettingCells()
            End If
        End With
    End Using
End Sub

What is happening is that the code executes without throwing any exceptions, but the comment is not set. What's frustrating is that I'm not able to debug because the CvsInsightDisplay's Insight gets set to null anytime I try to access the results in the middle of setting the comment. However, I can verify that the CameraSettings' properties are what I'd expect them to be because if I setup a Console.WriteLine to print the various properties they're right.
Looking through the SDK, I cannot find any documentation as to why it wouldn't set the value without throwing an exception.

A: For those of you who run into the same issue, the problem resolved around the fact that I was trying to set a cell that was past the maximum row in the job. To fix the issue, I had to change the cells in which I was setting the comments for to ones with a lower row index.
Unfortunately, Cognex does not have this behavior documented in any of their documentation.


text:
Q: simple login form using java and db2 . everything ok but still resultset empty I am trying to make a simple login form. Every thing is working fine, connection is established, query is executed but ResultSet is still empty so always getting redirected to fail.jsp. No error no warning at all.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    modelclass md = new modelclass();
    daoclass dao = new daoclass();
    md.setName(name);
    md.setPassword(password);
    System.out.println("this just before the sql query on the main servlet page");
    String sql = "Select * from USERADD where name = ? and password= ?";
    String result = dao.guser(md, sql);
    if (result.equals("success")) {
        response.sendRedirect("welcome.jsp");
    } else {
        response.sendRedirect("fail.jsp");
    }

}

This is the DAO class which makes connection.
Data Access code(dao.java):
public class daoclass {

    public static String username = "NickNeo";
    public static String password = "123123";
    public static String driver = "com.ibm.db2.jcc.DB2Driver";
    public static String url = "jdbc:db2://localhost:50000/CITYLIFE";
    public static Connection con = null;
    public static PreparedStatement ps = null;

    static {

        try {
            Class.forName(driver);
            System.out.println("before connection");
            con = DriverManager.getConnection(url, username, password);
            System.out.println("Connection Successfullll......!!!!!!");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    public String guser(modelclass obj, String sql) {

        try {
            System.out.println("entry into try block");
            ps=con.prepareStatement(sql);
            ps.setString(1, obj.getName());
            ps.setString(2, obj.getPassword());
            System.out.println("before query");
            ResultSet rs = ps.executeQuery();
            System.out.println("query executed");
            int i = 0;
            while(rs.next()) {
                System.out.println("entered into while loop");
                ++i;
            }
            if (i >= 1) {
                return "success";
            } else {
                System.out.println("this is inside else of while block");
                return "fail";
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
        System.out.println("this is the most outer fail statement");
        return "fail";
    }
}

the rs is always empty. tried many things but still getting rs as empty. please help


text:
Q: How could I stream the video with python in one script, and then load it and analyse with OpenCV in another? I am using this code from https://github.com/log0/video_streaming_with_flask_example to stream video from camera and make it public. I am able to do it with this code, but I need to analyse the video with OpenCV in external application, so I need to load it in that python script.
I use this code
camera.py
import cv2

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

and for main.py
from flask import Flask, render_template, Response
from camera import VideoCamera

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)

When I run the both scripts I get the page 127.0.0.1:5000 and I can see the video. What I need to do, is to stream the video like this, but to import it in some external python script that uses OpenCV to do some analysis like this
cap = cv2.VideoCapture('127.0.0.1:5000')

but it is not working, I am getting error
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:808)
warning: 127.0.0.1:5000 (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:809)
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow, file C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp, line 331
Traceback (most recent call last):

I am aware that localhost is not visible from outside, but I will put it later on the public ip as soon as I solve this to make it work without importing VideoCamera class. It is enough if it works on my computer now.


text:
Q: Command prompt that knows Java?
Possible Duplicate:
Java REPL shell

Is there a project that makes a command prompt that can execute Java statements? Why not? I'm looking for something like the builtin shell of Python but for Java.
I see there is http://www.beanshell.org/ but that project does not seem very active. But it appears to be what I'm looking for. Are there any other projects like this?
I want to be able to do something like this
$ import org.foobar.Bletch
$ new Bletch();
or similar. Has anyone done this?

A: You could always use a Clojure REPL - I do this for dynamically playing with Java objects at runtime.
(import 'my.package.SomeClass)

(def a (new SomeClass))

(.methodName a arg1 arg2)

Works pretty well as long as you know the Clojure syntax.

A: Look at Groovy Shell - this is not exactly Java, but very close.

A: You can use http://www.beanshell.org/
It is more than 12 years old and is used in a number of IDE's debuggers.


text:
Q: Does react suggest, how many nested component should be used in an application? Is creating more than 3 levels of nested components in react a bad practice? If yes, what are other ways to create complex UI without diluting a component's responsibility?

A: No but if they have lots of props passing down to each other then it is.
solution is:
REDUX! Or React Context Api
creates a global state container. so components can be decoupled from each other
https://redux.js.org/

A: The levels of nested components doesn't matter anymore than the level of nested HTML elements matters.
If on the other hand you're passing props more than 3-4 levels deep, that is not recommended. React's Context API was created to solve that. It helps you setup Provider/Consumer pairs that can inject props at any level. Here's a good example from React docs:
https://reactjs.org/docs/context.html#dynamic-context


text:
Q: Erro EntityFramework Alguém poderia me ajudar ?
Estou tentando fazer o CodeFirst e quando executo o comando me aparece este erro:
O inicializador de tipo de 'System.Data.Entity.Internal.AppConfig' acionou uma exceção.
Meu AppConfig esta assim:
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MusicasDbConexto" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;Database=musica;uid=root;pwd=''" />
  </connectionStrings>

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
    </providers>
  </entityFramework>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>

        <assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />

        <bindingRedirect oldVersion="0.0.0.0-8.0.17.0" newVersion="8.0.17.0" />

      </dependentAssembly>

    </assemblyBinding>

  </runtime>
</configuration>


text:
Q: gprof output is empty Using gprof 2.28 and gcc 6.3.0 in Ubuntu 17.04 on a variety of sample programs I get empty output for every category. If I run gprof -i on one example program I get:
1 histogram record
2 call-graph records
0 basic-block count records

My compilation looks something like this:
cc -g -c sem_test.c -pg
cc -o sem_test sem_test.o -lpthread -pg

Or this:
gcc -g3 -O0 -Wall -std=gnu99 -pg -fprofile-arcs -fno-inline -fno-reorder-functions sem_test.c -o sem_test -lpthread -pg

Both have the same results.
I notice that my gmon.out file is only 687 bytes which seems low.

A: This is a glibc bug/limitation:

*

*-pg -pie doesn't work
If you cannot install a fixed glibc, you can link with -no-pie to disable PIE.  Your toolchain probably enables PIE automatically.


text:
Q: brew cannot install go@1.13 while brew search shows it I am seeing on my mac the the following weird situation
$ brew search go@1.13
==> Formulae
go@1.13

and
$ brew install go@1.13
Error: go@1.13: unknown keyword: because

Also the error message is weird (it doesn't seem to complete the sentence.) I can brew install go@1.14 without any problem.
Please help provide some clues. Thank you.

A: That looks like your brew is not up to date. Can you run brew update to ensure everything is up to date before running brew install go@1.13? That would probably solve your issue.
Here is my installation test:
$ brew install go@1.13
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> Updated Formulae
Updated 15 formulae.

Warning: go@1.13 has been deprecated because it is not supported upstream!
==> Downloading https://homebrew.bintray.com/bottles/go%401.13-1.13.15.mojave.bottle.1.tar.gz
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/d994ff2b27c191bb74dd44a373e254ef92472c1cb13e381cf6bf9d3d118
######################################################################## 100.0%
==> Pouring go@1.13-1.13.15.mojave.bottle.1.tar.gz
==> Caveats
go@1.13 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.

If you need to have go@1.13 first in your PATH run:
  echo 'export PATH="/usr/local/opt/go@1.13/bin:$PATH"' >> /Users/rchen/.bash_profile

==> Summary
  /usr/local/Cellar/go@1.13/1.13.15: 9,282 files, 414.5MB


text:
Q: default spl_autoload_register() namespace behavior with index.php outside root With modern PHP, calling
spl_autoload_register();
allows you to instantiate new classes without having to specify REQUIRE, INCLUDE nor USE within your php files, as long as they have a namespace, and as long as that namespace follows a folder/file structure such as:
|--models
     |-- utility
|           |___calculator.php
|
|
|--index.php

With such setup, if calculator.php has declared on its top "namespace models\utility", and it contains the class Calculator (a match to the file name calculator.php) you can automatically instantiate it from index.php by calling:
calc = New models\utility\Calculator();

However, if the folder structure is like this:
|--models
     |-- utility
|           |___calculator.php
|
|
|--public
     |--index.php

Now index.php can no longer access calculator through its namespace, as index.php is no longer at the root folder.
It seems that there is no way for public/index.php to reach namespaces above its level. It is just a limitation of PHP. Is there a way perhaps to register a function with spl_autoload_register that would retain its automatic, easy to work with behavior but allowing index.php to instantiate namespaces above its folder level? Or another way to deal with this situation while still never having to USE nor REQUIRE/INCLUDE files?

UPDATE WITH ANSWER
This is a directory agnostic solution that worked for me. I can successfully instantiate new classes merely by calling their namespace, without having to resort on USE, REQUIRE nor INCLUDE even though index.php was moved to the /public folder.
//'/../../../../' points the autoloader.php file back to root directory
$include_path = realpath(dirname(__FILE__) . '/../../../../');
set_include_path($include_path);
spl_autoload_register();

A: When the spl_autoload_register() function is called without the $autoload_function argument, the default autoloading function spl_autoload() is used.
The spl_autoload() function checks all include paths for the file, matching namespaces to folders and class names to files as you have already noted.
The key for you is to make sure that the folder containing the directory structure with your class files (i.e. the directory that contains models) is on the include path. This is commonly done using the set_include_path() function.


text:
Q: Is it possible that PC can use phone battery during suspend? I plugged in my phone to recharge using USB recharger. When I went to bed I put my PC to suspend and then when I woke up my phone battery was 0% (even if it was almost full when I left it).
Is it possible that my desktop PC with Ubuntu on it used my phone's battery during suspend?

A: @Kunok your phone is built to use the pc's energy, not the contrary. So I think your usb cable was not more establishing the connection whereas your phone was draining. If that fails to be the case then you should check your phone charging system. Now, Ubuntu OS cannot be responsible for that right? I mean just be fair... cheers.


text:
Q: Ruby: each_with_index bails when encountering Range as string, NoMethodError I'm using the new Postgresql feature of storing an array in my Rails 4 app. As you know, each element of an array stored in PG is in strings.
So my array = [7, 8..9, 10] is what you want but is stored in PG as {'7', '8..9', '10'}. I can test for each element to turn it back into an integer or Range as needed.
But I get a NoMethodError: undefined method 'each_with_index' for "8..9":String
 array.each_with_index do |item, index|
   puts "index=#{index}, item=#{item}"
 end

The portion of my schema.rb is below:
create_table "items", force: true do |t|
  t.string   "category"
  t.string   "sub_category"
  t.string   "name"
  t.string   "explanation"
  t.integer  "scoring"
  t.integer  "high_score"
  t.boolean  "all_or_nothing"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "survey_id"
  t.boolean  "date"
  t.boolean  "time"
  t.string   "colors",         default: [], array: true
end

Running array.inspect yields:
 "[\"7\", \" 8..9\", \" 10\"]"

Reading the docs, it's not obvious to me while it's failing. It can't be for a string because it happily passed on the "7" previously. array[1].class => 'String'. My Google searches for this specific situation come up empty. I know it's a Range enclosed in a String, but at this point, it's just a string?
For completeness, it may be helpful to know that I'm using Windows and Ruby 2.0 to build this app.
Where should I look to learn how to resolve this? thanx, sam

A: It must be due to end of a long work day, but after a restart the next day, I cannot reproduce the behavior. It must be said that I've restarted console during this process but apparently I needed to do more to restart the entire environment in Windows. Thanks to mu is too short for hanging with me late to troubleshoot this one-off behavior.


text:
Q: One pretask for multiple tasks in package.json I am using Terraform for a project and I got two tasks in my package.json to launch terraform plan and terraform apply.
"scripts": {
    "tf:apply": "terraform apply",
    "tf:plan": "terraform plan"
}

For both of these commands, I need to perform a terraform get first. I would like to have just one pretask for both of them.
I tried to use:
"scripts": {
    "pretf:*": "terraform get",
    "tf:apply": "terraform apply",
    "tf:plan": "terraform plan"
}

But it doesn't work.
Is there any way to achieve this using NPM or Yarn only ? Or am I forced to write the exact same pretask for both of these tasks ?

A: I usually go like this:
"scripts": {
    "tf:get": "terraform get",
    "tf:apply": "npm run tf:get && terraform apply",
    "tf:plan": "npm run tf:get && terraform plan"
}

This is another option which fakes a sort of "tf:*" prehook. Only for obscure cryptic npm ninjas and not recomended:
"scripts": {
    "pretf": "terraform get",
    "tf": "terraform",
    "tf:apply": "npm run tf -- apply",
    "tf:plan": "npm run tf -- plan"
}

(Use it with npm run tf:plan or directly with any argument npm run tf -- whathever)

A: Have you tried to manage it directly using node?
You can bind the events inside your package.json directly to node scripts and inside the node scripts you can execute your terraform commands and your common code in this way:
var exec = require('child_process').exec;
var cmd = 'terraform apply';

// common code

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

You could also just use one single node script accepting a parameter to specify which terraform task to execute, define your common code inside the script, and then execute the right command depending on the parameter:
"scripts": {
    "tf:apply": "node myscript.js --param=apply",
    "tf:plan": "node myscript.js --param=plan"
}

Then inside node you can access your param in this way:
console.log(process.argv.param);


text:
Q: How to convert Future to int? So I'm trying to display a pie chart using the fl_chart plugin. The data for the chart is being retrieved from firestore. I have this function that is used to display the data:
List<PieChartSectionData> showSection(AsyncSnapshot<QuerySnapshot> snapshot) {
    return List.generate(length, (i) {
      final isTouched = i == touchedIndex;
      final double fontSize = isTouched ? 25 : 16;
      final double radius = isTouched ? 60 : 50;
      return PieChartSectionData(
        color: Color(int.parse(cerealData[i].colorVal)),
        value: cerealData[i].rating,
        title: cerealData[i].rating.toString(),
        radius: radius,
        titleStyle: TextStyle(
            fontSize: fontSize,
            fontWeight: FontWeight.bold,
            color: const Color(0xffffffff)),
      );
    });
  }

The List.generate() takes an int as an argument. Since I'm displaying realtime data, I'm trying to get the number of documents present in my collection. For that, I have a function called getLength():
  void getLength(AsyncSnapshot<QuerySnapshot> snapshot) async {
    length = await Firestore.instance.collection('cereal').snapshots().length;
    cerealData =
        snapshot.data.documents.map((e) => Cereal.fromJson(e.data)).toList();
  }

However, when I run the code, I get:
 Another exception was thrown: type 'Future<int>' is not a subtype of type 'int'

The entire code:
class _FlChartPageState extends State<FlChartPage> {
  int touchedIndex;
  var length;
  List<Cereal> cerealData;

  void getLength(AsyncSnapshot<QuerySnapshot> snapshot) async {
    length = await Firestore.instance.collection('cereal').snapshots().length;
    cerealData =
        snapshot.data.documents.map((e) => Cereal.fromJson(e.data)).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<QuerySnapshot>(
          stream: Firestore.instance.collection('cereal').snapshots(),
          builder: (context, snapshot) {
            getLength(snapshot);
            if (!snapshot.hasData)
              return CircularProgressIndicator();
            else {
              return PieChart(PieChartData(
                  pieTouchData: PieTouchData(touchCallback: (pieTouchResponse) {
                    setState(() {
                      if (pieTouchResponse.touchInput is FlLongPressEnd ||
                          pieTouchResponse.touchInput is FlPanEnd) {
                        touchedIndex = -1;
                      } else {
                        touchedIndex = pieTouchResponse.touchedSectionIndex;
                      }
                    });
                  }),
                  borderData: FlBorderData(show: false),
                  sectionsSpace: 0,
                  centerSpaceRadius: 40,
                  sections: showSection(snapshot)));
            }
          }),
    );
  }

  List<PieChartSectionData> showSection(AsyncSnapshot<QuerySnapshot> snapshot) {
    return List.generate(length, (i) {
      final isTouched = i == touchedIndex;
      final double fontSize = isTouched ? 25 : 16;
      final double radius = isTouched ? 60 : 50;
      return PieChartSectionData(
        color: Color(int.parse(cerealData[i].colorVal)),
        value: cerealData[i].rating,
        title: cerealData[i].rating.toString(),
        radius: radius,
        titleStyle: TextStyle(
            fontSize: fontSize,
            fontWeight: FontWeight.bold,
            color: const Color(0xffffffff)),
      );
    });
  }
}

I read somewhere that awaiting the future gets rid of the Future. But that doesn't work here.
How do I fix this?
Edit: It works if I simply pass the number of documents instead of length in List.generate(). But this won't work if there are changes to the collection. So how do I convert Future to int?

A: I think you aren't getting the length of the documents, you are getting the length of the snapshots if you want to get the documents length :
QuerySnapshot querySnapshot = await Firestore.instance.collection('cereal').getDocuments();
    int length = querySnapshot.documents.length;

A: In get getLength function you are trying to get length which is actually async task which returns future and because of that you are getting following error.
Change your method with following metod
getLength()async{
 Firestore.instance.collection('cereal').snapshots().length.then((len){
  length = len;
  cerealData =
        snapshot.data.documents.map((e) => Cereal.fromJson(e.data)).toList();
  });
}


text:
Q: How to hook ngOnInit event in angular? In angular, is it possible to hook to ngOnInit event for each component?
for example I want to execute console.log('im on ngOnInit');, in every component in my application, and I do not want to open each component and write this in the code.
Something like this or similar way is possible to do?
main.ts
 import { component } from '@angular...';

 component.hook('ngOnInit', (cmp) => { console.log('im on ngOnInit'); });


text:
Q: URL rewrites does not work after update to 1.9.3.1 Our redirects aren't working anymore - properply after updating to Magento 1.9.3.1.
The rewrites are still present in the URL Rewrites. If I click on one of them and save it (without editing anything), then it works again.
Any ideas how to "re-apply" them, without manually saving each and everyone?
(Reindexing does not fix the issue.

Example:
https://www.fyr-selv.dk/Briketter/SEDI-Toervebriketter/SEDI-Toervebriketter-k111-i46.html

UPDATE:
Seem's to be 1.9.3.1 bug caused by changes to rewrites and case sensitivity.
When i save a rewrite, then requestpath changes all uppercase characters to lowercase. This matches the fix description in Magento changelog regarding rewrites:
Case-sensitive variations of URL rewrites work as expected.
But seems like the update lacks to change this for all current rewrites.

A: SQL: UPDATE core_url_rewrite SET request_path = LOWER(request_path)
fixes the issue.
This is caused by Magento 1.9.3.1 changes, making request_path entries that are not all lowercase invalid.

A: The bug comes from changements made in app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php
$path = array($path);                          => $path = array(strtolower($path));
$pathBind['path' . $key] = $url;               => $pathBind['path' . $key] = strtolower($url);
$mapPenalty = array_flip(array_values($path)); => $mapPenalty = array_change_key_case(array_flip(array_values($path)));

The update request proposed by Michael Knudsen is probably the best solution.
Another solution is to complete the changements made in app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php replacing also the 2 occurences of $item['request_path'] by strtolower($item['request_path'])
Best regards,
Olivier Blanc, Web Developper
Note: the same question has been asked here


text:
Q: 'ontouchstart' in window returns true in MS Edge browser phone emulator, but the touchstart event is not fired When I select the Windows Phone 10 browser profile at the Microsoft Edge developer tools emulation tab, 'ontouchstart' in window returns true but the touchstart event is not fired.
Is this a bug? Does a real Windows 10 phone behave the same way? Is there a way to emulate touchstart on Edge?
Note: I know the pointerup event, but I thought that, if only pointerup is fired, 'ontouchstart' in window should be false.
Test at jsfiddle

A: Are you using a mouse?
I don't know if Edge is supposed to simulate a touchscreen event when it's using the Windows Phone 10 browser profile, but my guess would be that it wouldn't. Laptops (nowadays) often have touch screens, and these create touchstart events on desktop Edge (and IE if I recall correctly), so Microsoft may have decided that the input method (mouse vs. touch vs. pen) shouldn't be considered part of the desktop/mobile distinction.
Anyway, if you do have a computer with a touchscreen handy, you can use that to test touchstart/touchend, but I'm not sure how else to do it.


text:
Q: How can tasks "refuse to freeze" on suspend? Yesterday, when closing my laptop, it did not go into standby mode immediately. According to the logs, it was trying to, but a tasks refused to freeze:
Freezing of tasks failed after 20.005 seconds (1 tasks refusing to freeze, wq_busy=0):

This went on for a few hours until the system actually suspended. The syslog was full of messages like in this question, because systemd was trying again and again.
How can this happen? Why can't the scheduler just stop scheduling that application? and then it's effectively frozen? I read that there are multiple STOP commands, one of them asking nicely and one of them forcing freeze. Why did systemd not use this or why did this not work here?

A: Task freezing is documented in detail in the kernel documentation.
User-space processes can't refuse to freeze; they do get frozen, but the signalling between the kernel and processes is handled automatically by the signal-handling code (freezing uses a fake signal).
If you're seeing "tasks refusing to freeze" messages, that means that a kernel thread is refusing to freeze, usually because it's doing something which can't be checkpointed. However having to wait several hours for the kernel to suspend isn't normal; the stack traces in the log messages would help to get some idea of what's going wrong.


text:
Q: Do int return the memory location/address? There is no code for this question at all..Just a simple question... As strings return their memory location\address but do int do the same or there is something else going on?  ||  (pardon me if there's any mistake in this question I am just a beginner in programming and I just know the basic concepts of it.)||

A: You don't return a string, you return a pointer to a char.

*

*When you return a pointer to a char (address of a char), a pointer (an address) is returned.
char *x; ... return x;

*When you return a pointer to an int (address of an int), a pointer (an address) is returned.
int *x; ... return x;

*When you return an int, an int is returned.
int x; ... return x;


text:
Q: Load ml files dynamically in OCaml toplevel? As all we know, in we can use #use directive in OCaml toplevel to load ml files then execute.
And we can also use ocaml.exe  to load and execute ml files.
Here my requirement has some changes to these two situations:
I have a main process, who creates a ocaml toplevel to execute scripts, the two process communicates with shared memory and stdin/stdout. The address(token) of shared memory are given in Sys.argv.
The problem is, I want to load ml files dynamically after the creation of process, so the ml to execute is not given at first.
If I start the process with "ocaml.ml xx.ml [params]", the script will be executed at once and I can't simply use #use directive after the beginning of the script.
If I go into interactive mode, I can't give the shared address since once I give these prams, they are considered as ml filename.
So anyone has an idea to make it happen? The ocaml toplevel is a background service and it calls a script who enters an event loop once started.

A: It seems to me that you could send the parameters for communication to the interactive toplevel before entering your event loop.
Or you could use the compiler libraries to take control of the repl directly and interleave Toploop.execute_phrase and Toploop.use_silently.
Another option might be to spawn a native process and use dynlinking rather than loading ml files.


text:
Q: Python "pip install " is failing with AttributeError: 'module' object has no attribute 'SSL_ST_INIT' $ sudo pip install --upgrade pyOpenSSL
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 9, in <module>
load_entry_point('pip==8.1.1', 'console_scripts', 'pip')()
File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 558,
in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line
2682, in load_entry_point
return ep.load()
File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line
2355, in load
return self.resolve()
File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line
2361, in resolve
 module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "/usr/local/lib/python2.7/dist-packages/pip-8.1.1-
 py2.7.egg/pip/__init__.py", line 16, in <module>
from pip.vcs import git, mercurial, subversion, bazaar  # noqa
 File "/usr/local/lib/python2.7/dist-packages/pip-8.1.1-
 py2.7.egg/pip/vcs/mercurial.py", line 9, in <module>
from pip.download import path_to_url
File "/usr/local/lib/python2.7/dist-packages/pip-8.1.1-
py2.7.egg/pip/download.py", line 39, in <module>
from pip._vendor import requests, six
File "/usr/local/lib/python2.7/dist-packages/pip-8.1.1-
py2.7.egg/pip/_vendor/requests/__init__.py", line 53, in <module>
from .packages.urllib3.contrib import pyopenssl
File "/usr/local/lib/python2.7/dist-packages/pip-8.1.1-
  py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py",
line
54, in <module>
 import OpenSSL.SSL
   File "/usr/lib/python2.7/dist-packages/OpenSSL/__init__.py", line 8, in
  <module>
    from OpenSSL import rand, crypto, SSL
    File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 118, in
<module>
 SSL_ST_INIT = _lib.SSL_ST_INIT
AttributeError: 'module' object has no attribute 'SSL_ST_INIT'

I am unable to Uninstall " pip uninstall pyopenssl "
Using pip gets me this error.
Thanks in advance.
Additional Details:
I am using
Distributor ID: Ubuntu
Description:    Ubuntu 15.10
Release:        15.10
Codename:       wily

A: I ran into this issue as well. The solution proposed to run pip  doesn't work because pip is broken too! I found this solved it for me:
sudo python -m easy_install --upgrade pyOpenSSL

This installed version 17.3.0 which was an upgrade to the (stock python-openssl on xenial) version ?0.15.1?. Note the massive change in version it could be they dropped the leading 0. in later versions.
Anyway, after that, pip and ansible started to work again.

A: I did the following which seemed to fix the error, not sure if it's the correct way, but it did fix the error on my machine:
I first backed up the directories below, recommend you do same.
rm -rf /usr/lib/python2.7/dist-packages/OpenSSL
rm -rf /usr/lib/python2.7/dist-packages/pyOpenSSL-0.15.1.egg-info
sudo pip install pyopenssl

I couldn't uninstall it because every time I ran pip I got the same error you did: 'module' object has no attribute 'SSL_ST_INIT'.
After the above my pip now works and more importantly my ansible now works (which was broken by my previous updates).
Not sure if it will work on your system, and removing things out of band,  like I did, is risky at best, so as a warning, I would say, your mileage may vary with my kludgy fix, use caution!

A: Below method worked for me, I am using Ubuntu 20.04 and wanted to install Objection for Runtime manipulation and dynamic analysis of iOS apps.
Short Background:
I noticed that when I fired pip3 install objection in terminal it gave me same error as you but the directory path was little bit different.
In my case it was related to python3.8, so I did following things
Solution:
rm -rf /home/smshrimant/.local/lib/python3.8/site-packages/OpenSSL/

sudo rm -rf /usr/local/lib/python3.8/dist-packages/OpenSSL/

A: Upgrading pyOpenSSL to 16.2.0 fixes it.
pip uninstall pyOpenSSL
pip install pyOpenSSL==16.2.0

There is an issue with version compatibility.


text:
Q: Replace "%" with "\%" in string I need to make a character vector suitable for use in LaTeX, so I need to escape all the percent signs with a single backslash. So far, all I've been able to do is to get two backslash:
> text <- c("This is 60%", "This is 30%")
> gsub("%", "\\%", text, fixed=TRUE)
[1] "This is 60\\%" "This is 30\\%"
> gsub("%", "\\\\%", text, fixed=TRUE)
[1] "This is 60\\\\%" "This is 30\\\\%"

As expected, if fixed=FALSE I get no backslash using "\\%" as a substitution or two backslash using `"\\%"' as a substitution. How can I get "This is 60\%" as a result?

A: In fact, the first version is already working:
text <- c("This is 60%", "This is 30%")
gsub("%", "\\%", text, fixed=TRUE)
[1] "This is 60\\%" "This is 30\\%"

When you see \\% in the printed string, the first backslash is just an escape character for the second backslash, which is literal.  Your output string is really this:
This is 60\%


text:
Q: Allure reports in parallel test pipeline in Jenkins trying to generate two allure reports while running jenkins pipeline job in paralled mode.
tried to implement solution found here Can't split allure report into suites in jenkins pipeline, but no luck.
here is my pipeline code that is working. but allure report shows details on test which lasted longer in terms of execution.
is there a possibility to create separate folders for different stages? jenkins is running on remote server and i am unable to create dir for allure-report there. maybe there is a mvn command that i can send in steps where allure-report will store artifacts of test execution or something else? please, advice.
pipeline {
    agent any
    tools {
        maven 'Maven 3.8.6'
    }
    stages {
        stage('Run Tests') {
            parallel {
                stage('Test on DEV') {
                    agent {
                        label 'node_02_jdk_17'
                    }
                    steps {
                        cleanWs()
                        git branch: 'develop', credentialsId: 'jenkins_git', url: 'https://Jenking_GIT@...-automated-tests.git'
                        sh "mvn test -P UI -Dtarget.env=develop -Dtest=LogIn"
                        allure includeProperties: false, jdk: '', properties: [[key: 'allure.results.directory', value: 'target/allure-results']], report: 'target/allure-report', results: [[path: 'target/allure-results']]
                    }
                }
                stage('Test on QA') {
                    agent {
                        label 'node_02_jdk_17'
                    }
                    steps {
                        cleanWs()
                        git branch: 'develop', credentialsId: 'jenkins_git', url: 'https://Jenking_GIT@...-automated-tests.git'
                        sh "mvn test -P UI -Dtarget.env=qa -Dtest=LogIn2"
                        allure includeProperties: false, jdk: '', properties: [[key: 'allure.results.directory', value: 'target/allure-results']], report: 'target/allure-report', results: [[path: 'target/allure-results']]
                    }
                }
            }
        }
    }
}


text:
Q: Redux Unit Test - reducers and action creators I'm recently learning Redux and writing Unit Test as part of TDD process using Jest
Im writing test for action creators and reducers. But i'm struggling with: can I  make use of action creators in the reducers test?
import * as types from './../../constants/auth';
import * as actions from './../../actions/auth';
import reducer, {initialState} from './../auth';

can I do this
it('should set isFetching to true', () => {
    const expectedState = {
        ...initialState,
        isFetching: true
    }

    expect(
        reducer(initialState, actions.loginPending())
    ).toEqual(expectedState)
});

instead of this?
it('should set isFetching to true', () => {
    const expectedState = {
        ...initialState,
        isFetching: true
    }

    expect(
        reducer(initialState, {type: types.LOGIN_PENDING})
    ).toEqual(expectedState)
});

I came to this doubt because the official documentation use hard coded action in the reducers test:
expect(
  reducer([], {
    type: types.ADD_TODO,
    text: 'Run the tests'
  })
).toEqual([{
      text: 'Run the tests',
      completed: false,
      id: 0
}])

I guess using hard coded actions is the best practice isn't?

A: Interesting question and I would say it depends how you run your test suite. Personally, I hardcode the actions because if you think about it, they declaratively explain what the reducer is expecting. The argument in favor of importing the actions is that if you ever change their source, the tests will not need to be updated. However, this also means you're expecting your actions to always be correct BEFORE running these tests.
If that's the case (if you always run your actions test suite before this one) then it would be reasonable to import them in your reducer test suite. The only argument against this logic would be that it's not as easy to have a new developer learn how your reducer works by only looking at the reducer test suite as they would also need to look at the actions source file to see what type of actions are dispatched.
On the other hand, hard-coding your actions is more declarative but does require you to update each reducer test if your action changes. The reason I still recommend this approach is that this is that it allows you to send more controlled data but I do agree that it increases maintenance costs.


text:
Q: Prove that ${\sum\limits_{n=1}^{\infty}}(-1)^{n-1} \frac{H_n}{n} = \frac{\pi^2}{12} - \frac12\ln^2 2$ We know that $H_n = \sum_{j=1}^{n}{1 \over j}$. Article in The Sum of Certain Series Related To Harmonic Numbers of Omran Kolba, we have proof of this identity which involves some advanced concepts.
I tried to turn the sum into a definite integral and could not. I appreciate any help.
$$
\sum_{n=1}^{\infty}(-1)^{n-1} \dfrac{H_n}{n} = \sum_{n=1}^{\infty}\dfrac{(-1)^{n-1}}{n}\sum_{i=2}^{n+1}\dfrac{1}{i+1} = \sum_{n=1}^{\infty}\dfrac{(-1)^{n-1}}{n}\sum_{i=2}^{n+1}\int_{0}^{1}x^{i}dx = ?
$$

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
Note that
\begin{align}
H_{n}&=\int_{0}^{1}{1 - t^{n} \over 1 - t}\,\dd t
=-n\int_{0}^{1}\ln\pars{1 - t}t^{n - 1}\,\dd t
\end{align}
where we integrated by parts.

Then,
\begin{align}
&\bbox[10px,#ffd]{\sum_{n = 1}^{\infty}
\pars{-1}^{n - 1}\,{H_{n} \over n}} =
-\int_{0}^{1}\ln\pars{1 - t}
\sum_{n = 1}^{\infty}\pars{-t}^{n - 1}\,\dd t
\\[5mm] = &\
-\int_{0}^{1}{\ln\pars{1 - t} \over 1 + t}\,\dd t =
-\int_{0}^{1}{\ln\pars{t} \over 2 - t}\,\dd t
=-\int_{0}^{1/2}{\ln\pars{2t} \over 1 - t}\,\dd t
\\[5mm] = &\
-\int_{0}^{1/2}{\ln\pars{1 - t} \over t}\,\dd t =
\int_{0}^{1/2}{{\rm Li}_{1}\pars{t} \over t}\,\dd t
=\int_{0}^{1/2}{\rm Li}_{2}'\pars{t}\,\dd t
\\[5mm] = &\ {\rm Li}_{2}\pars{\half} =
\bbox[10px,border:1px groove navy]
{{\pi^{2} \over 12} - \half\,\ln^{2}\pars{2}}
\approx 0.5822
\end{align}
$\large\mbox{See this link}$.

A: You may consider the standard identity $$\sum_{n=1}^{\infty}H_n x^{n-1} = -\dfrac{\ln(1-x)}{x(1-x)} \quad -1 < x<1,\,x\neq0.$$ Then integrate from $x=-1$ to $x=0$ to obtain easily$$\sum_{n=1}^{\infty}(-1)^{n-1} \dfrac{H_n}{n} \!= -\! \int_{-1}^{0}\dfrac{\ln(1-x)}{x(1-x)} dx = -\!\int_{-1}^{0}\left(\dfrac{\ln(1-x)}{x}\! + \!\dfrac{\ln(1-x)}{1-x}\right) \! dx=\dfrac{\pi^2}{12} - \dfrac{1}{2}\ln^2 2.$$


text:
Q: multi page password protection Is it possible to have the "password protected page" feature of WordPress apply to more than one page? I have dozens of pages which I wish to protect with the same password, but I don't want people to keep having to type the password every time they open a new page. I also don't want people to require an account, all they should need is one password!

A: WordPress FTW! It actually works this way out of the box. If you use the same password on multiple pages, it only has to be entered once.


text:
Q: how to compute length in polar coordinates? The line element $\Delta s^2$ is suppose to be an invariant of Euclidean space. In standard coordinates $\Delta s^2=\Delta x^2+\Delta y^2$ while in polar coordinates $\Delta s^2=\Delta r^2+r^2\Delta \theta^2$. Equivalently, in standard coordinates the metric is $$\begin{bmatrix}1&0\\0&1\end{bmatrix}$$ while in polar coordinates it is   $$\begin{bmatrix}1&0\\0&r^2\end{bmatrix}.$$
I don't understand how to compute the length of a point. Suppose the point is $(a,b)$ in standard coordinates. It's squared length in standard coordinates is given by $$(a,b)\begin{bmatrix}1&0\\0&1\end{bmatrix}(a,b)^T=a^2+b^2$$But how do you compute the length in polar coordinates? Wouldn't it be $$(\sqrt{a^2+b^2},\arctan(b/a))\begin{bmatrix}1&0\\0&a^2+b^2\end{bmatrix}(\sqrt{a^2+b^2},\arctan(b/a))^T$$which is definitely not the same as $a^2+b^2$.
How do you get the same line element in polar coordinates versus standard coordinates?

A: $\newcommand{\dd}{\partial}$To say the Euclidean metric in polar coordinates is
$$
\left[\begin{array}{cc}
1 & 0 \\
0 & r^{2}
\end{array}\right]
$$
really means that $ds^{2} = dr^{2} + (r\, d\theta)^{2}$. In other words, if
$$
v = a\, \dd_{r} + b\, \dd_{\theta}
\tag{1}
$$
is a tangent vector at some point $(r, \theta)$ in polar coordinates, then the Euclidean length of $v$ is
$$
\sqrt{a^{2} + (rb)^{2}}.
\tag{2}
$$
To calculate the arc length of a curve, use (2) to calculate the curve's speed, then integrate.
For example, to calculate the length of the parametrized line segment
$$
\gamma(t) = (r_{0}t, \theta_{0}),\quad 0 \leq t \leq 1
$$
joining the origin to the point with polar coordinates $(r_{0}, \theta_{0})$, note that

*

*The velocity of gamma is $v = r_{0}\, \dd_{r}$.

*The speed of $\gamma$ is $\sqrt{r_{0}^{2}} = |r_{0}|$ by (2).

*The length of $\gamma$ is the integral of the speed,
$$
\int_{0}^{1} \|\gamma'(t)\|\, dt
  = \int_{0}^{1} |r_{0}|\, dt
  = |r_{0}|,
$$
the Euclidean distance.

A: It seems that you are talking about two dimensional coordinate. No matter 2D or 3D polar coordinate, the length, $r$, is given.
The relation for a 2D standard coordinate and polar coordinate is:
$x = r \cos\theta, y = r \sin\theta $. The squared length is $x^2 + y^2 = r^2$ since $\sin^2\theta+\cos^2\theta=$1
  More common is the relation of 3D polar coordinates, $r, \theta, \phi$ to Cartesian axes $x, y, z$.
$x=r\sin\theta \cos\phi,y=r\sin\theta \sin\phi, z=r\cos\theta$
Hope you can picture the coordinates in mind with the equations.


text:
Q: IMGKit displays blank image My application has an activities database, and I'm trying to use IMGKit to render the show view of an activity as an image file that can be then used on other platforms.  I feel like I've implemented IMGKit properly, but all I'm getting is a blank image.
Controller action:
def show
    @activity = Activity.find(params[:id])

    respond_to do |format|
      format.html
      format.jpg do
        html = render_to_string
        kit = IMGKit.new(html)
        img = kit.to_img(:jpg)
        send_data img, type: "image/jpeg", disposition: "inline"
      end
    end
end

Not sure if there's anything else applicable?
Edit - this is the view it should be rendering, show.jpg.erb

<%= @activity.title %>

Hello


text:
Q: liferay 6.2GA2 soap authentication with python suds client I've got some problems with the liferay 6.2 soap api: i need it to search users with the python suds client.
In liferay 6.1, i used the following code, it worked well:
from suds.client import Client
c = Client('http://liferay62instance.domain.com/api/secure/axis/Portal_UserService?wsdl', username='liferayuser', password='liferaypassword')
c.service.getUserByScreenName(companyId=10154, screenName='user')

In liferay 6.2, the wsdl url has changed and doesn't require an http authentication by default, so using the following code gives an error:
from suds.client import Client
c = Client('http://liferay62instance.domain.com/api/axis/Portal_UserService?wsdl', username='liferayuser', password='liferaypassword')
c.service.getUserByScreenName(companyId=10154, screenName='user')

and the error:
Server raised fault: 'java.rmi.RemoteException: Authenticated access required'

with the server side traceback:
14:50:45,030 ERROR [ajp-bio-9009-exec-8][UserServiceSoap:845]
java.lang.SecurityException: Authenticated access required
java.lang.SecurityException: Authenticated access required

Do you have any idea on how to pass soap authentication in liferay 6.2??
Thanks for any answser.
Jérôme.

A: Finally i managed my issue using HttpAuthenticated transport from suds.transport.http
Using it adds a new header Authorization with a base64 encoded combinaison of username + password and will be used in each soap request.
Here's an example:
from suds.client import Client
from suds.transport.http import HttpAuthenticated

t = HttpAuthenticated(username='liferayuser', password='liferaypassword')
c = Client('http://liferay62instance.domain.com/api/axis/Portal_UserService?wsdl', transport=t)
result = c.service.getUserByScreenName(companyId=10154, screenName='user')


text:
Q: Thinking Sphinx after deployment - ThinkingSphinx::SphinxError (unknown local index 'user_core' in search request): I check this topic: Sphinx error: unknown local index "INDEX_NAME" in search request , but it's closed and it's not resolve problem in my rails application.
I update TS to 3.0.2, and include it to deploy.rb. I also change code in model. Now it works in development, and some examples work in test, and some not. But after successful deployment I get error:
ThinkingSphinx::SphinxError (unknown local index 'user_core' in search request):

I try rebuild, restart, and other things, but it doesn't work :(
Can anybody help me?
Thanks!

A: It looks like there's already a Sphinx daemon running that Thinking Sphinx hasn't stopped (if you're still getting the same error) so I'd recommend killing that rogue searchd process (which you should be able to find via ps aux | grep searchd - and, if the permissions are fine, killall searchd will stop that Sphinx process).


text:
Q: How can I change the black text in my terminal? I have changed the color in my profile, but some text is still black. How can I make all black text inverted, or any color that's visible? I'm including screenshot of my preferences and the issue. The second terminal screenshot is the result of highlighting, to illustrate the problem.

A: In the second screen shot, it looks like you're looking at man builtin and the Command column, the first column, is in bold text and not visible. Looking at the Bold Text color shows it being rather dark, as dark as the Background Color & Effects in the first screen shot. So, change the Bold Text color to the same color as the Text color or just a shade darker then the Text color.


text:
Q: How to get difference between dates in SQL I have seen other answers but my question is different because I want to get the difference between two dates and use it in the where clause but its asking me to enter days to get difference. The dates are coming from my database.
Select datediff(D, cid, ced) as theDateDiff
from customers

Select datediff(D, cid, ced) as theDateDiff
from customers where theDateDiff>=5

A: Assuming that cid and ced are fields in your customers table, you may wish to try the following:
select * from customers c where datediff("d", c.cid, c.ced) >= 5

A: Consider following two issues involving your MS Access SQL:

*

*In most cases with some exceptions, you cannot use an alias of a calculated column in other parts of same level query. You can however use such an alias if residing in another query or subquery.
SELECT *
FROM (SELECT *, DateDiff("d", cid, ced) AS theDateDiff
      FROM customers) sub
where theDateDiff >= 5

*The DateDiff function in MS Access differs from the DateDiff of SQL Server where the latter appears to be the version you use with unquoted D as first argument. Remember no two dialects in the relational database world are exactly alike even if under same parent company.
Therefore, replace DateDiff(D, cid, ced) with DateDiff("d", cid, ced).
To cite another example other than Microsoft, Oracle (company) now manages MySQL which is a very different RDBMS with much different dialect than flagship database: Oracle.


text:
Q: IS this syntax ok for ruby 1.8.7 i have this app  and while doing a rake db:migrate I get this error
      scope :my, lambda { |options = {}|
        includes(:permissions).
        where("#{quoted_table_name}.user_id     = :user OR " <<
              "#{quoted_table_name}.assigned_to = :user OR " <<
              "permissions.user_id              = :user OR " <<
              "#{quoted_table_name}.access = 'Public'", :user => options[:user] || User.current_user).
        order(options[:order] || "#{quoted_table_name}.id DESC").
        limit(options[:limit]) # nil selects all records
      }

 rake aborted!
 /Users/tamer/Sites/fat_free_crm/lib/fat_free_crm/permissions.rb:45: syntax error, unexpected '=', expecting '|'
      scope :my, lambda { |options = {}|
                                    ^
/Users/tamer/Sites/fat_free_crm/lib/fat_free_crm/permissions.rb:53: syntax error, unexpected '}', expecting kEND

Line 45 is the first line
scope :my, lambda { |options = {}|

Do i need to use ruby 1.9*

A: No, this wont' work in 1.8.7. Yes, it will work in 1.9.2. The more flexible block arguments were introduced as part of Ruby 1.9, including default arguments.
That said, this scope should really just be pushed off into a class method:
def self.my(options = {})
  includes(:permissions).
  where("#{quoted_table_name}.user_id     = :user OR " <<
        "#{quoted_table_name}.assigned_to = :user OR " <<
        "permissions.user_id              = :user OR " <<
        "#{quoted_table_name}.access = 'Public'", :user => options[:user] || User.current_user).
  order(options[:order] || "#{quoted_table_name}.id DESC").
  limit(options[:limit]) # nil selects all records
end

Same result, only it's 1.8.7 compatible.


text:
Q: can't access the class from ActionBar-PullToRefresh library I'm on a android project and I need import the ActionBar-PullToRefresh library, so I import the library with gradle like following:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile('com.android.support:appcompat-v7:20.0.0') {
        force = true
    }
    compile('com.android.support:support-v4:20.0.0') {
        force = true
    }
    repositories {
        mavenCentral()
    }
    compile 'com.github.chrisbanes.actionbarpulltorefresh:extra-abc:+'
}

Then I Sync Project with Gradle Files, so I can use the PullToRefreshLayout in my layout xml file.But when I use the library's class in my Fragment code,I can't get nothing code trigger. When I spell the whole class name PullToRefreshLayout the Android studio will not import the class automatically. So what's the problem.
The next two file is my build.gradle file in the root directory and my app directory:
build.gradle file in the root directory
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

build.gradle file in the app directory
apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.ifeve.ifeveforandroid"
        minSdkVersion 10
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile('com.android.support:appcompat-v7:20.0.0') {
        force = true
    }
    compile('com.android.support:support-v4:20.0.0') {
        force = true
    }
    repositories {
        mavenCentral()
    }
    compile 'com.github.chrisbanes.actionbarpulltorefresh:extra-abc:+'
}

A: Try importing library this way, add in dependencies section this line:
compile 'com.github.chrisbanes.actionbarpulltorefresh:library:0.9.9'


text:
Q: The argument type 'Null Function(Reaction, int)' can't be assigned to the parameter type 'dynamic Function(Reaction, int, bool)' Hello I am having the below error in my code. I really really appreciate any help! This is the error output
Error: The argument type 'Null Function(Reaction, int)' can't be assigned to the parameter type 'dynamic Function(Reaction, int, bool)'.

*

*'Reaction' is from 'package:flutter_reaction_button/src/reaction.dart' ('../../../flutter/.pub-cache/hosted/pub.dartlang.org/flutter_reaction_button-1.0.7+3/lib/src/reaction.dart').
onReactionChanged: (reaction, isChecked) {
and

Error: A value of type 'int' can't be assigned to a variable of type 'bool'.
if (isChecked) {
^
                                             ^

return FlutterReactionButtonCheck(
                          onReactionChanged: (reaction, isChecked) {
                            setState(() {
                              post.myReaction = Reaction(
                                  id: reaction.id,
                                  icon: reaction.icon,
                                  previewIcon: reaction.previewIcon);
                            });
                            if (isChecked) {
                              bool isNewReaction = false;
                              SocialReactionModel postReaction =
                                  _reactionsList.firstWhere(
                                      (element) =>
                                          element.postID == post.id,
                                      orElse: () {
                                isNewReaction = true;
                                String reactionString =
                                    getReactionString(reaction.id);
                                SocialReactionModel newReaction =
                                    SocialReactionModel(
                                        postID: post.id,
                                        createdAt: Timestamp.now(),
                                        reactionAuthorID:
                                            MyAppState.currentUser.userID,
                                        reaction: reactionString);
                                _reactionsList.add(newReaction);
                                return newReaction;
                              });
                              if (isNewReaction) {
                                setState(() {
                                  post.reactionsCount++;
                                });
                                fireStoreUtils.postReaction(
                                    postReaction, post);
                              } else {
                                postReaction.reaction =
                                    getReactionString(reaction.id);
                                postReaction.createdAt = Timestamp.now();
                                fireStoreUtils.updateReaction(
                                    postReaction, post);
                              }
                            } else {
                              _reactionsList.removeWhere(
                                  (element) => element.postID == post.id);
                              setState(() {
                                post.reactionsCount--;
                              });
                              fireStoreUtils.removeReaction(post);
                            }
                          },

A: I think is an old version, try to use the latest version:
flutter_reaction_button: ^2.0.0


text:
Q: How to show all notification in statusbar until user click in android FCM Like Whatsapp As I'm using FCM push notification in my application,Whenever notification comes its showing latest one in status bar,I want to show all notification until user click.If I use pending intent.Flag_current means its showing latest one in android.Please help me.
Service:
    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;
    AlertDialog alertDialog = null;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

       // Log.e("BB", "From: " + remoteMessage.getNotification().getBody());

        //  Log.e("BB", "From-: " + remoteMessage.getNotification());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e("BB", "remoteMessage.getData().toString() " + remoteMessage.getData().toString());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
           // Log.e(TAG, "Data Payload---: " + remoteMessage.getNotification().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message

            Log.e("BB", "iff: " +message);

            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
           // showNotificationMessage(getApplicationContext(), "", message, "", pushNotification, roleid, clickmessage);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
//            notificationUtils.playNotificationSound();
        }else{
            Log.e("BB", "else: " +message);
            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
            // If the app is in background, firebase itself handles the notification
        }
    }

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("body");
            String message = data.getString("body");
            String roleid = data.getString("role_Id");
            String clickmessage = data.getString("click_action");
           // boolean isBackground = data.getBoolean("is_background");
            //String imageUrl = data.getString("image");
           // String timestamp = data.getString("timestamp");
          //  JSONObject payload = data.getJSONObject("payload");

         /*   Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);*/

            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message

                Log.e("BB", "iff: " + title+message);

                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
                //notificationUtils.playNotificationSound();
                showNotificationMessage(getApplicationContext(), title, message, "", pushNotification,roleid,clickmessage);

               /* if (TextUtils.isEmpty(imageUrl)) {
                  } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, "", pushNotification, "");
                }*/

            } else {

                Log.e("BB", "elsee: " + title+message);
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

                showNotificationMessage(getApplicationContext(), title, message, "", pushNotification,roleid,clickmessage);

            }
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent, String roleid, String clickmessage) {
        notificationUtils = new NotificationUtils(context);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent,roleid,clickmessage);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl,String roleid, String clickmessage) {
        notificationUtils = new NotificationUtils(context);
       // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl,roleid,clickmessage);
    }
}

Notification Util:
public class NotificationUtils {

    private static String TAG = NotificationUtils.class.getSimpleName();

    private Context mContext;

    public NotificationUtils(Context mContext) {
        this.mContext = mContext;
    }

    public void showNotificationMessage(String title, String message, String timeStamp, Intent intent, String roleid, String clickmessage) {
        showNotificationMessage(title, message, timeStamp, intent, null,roleid,clickmessage);
    }

    public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl,String roleid, String clickmessage) {
        // Check for empty push message
        if (TextUtils.isEmpty(message))
            return;

        // notification icon
        final int icon = R.drawable.getspot_logo;

        if(roleid.equalsIgnoreCase("5"))
        {

            intent = new Intent(mContext, ManagerHomePage.class);
            Bundle bundle = new Bundle();
            bundle.putString("fromwhere",clickmessage);
            intent.putExtras(bundle);

        }
        else {

            intent = new Intent(mContext, UserHomePage.class);
            Bundle bundle = new Bundle();
            bundle.putString("fromwhere",clickmessage);
            intent.putExtras(bundle);
        }

       // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
      /*  final PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        mContext,
                        0,
                        intent,
                        PendingIntent.FLAG_CANCEL_CURRENT
                );*/
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
        stackBuilder.addNextIntentWithParentStack(intent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);

        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                mContext);

        final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");

        if (!TextUtils.isEmpty(imageUrl)) {

            if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

                Bitmap bitmap = getBitmapFromURL(imageUrl);

                if (bitmap != null) {
                    showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
                } else {
                    showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
                }
            }
        } else {
            showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            //  playNotificationSound();
        }
    }

    private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

        int notifyID = 1;
        String CHANNEL_ID = "my_channel_01";// The id of the channel.
        CharSequence name = "Product";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Log.i("RR","----");
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            // Create a notification and set the notification channel.
            Notification notification = new Notification.Builder(mContext)
                    .setContentTitle("Notification")
                    .setContentText(message)
                    .setSmallIcon(R.drawable.getspot_logo)
                    .setChannelId(CHANNEL_ID)
                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setContentIntent(resultPendingIntent)
                    .setAutoCancel(true)

                    .build();
            mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;

            NotificationManager mNotificationManager =
                    (NotificationManager)mContext. getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.createNotificationChannel(mChannel);

// Issue the notification.
            mNotificationManager.notify(notifyID , notification);

        }

        Log.i("RR","elsee----");

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

        inboxStyle.addLine(message);

        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setAutoCancel(true)
                .setContentTitle("Notification")
                .setContentIntent(resultPendingIntent)
                .setSound(alarmSound)
                .setStyle(inboxStyle)

                .setSmallIcon(R.drawable.getspot_logo)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                .setContentText(message)
                .build();
       // mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(Config.NOTIFICATION_ID, notification);

    }

    private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
        bigPictureStyle.setBigContentTitle(title);
        bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
        bigPictureStyle.bigPicture(bitmap);
        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .setSound(alarmSound)
                .setStyle(bigPictureStyle)
                .setSmallIcon(R.drawable.getspot_logo)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                .setContentText(message)
                .build();

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
    }

    /**
     * Downloading push notification image before displaying it in
     * the notification tray
     */
    public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // Playing notification sound
    public void playNotificationSound() {
        try {
            Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + mContext.getPackageName() + "/raw/notification");
            Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Method checks if the app is in background or not
     */
    public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    // Clears notification tray messages
    public static void clearNotifications(Context context) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    public static long getTimeMilliSec(String timeStamp) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format.parse(timeStamp);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

Note: I want to show all notification to the user, when they click notification it should go ,otherwise all notification i want to display.Please help me.based upon notification only user have to perform task, if old notification is cleared means ,user doesn't know what notificaiton previously came.

A: You should use a different notifyId for each notification to display them as separate. This already has an answer here Add a new notification when push notification receives (not replace old one)
Please search SO before posting a new question.

A: You have hardcoded id used by notification int notifyID = 1;
so each time notification is received the same value (1) is passed into method
mNotificationManager.notify(notifyID , notification);

making it override the previous one, make sure to pass unique "notifyID" each time you show notification, like, I suggest, make that int notifyID to be static and after showing notification increment value by 1 , or you can use timestamp (timestamp is in long so typecast it to int) and then pass in method.
Hope this helps,
Happy coding... :)


text:
Q: how to make a dynamic query using cakephp 3? I have a filter to search the database from it. But if any of the filter fields are empty it is to ignore.
$name = $this->request->data['name'];
$status = $this->request->data['status'];
$code_transaction = $this->request->data['code_transaction'];

$orders = $this->Orders->find('all')->where(['name'=> $name, 'status'=> $status, 'id'=> $code_transaction]);

when you have a blank field behind not query anything database.
I need help to create a query to do the query in the database when you first filled field and ignore those that are blank. Could anyone help me? I accept any idea to create it.

A: You can do something like this:
$query = ['name'=> $name, 'status'=> $status, 'id'=> $code_transaction];
$newdataquery =[];
foreach($query as $key => $data) {
 if (strlen($data) > 0 )
     $newdataquery[$key] = $data;
}
$orders = $this->Orders->find('all')->where($newdataquery);


text:
Q: console window no longer appearing on my Visual Studio Node Console Application The console window appears as expected initially when running the app from Visual Studio but at some point no longer opens...

A: If you run a command from the Package Manager Console from inside Visual Studio it seems to hijack the console window.  Just exit and restart Visual Studio and it should work.
You may have to delete the npm-debug.log as well.


text:
Q: Prob. In Downloading VLC I'm trying to download VLC, when the download process complete, this pops out:

NSIS  Error
Installer integrity check has failed. Common causes include incomplete download and damaged media. Contact the installer's author to obtain a new copy.
More information at:
http://nsis.sf.net/NSIS_Error

A: The VLC download website selects the nearest mirror from the list of available mirrors. Your problem downloading VLC may be solved by selecting a different mirror. The official VideoLAN website has four alternate mirrors. To show the alternate mirrors, click on where it says: If you have a problem, click here.

A: Sounds like the downloaded installer is faulty.
I'm assuming you downloaded it from http://www.videolan.org/, and they have a checksum listed for the current download - check it with FCIV or some other sha1 hashing tool to make sure its valid.
I typically do my installs off ninite (though I may want to move to chocolaty), which might be an alternative.

A: You want to likely install a reputable download manager such as DownThemAll! for Firefox or Chrono Download Manager for Chrome.
"Browser-only" downloads are prone to corruption in my experience (Firefox seems especially eager to terminate downloads before the last few bits are actually processed). A quality third-party download manager will generally solve many of these problems or otherwise clearly indicate the failure of the download.


text:
Q: Array out of bounds exception on simple check box program I have 4 checkboxes, when selected they should concatenate onto a single string displayed on a Jlabel.  It was working before sort-of, not sure whatI did to break it, now I get array exception out of bounds errors.  This is the update() method being run whenever a checkbox is interacted with.
http://pastebin.com/tbSpx7jA
It's been answered thanks all, just messed up my initial array declaration.

A: It looks like you're iterating to an index that does not exist:
for (int j = 0; j <= oslist2.length; j++)

should be
for (int j = 0; j < oslist2.length; j++)

Java array indexes are (0, 1, 2... length-1)
You also have
oslist2[3]="";

which means, you should make the array bigger, or don't use that index.
This should work:
String[] oslist2 = new String[4];


text:
Q: Seven Segment Display error java Hi when ever i run my program i get an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at seven.segmeng.display.test.MultiCharacterDisplay.main(MultiCharacterDisplay.java:68)
Java Result: 1

there is a portion of the code which i'm not sure about which i am not sure about and it's linked to the error from the output
public static void main(String[] args) {
        String text = args[0];

        MultiCharacterDisplay display = new MultiCharacterDisplay(text.length(), Color.GREEN);
        display.setText(text);

        JFrame frame = new JFrame();
        frame.setBackground(Color.black);
        frame.getContentPane().setBackground(Color.black);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(display);
        frame.pack();

        frame.setVisible(true);
    }

I'm not sure where to go at this point.
here is the multicharacter display code segment
public MultiCharacterDisplay(int segmentDisplayCount, Color segmentColor) {
        this.segmentDisplayCount = segmentDisplayCount;
        segmentDisplays = new ArrayList<SixteenSegmentDisplay>(segmentDisplayCount);
        setLayout(new FlowLayout(FlowLayout.LEFT, GAP, 0));
        for (int i = 0; i < segmentDisplayCount; i++) {
            SixteenSegmentDisplay display = new SixteenSegmentDisplay();
            display.setSegmentColor(segmentColor);
            segmentDisplays.add(display);
            add(display);
        }
    }

here is the segmentdisplaycount section
public class MultiCharacterDisplay extends JComponent {
    private static final int GAP = 5;
    private int segmentDisplayCount;
    private List<SixteenSegmentDisplay> segmentDisplays;

    public MultiCharacterDisplay(int segmentDisplayCount) {
        this(segmentDisplayCount, Color.red);
    }

    public MultiCharacterDisplay(int segmentDisplayCount, Color segmentColor) {
        this.segmentDisplayCount = segmentDisplayCount;
        segmentDisplays = new ArrayList<SixteenSegmentDisplay>(segmentDisplayCount);
        setLayout(new FlowLayout(FlowLayout.LEFT, GAP, 0));
        for (int i = 0; i < segmentDisplayCount; i++) {
            SixteenSegmentDisplay display = new SixteenSegmentDisplay();
            display.setSegmentColor(segmentColor);
            segmentDisplays.add(display);
            add(display);
        }