text:
Q: Javascript Slider doesn't work correctly with transition end I don't know why people's are not answering this question.I'm making a horizontal infinite loop slider. What approach i'm using is making a ul container which has 3 images, for example if there are 3 images then clone the first image and place it to the end of the slider, same with last image make clone and place it before the first image. So now total images are 5. Default slider translation always start from first image not from clone one. Here is an example. What i'm facing is, I want to reset the slider after slider comes to the last clone image with same continuous loop like a carousel slider. I try using addEventListener with the event name transitionend but that event doesn't perform correctly and showing unsatisfied behavior. Is there a way to fix this?

(function () {
    var resetTranslation = "translate3d(-300px,0px,0px)";
    var elm = document.querySelector('.Working');
    elm.style.transform = resetTranslation;
    var arr = document.querySelectorAll('.Working li');
    var clonefirst,
        clonelast,
        width = 300;
    index = 2;
    clonefirst = arr[0].cloneNode(true);
    clonelast = arr[arr.length - 1].cloneNode(true);

    elm.insertBefore(clonelast, arr[0]);
    arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
    //Update
    arr = document.querySelectorAll('.Working li');
    elm.style.transition = 'transform 1.5s ease';

    setInterval(function () {

        elm.style.transform = 'translate3d(-' + index * width + 'px,0px,0px)';
        if (index == arr.length - 1) {
            elm.addEventListener('transitionend', function () {
                elm.style.transform = resetTranslation;
            });
            index = 1;
        }
        index++;

    }, 4000)

})();
*{
    box-sizing: border-box;
}
.wrapper{
    position: relative;
    overflow: hidden;
    height: 320px;
    width: 300px;

}

.Working{
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    width: 3125%;

}
.Working li{
    position: relative;
    float: left;
}

img{
    max-width: 100%;
    display: block;
}

.SubContainer:after{
    display: table;
    clear: both;
    content: "";
}

A: I've messed around with your code to hack in a fix: https://jsfiddle.net/rap8o3q0/
The changed part:
var currentItem = 1;

setInterval(function () {
    var getWidth = window.innerWidth;

    if(len === currentItem){
        i = 1;
        currentItem = 1;
    } else {
        currentItem++;
        i++;
    }

    var val = 'translate3d(-' + (i-1) * getWidth + 'px,0px,0px)';
    UnorderedListElement.style.transform = val;

}, 3000);

A: Your transition end event is not immediately fire because last transition doesn't computed when last clone image appear. You can easily achieve this thing by using setTimeout function and pass number of milliseconds to wait, after that reset the translation. I don't know it's an efficient solution but i think its easily done by using this function.
Now I'm fixing your code with this.

(function () {
    var elm = document.querySelector('.Working');
    var arr = document.querySelectorAll('.Working li');
    var clonefirst,
        clonelast,
        width = 300;
    index = 2;
    clonefirst = arr[0].cloneNode(true);
    clonelast = arr[arr.length - 1].cloneNode(true);

    elm.insertBefore(clonelast, arr[0]);
    arr[arr.length - 1].parentNode.insertBefore(clonefirst, arr[arr.length - 1].nextSibling);
    //Update
    arr = document.querySelectorAll('.Working li');

     setInterval(function () {
        $(elm).css({
            'transform': 'translate3d(-' + (index * width) + 'px,0px,0px)',
            'transition': 'transform 1.5s ease'
        });
        if (index == arr.length - 1) {
            setTimeout(function () {
                $(elm).css({'transform': 'translate3d(-300px,0px,0px)', 'transition': 'none'});
                index = 1;
            }, 1400);

        }
        index++;

    }, 2000)

})();
* {
    box-sizing: border-box;
}

.wrapper {
    position: relative;
    overflow: hidden;
    height: 320px;
    width: 300px;
    margin-top: 8px;

}

.Working {
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    transform: translateX(-300px);
    width: 3125%;

}

.Working li {
    position: relative;
    float: left;
}

img {
    max-width: 100%;
    display: block;
}

.SubContainer:after {
    display: table;
    clear: both;
    content: "";
}

#checkboxer:checked + .wrapper {
    overflow: visible;
}

Remove Overflow Hidden
<input type="checkbox" id="checkboxer" name="checkboxer"/>

A: To come back your slider in its first position, you need to trigger a transition end event after the last (3th) translation, That works only one time.
$(UnorderedListElement).one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function ()
    {
        {
            $(UnorderedListElement).css('transform', 'translate3d(0, 0, 0)');

        }
    });

But you need to make it to translate immediately. In link below you can see my slider that is very similar to yours, but works by absolute positioning and change the left property instead of transform.
Slider
Last thing: It is not a good idea to slide the hole of the image container. You must slide your images separately. In your way there is an obvious problem: When the page is sliding out the last image, there is not the next image to push it!

A: You can update your setInterval as
  setInterval(function() {
    var getWidth = window.innerWidth;
    var val = 'translate3d(-' + i * getWidth + 'px,0px,0px)';
    UnorderedListElement.style.transform = val;

    i++;
    if (i == 3) { //assuming three images here
      i = 0
    }

  }, 3000)

var DomChanger;

(function() {

  var listItem = document.querySelectorAll('.ah-slider li');
  var len = listItem.length;

  var getImage = document.querySelector('.ah-slider li img');
  var UnorderedListElement = document.querySelector('.ah-slider');

  var outerDiv = document.querySelector('.Slider');

  UnorderedListElement.setAttribute('style', 'width:' + (len * 1000 + 215) + '%');

  var i = 1;

  DomChanger = function() {

    for (var i = 0; i < len; ++i) {
      listItem[i].setAttribute('style', 'width:' + window.innerWidth + 'px');
    }
    outerDiv.setAttribute('style', 'height:' + getImage.clientHeight + 'px');

  };

  setInterval(function() {
    var getWidth = window.innerWidth;
    var val = 'translate3d(-' + i * getWidth + 'px,0px,0px)';
    UnorderedListElement.style.transform = val;

    i++;
    if (i == 3) {
      i = 0
    }

  }, 3000)

})();

window.onload = function() {
  DomChanger();

};
window.onresize = function() {

  DomChanger();
};
* {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  background-color: #fff;
}

.Slider {
  width: 100%;
  margin: 50px 0 0;
  position: relative;
  overflow: hidden;
}

.ah-slider {
  padding: 0;
  margin: 0;
  list-style: none;
  position: relative;
  transition: transform .5s ease;
}

.ah-slider li {
  position: relative;
  float: left;
}

.ah-slider li img {
  max-width: 100%;
  display: block;
}

.clearFix:after {
  content: "";
  display: table;
  clear: both;
}


text:
Q: Undefined_constant: Error after PHP 7 upgrade I have this simple PHP script (authors.php) to rotate through a list of images in a random order
<?php
$random = mt_rand(1,9);
$image_1 = '';
$image_2 = '';
$image_3 = '';
$image_4 = '';
$image_5 = '';
$image_6 = '';
$image_7 = '';
$image_8 = '';
$image_9 = '';
echo ${image_.$random};
?>

It was working fine until I upgraded from PHP 5.6 to PHP 7.2.34.
Now I get this error.
Use of undefined constant image_ - assumed 'image_' (this will throw an Error in a future version of PHP) in /home/website/public_html/authors.php, line 12

What needs to be changed in order for this script to work?
Thanks

A: Try this instead of long,long lines
$random = mt_rand(1,9);
echo "";

redpajama_set_name: RedPajamaStackExchange


text:
Q: meromorphic functions on the Riemann sphere I am studying the following exercise:
Show that the meromorphic functions on the Riemann sphere have the form
$p(z)/q(z)$, where $p$, $q$ are coprime polynomials.
Is an exercise in Donaldson Riemann Surface.
I thought the following way to solve:
Let $f$ be a meromorphic function on the Riemann sphere. Let $\lambda_1,\ldots,\lambda_n$ be a points in $f^{-1}(0)$ such that $\lambda_i \neq \infty$.
Let $\mu_1,\ldots,\mu_m$ be the points in $f^{-1}(\infty)$ in the same way.
Then
$$\frac{f(z)(z- \mu_1)\cdots(z-\mu_m)}{(z-\lambda_1)\cdots(z-\lambda_n)} =:g(z)$$ defines a meromorphic function with no zeros (except possibly at $\infty$) and no poles (except possibly $\infty$).
Either way $g(z)$ either lacks zeros it lacks poles. So $\deg(g)=0$ and hence $g$ is constant. Then $f=p/q$ for some polynomials $p$ and $q$.
I wonder if you're reasonable. Any adjustment ??

A: To show that a function that is meromorphic in $\mathbb C\cup\{\infty\}$ and has no poles or zeros is constant, you can argue as follows.
First say that it's holomorphic in all of $\mathbb C$ because of the lack of poles. Then, since it's holomorphic at $\infty$, it has neither a pole nor an essential singuarity at $\infty$; hence it has some finite value there. Now you have a function that is continuous on the compact space $\mathbb C\cup\{\infty\}$ and that never takes the value $\infty$, so there is some open neighborhood of $\infty$ in which the function has no values. Thus it is bounded and holomorphic on $\mathbb C.$ Then use Liouville's theorem.


text:
Q: Can I use the Lagrange multiplier to solve the programming problem LeetCode 1792. Maximum Average Pass Ratio. Here is the programming problem LeetCode 1792. Maximum Average Pass Ratio.
The average pass ratio is
$$
f({extraStudents_0, extraStudents_1,...extraStudents_{n-1}})=\frac{1}{n}\sum{\frac{{pass_i}+{extraStudents_i}}{{total_i}+{extraStudents_i}}}
$$
where $n$ is the number of classes of students, and $extraStudents_i$ is the nunber of brilliant students that are assigned to $classes_i$.
And the constraint is
$$
g({extraStudents_0, extraStudents_1,...extraStudents_{n-1}})=\sum{extraStudents_i}-extraStudents=0
$$
This problem is equivalent to maximize $f$ subject to the constraint $g$. But maybe there is another constraint ${extraStudents_i}\in{\mathbb{Z}}$.


text:
Q: Help with calculating relative error in approximation of x So i have
$$x=\displaystyle\sum_{k=1}^{\infty}2^{-k}+\displaystyle\sum_{k=0}^{\infty}2^{-6k-1}$$
and i need to calculate relative error when approximating above x in $$MARC-32 \ \dots P(2,24,-127,127)$$
Hopefully the notation is understandable, basically it is a 32-bit computer that has base 2, significand is 24, exponents are in an interval [-127,127]
I know i will have to calculate:
$$x_{-}, x_{+}, fl(x)$$ which are essential for calculating the relative error, but i believe that is not the hardest part(i used a notation by which i normally do this, so i apologize if it's not known by everyone)
I am stuck in changing the x in binary. I would appreciate the help.

A: The storage of this value will depend upon how you calculate it. If you are getting the computer to increase $k$ by one (through some sort of loop) and add the values to a total it will get a different answer to if you calculate the answer mathematically then try to store that.
Option 1
Do the math first then store the answer. Mathematically $x=\frac{95}{63}$. If you use the process in my answer to your other question you'll get:
$$\frac{95}{63}=1.100000100000100001000001...$$
The 25th bit after the binary point is a one so as we can only 24 bits after the point we need to work out if we round up or down. As it is a one we round up the 24th bit.
As we have a leading one the 24 bits of the significant are therefore: 1000010000010000100001. The exponent is clearly zero. The stored value is equal to: $$1+2^{-1}+2^{-7}+2^{-13}+2^{-19}+2^{-24}=\frac{25298977}{16777216}$$
This is slightly more than the value of $x$ by: $\frac{31}{1056964608}\approx3\times10^{-8}$.
Option 2
You get the computer to work it out using a loop similar to:
for (k=0 to 50) //50 is big enough to use all bits
  total = total +2^-k+2^(-6*k-1)

After the 4th loop the second term doesn't contribute anything as the terms $2^{-25}$ onwards are smaller than can be stored in total which is of the order of 1.
Carrying the loop out will end up storing you the value: $1.100000100000100000011111$ which is equal to:
 $$\frac{25298975}{16777216}$$ The difference comes because all values equal to or lower that $2^{-25}$ can not be added on.
This will give a value below the real value of $x$ by: $\frac{95}{1056964608}\approx9\times10^{-8}$.

A: Remember that
$$
\sum_{k=1}^\infty2^{-k}=\frac12·\frac1{1-\frac12}=1
$$
to get the bit sequence directly from the definition of $x$. In the significant, bit 23, 24, 25 are zero, bit 26 would be 1.


text:
Q: Need to populate several labels from XML file, is there a faster way? I have an XML file I am loading and breaking the document down into Ienumerable then putting each element into a label on a winform. sofar I have the following code, which works
public void PopulateGameBoard()
    {
         XDocument gameFiles = XDocument.Parse(Properties.Resources.Jeopardy);

         IEnumerable<string> categories =
             from category in gameFiles.Descendants("category")
             select (string)category.Attribute("name");

         string first = categories.ElementAt(0);
         cat1HeaderLabel.Text = first;
         string second = categories.ElementAt(1);
         cat2HeaderLabel.Text = second;
         string third = categories.ElementAt(2);
         cat3Label.Text = third;
         string fourth = categories.ElementAt(3);
         cat4Label.Text = fourth;
         string fifth = categories.ElementAt(4);
         cat5Label.Text = fifth;

    }

The final product is  Jeopardy Game Board where the categories and questions will be pulled from an XML file
This is the first of 5 rows that I will need to do this with (5 lists going into 5 rows). I am wondering if there is a better way to code this where I dont end up with 25 statements assigning a variabel to an ElementAt() and then 25 assignments of that variable.

A: Here I tried to create labels dynamically and assign values to them,This is a hand written code,so no guarentee it will compile ,make necessary changes
public void PopulateGameBoard()
{
     XDocument gameFiles = XDocument.Parse(Properties.Resources.Jeopardy);
     IEnumerable<string> categories =
         from category in gameFiles.Descendants("category")
         select (string)category.Attribute("name");
     Label[] cat1HeaderLabel= new Label[100];
     int i = 0;
       categories.Each(p =>
       {
           cat1HeaderLabel[i] = new Label();
           cat1HeaderLabel[i].Text = p;
           this.Form.Controls.Add(cat1HeaderLabel[i]);
           i++;
       });
}


text:
Q: Using require in TypeScript in order to load modules in the browser I have a web page on which I would like to use a TypeScript file I created. That web page uses a few modules, most importantly vega-lite, papaparse, and tabulator-tables. I would like to load them into the code via TypeScript, and when I attempt to write into the TS file a line such as the following:

const Papa = require("papaparse");

I don't get any errors on compiling, but when I load the HTML page I get a require is not defined error. I suspect it has something to do with my tsconfig.json, so I'm attaching it. Does anyone know how to solve this? The structure of my project is:
node_modules
public
    index.html
    styles.css
    index.js
src
    index.ts

And this is my tsconfig.json file:
{
  "compilerOptions":
  {
    "target": "es2021",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "./public",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": false,
    "strictNullChecks": false,
    "skipLibCheck": true
  }
}


text:
Q: Grade averaging in assembly language crashes I am trying to adapt some code we developed in class and am having a problem.
Here is the code we developed in class -- take 10 numbers, average them.
    include irvine32.inc
    Title GetTen
    .data
    inprompt db "Enter a number:",0
    sumMsg db "The sum of your numbers is ",0
    avgMsg db "The average of your number is ",0
    nums    db 10 dup(0) ;duplicate nums 10 times for indirect
    sum db 0
    divisor db 0
   .code

    main proc

    call getValues
    call sumValues
    call calcAvg

    exit
    jmp ENDITALL
    ;SUM 10 VALUES
    sumValues proc
    mov ebx,offset nums
    mov ecx, lengthof nums
    sub eax,eax
    SumLoop:
    add al,[ebx]
    add ebx,1
    loop SumLoop
    mov sum,al
    mov edx,offset sumMsg
    call WriteString
    call WriteInt

    call crlf
    ret
    sumValues endp

    ;READ 10 Numbers in proc
    getValues PROC
    mov ebx, offset nums
    mov ecx, lengthof nums
    InLoop:
    mov edx, offset inprompt
    call WriteString
    call ReadInt
    call crlf
    mov [ebx],al
    add ebx,1 ;add one to advance the nums array
    loop InLoop
    ret
    getValues endp

    ;--------Calculate the average
    calcAvg proc
    mov ebx, lengthof nums
    mov divisor,bl
    call dumpregs
    div bl ;the first operand is always eax
   ;call dumpregs
    mov edx, offset avgMsg
    call writestring
    movsx eax,al
   ;call dumpregs
    call writeInt
    ret
    calcAvg endp

    ENDITALL:

    main endp
    end main

That code runs great.  I need to adapt that into a grade calculator (put in ten numeric grades, average them, then compare the average to some pre-canned values to assign a numeric grade.)   All basic stuff, except AL doesn't like numbers like 100 too much -- if I enter, say, 5 100's and 5 80's it tells me the sum of the numbers is 132 and the average is 13.
OK, so I tried both AH and EAX in place of AL, figuring that there wasn't enough room in AL.  Here is that code.
    include irvine32.inc
    Title GradeAverage
    .data
    inprompt db "Enter a grade:",0
    sumMsg db "The sum of your numbers is ",0
    avgMsg db "The average of your grade is ",0
    nums    dd 10 dup(0) ;duplicate nums 10 times for indirect
    sum dd 0
    divisor dd 0
   .code

   main proc

  call getValues
  call sumValues
  call calcAvg

  exit
  jmp ENDITALL
  ;SUM 10 VALUES
  sumValues proc
  mov ebx,offset nums
  mov ecx, lengthof nums
  sub eax,eax
  SumLoop:
  add eax,[ebx]
  add ebx,1
  loop SumLoop
  ;mov sum,eax ;I shouldn't even need this anymore since we're using all the       same size.
  mov edx,offset sumMsg
  call WriteString
  call WriteInt

  call crlf
  ret
  sumValues endp

  ;READ 10 Numbers in proc
  getValues PROC
  mov ebx, offset nums
  mov ecx, lengthof nums
  InLoop:
  mov edx, offset inprompt
  call WriteString
  call ReadInt
  call crlf
  mov [ebx],eax
  add ebx,1 ;add one to advance the nums array
  loop InLoop
  ret
  getValues endp

  ;--------Calculate the average
  calcAvg proc
  mov esi, lengthof nums
  mov divisor,esi
  call dumpregs
  div esi ;the first operand is always eax
 ;call dumpregs
  mov edx, offset avgMsg
  call writestring
  ;movsx eax,eax
  ;call dumpregs
  call writeInt
  ret
  calcAvg endp

  ENDITALL:

  main endp
  end main

This code crashes.  It will take the numbers, and if I put, say 100 5 times and 50 5 times, it tells me the sum is -42041476 and then crashes.
It's probably something really basic, but I'm at a loss.  What am I doing wrong here?

A: You have at least one bug and some conceptual issues.
Concept: EAX is the name of a 32 bit register; the lower 16 bits of that register are called AX. In AX the lower 8 bits are called AL and the higher - AH.
Concept: an N-bit instruction that involves memory reads/writes N bits in memory. When you use AL you'd read/write 8 bits, and when you use EAX you'd read/write 32 bits.
.... so your main sum loop has a bug, it reads 32 bits from memory every time:
 SumLoop:
  add eax,[ebx]
  add ebx,1
  loop SumLoop

Lets say you have bytes [1,2,3,4] at [EBX]. First loop will add 1234H to EAX, subsequent loops are unknown because the memory you're reading is out of the bounds of your array. The crash may be due to this or something entirely different.
If your data are bytes you can read them one-by-one:
  xor edx, edx
SumLoop:
  mov dl,[ebx]
  add eax, edx
  inc ebx
  loop SumLoop

And in your average proc you have div esi but before you div your EDX must be zeroed because you're dividing [EDX,EAX] 64-bit number to ESI. You need to add xor dx,dx before that instruction


text:
Q: Installing OpenCL on XeonPhi Because I don't have device to test so I ask this question
If i use OpenCL on XeonPhi I only want install the driver and runtimes of XeonPhi (https://software.intel.com/en-us/articles/opencl-drivers), then OpenCL can run and complier code, is that right ? And how about MPSS (https://software.intel.com/en-us/articles/intel-manycore-platform-software-stack-mpss-archive#33n-2) i see when deverlop OpenCL on Linux, must install MPSS and driver and runtimes of XeonPhi.
I haven't found a document introduced the detail about using OpenCL on XeonPHi on WindowOS , Can you share with me some document about this ?

A: The Intel® Xeon Phi™ coprocessor always runs Linux. However, you can run either Linux or Windows on the host system. Regardless of which operating system you run on your host, you will always install a version of the MPSS.
If you want to run Windows on your host system and use OpenCL with the coprocessor, you would use the OpenCL™ Runtime 14.2 for Intel® CPU and Intel® Xeon Phi™ coprocessors for Windows* (64-bit) which would give you a Windows compatible runtime for your host and a Linux compatible runtime for the coprocessor. There is no OpenCL™ Code Builder for Windows, independent of the Intel® INDE and Intel® Media Server Studio, neither of which support the 14.2 version of the runtime.


text:
Q: How to limit the number of service launched on one CoreOS node Here is my problem :
fleetctl list-units

UNIT                            MACHINE
processing-node@1.service       X.Y.Z.86
processing-node@10.service      X.Y.Z.150
processing-node@11.service      X.Y.Z.48
processing-node@12.service      X.Y.Z.48
processing-node@13.service      X.Y.Z.48
processing-node@14.service      X.Y.Z.86
processing-node@15.service      X.Y.Z.82
processing-node@16.service      X.Y.Z.48
processing-node@2.service       X.Y.Z.248
processing-node@3.service       X.Y.Z.48
processing-node@4.service       X.Y.Z.85
processing-node@5.service       X.Y.Z.48
processing-node@6.service       X.Y.Z.48
processing-node@7.service       X.Y.Z.48
processing-node@8.service       X.Y.Z.87
processing-node@9.service       X.Y.Z.248
worker-cache@1.service          X.Y.Z.248
worker-cache@2.service          X.Y.Z.222
worker-cache@3.service          X.Y.Z.87
worker-cache@4.service          X.Y.Z.150
worker-cache@5.service          X.Y.Z.82
worker-cache@6.service          X.Y.Z.85
worker-cache@7.service          X.Y.Z.48
worker-cache@8.service          X.Y.Z.86

The cluster is composed of ten machines. The worker-cache units needs a lot of calculation power so they exclude each other in the service file :
tail -2 worker-cache@.service

[X-Fleet]
Conflicts=worker-cache@*

So we have only one worker-cache unit per node. The processing-nodes units need less power and can be spawned on the same machines as the worker-cache units but I would like to have maximum two of them per machines which is definitely not the case actually :
processing-node@11.service      X.Y.Z.48
processing-node@12.service      X.Y.Z.48
processing-node@13.service      X.Y.Z.48
processing-node@16.service      X.Y.Z.48
processing-node@3.service       X.Y.Z.48
processing-node@5.service       X.Y.Z.48
processing-node@6.service       X.Y.Z.48
processing-node@7.service       X.Y.Z.48

Is there a way to do that ?


text:
Q: Unable to display TodoList view in browser Iam learning Backbone JS, Iam trying to display TodosList, but not rendering. However, iam able to get collection data from the server.
Could you please tell me what went wrong in the below code.
Here is the code:

<link rel="stylesheet"
    href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css">

And also Iam not sure whether 'fetch' is pre-defined event or not? When to use 'reset' event , when to use 'fetch' event? They both look similar to me.

A: There is no 'fetch' event so your listenTo doesn't do anything useful. Usually you'd reset the whole collection when you fetch it:
this.collection.fetch({ reset: true });

and then listen for a 'reset' event:
this.listenTo(this.collection, 'reset', this.render);

The reset:true option to fetch tells fetch to completely replace the collection's content with the fetched data in one operation; then the collection will trigger a 'reset' event when the fetch is all done and you're listener will convert that to a render call.
Your initialize should look more like:
initialize: function(){
    this.listenTo(this.collection, 'reset', this.render);
    this.collection.fetch({ reset: true });
}


text:
Q: User-Defined settings for WatchKit I am using User-Defined settings (for example CustomAppBundleId) to change bundle identifier for different configurations. In the app's plist file I set CFBundleIdentifier to ${CustomAppBundleId}. For Release configuration I use bundle:
com.yourcompany.${PRODUCT_NAME:rfc1034identifier}

and for AdHoc I use:
com.yourcompany.adhoc.${PRODUCT_NAME:rfc1034identifier}

Now I added WatchKit Extension and WatchKit App. For WatchKit Extension bundle identifier I can use the same approach. I also have to change WKAppBundleIdentifier to match the bundle identifier in the WatchKit App. Again, I could use  User-Defined settings. Now the last bit is WatchKit App. Unfortunately WatchKit App doesn't have an option to add User-Defined settings but I need to set the right values for CFBundleIdentifier and WKCompanionAppBundleIdentifier (that is equal to CustomAppBundleId in the app). Is there any way I can do it? Or should I use different approach?

A: Define your "User-Defined" variables in project's Build Settings rather than in target's. That way you will have the same user defined variables automatically available (inherited) in WatchKit Extension and App target.

Btw make sure you have the latest Xcode 6.3 from the App Store. This version (and most recent Xcode 6.3 beta 4) already allow you to define custom "User-Defined" in Build Settings).
Previous versions were simply missing "Build Settings" tab in WatchKit App target, but if you were brave enough, you could have modify those manually in plain text editor :-)

A: Update to Xcode 6.3.
In 6.3 you will have additional tabs for target configuration that should provide what you need.
But I'm almost sure you will face issues with the WatchKit App Storyboard.
In the Scenes > Identity Inspector > Custom Class you have to set the correct module - that is not possible if you have more than 1 (if you do not have more than one I would be more than interested in your setup)
I solved that issue with a pre-action script that updates the storyboard XML accordingly


text:
Q: Swift UITabBarItem as a UIButton I tried to implement a UITabBar and now I am not able to retreive a callback from a method when an item was selected. Is there a possibillity to just create a @IBAction func therefore? Or do I need to do something else?

A: In order to implement UITabBar button, your view controller should conform to UITabBarDelegate protocol. You need to implement:
Swift:
func tabBar(_ tabBar: UITabBar, didSelectItem item: UITabBarItem!)

Objective-c:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item

You also need to set the delegate (tabBar.delegate = self) in the viewDidLoad of your ViewController
Edit: Swift 3 answer:
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

}

A: Your view controller should conform to UITabBarDelegate and implement:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

This method is called when the user selects a tab (i.e. UITabBarItem).

A: I finally solved the problem. I had some trouble with the Delegator-class and normal class.
This fixed my problem : tabBar.delegate = self in the Main-Controllerclass


text:
Q: Django CBV - change FBV to CBV Writing my first "real" django project I realized that my views are really huge. I try to convert it into CBV (as additional django training). Here are my fbv views:
def index(request):
    context = {}
    categories = Category.objects.select_related()
    subcategories = SubCategory.objects.all()
    context['categories'] = categories
    context['subcategories'] = subcategories
    return render(request, 'mainapp/index.html', context)

def category(request, category_name_slug):
    context = {}
    try:
        category = Category.objects.get(slug=category_name_slug)
        subcategory = SubCategory.objects.filter(category=category)
        context['subcategories'] = subcategory
        context['category'] = category
    except Category.DoesNotExist:
        raise Http404("Category doesn't exist")
    return render(request, 'mainapp/category.html', context)

def subcategory(request, category_name_slug, subcategory_name_slug):

    context = {}
    form = SiteAddForm(initial={'url': 'http://'})
    context['form'] = form
    try:
        category = Category.objects.get(slug=category_name_slug)
        subcategory = SubCategory.objects.filter(category=category
                                                 ).get(slug=subcategory_name_slug)
        sites = Site.objects.filter(subcategory=subcategory, is_active=True)
        context['subcategory'] = subcategory
        context['category'] = category
        context['sites'] = sites
    except (SubCategory.DoesNotExist, Category.DoesNotExist):
        raise Http404("Nie ma takiej strony")
    if request.method == 'POST':
        form = SiteAddForm(request.POST)
        if form.is_valid():
            siteurl = form.cleaned_data['url']
            context['siteurl'] = siteurl
            try:
                page = AddNewSite(siteurl)
            except:
                print('ERRROR')
                context['Error'] = "URL is not responding"
                return render(request, 'mainapp/subcategory.html', context)
            title = page.title()
            description = page.description()
            keywords = page.keywords()
            if page.check_url_in_database():
                context['Error'] = "Site already in database"
                return render(request, 'mainapp/subcategory.html', context)
            else:
                form_extended = SiteAddFormFull(initial={'url': siteurl, 'name':
                                                     title, 'description':
                                                     description, 'keywords':
                                                     keywords})
            context['form_extended'] = form_extended
            if request.method == 'POST':
                form_extended = SiteAddFormFull(request.POST)
                if form_extended.is_valid():
                    keywords = form_extended.cleaned_data['keywords']
                    name = form_extended.cleaned_data['name']
                    description = form_extended.cleaned_data['description']
                    page.add_site(category, subcategory, keywords,
                                  description, name, siteurl)
                    context['added_site'] = 'Thank you - site was added'
                    messages.add_message(request, messages.SUCCESS, 'Dodano!!')

return render(request, 'mainapp/subcategory.html', context)

How Can I simpy write my base view (index) using CBV. It should look that way:
Category:
    Sub1
    Sub2
Category2:
    Sub2a
    Sub2b
Should I learn CBV or stay using FBV (it works)? Below are my Category, Subcategory models:
class Category(models.Model):
    name = models.CharField(max_length=30, unique=True,
                        verbose_name='Category name')
    slug = models.SlugField()
    image = models.ImageField(upload_to='category_images',
                          verbose_name="Category image",
                          blank=True)
    description = models.TextField(default='Description',
                               verbose_name="Category description")

    class Meta:
        verbose_name_plural = "Categories"

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def image_thumb(self):
        if self.image:
            return '<img src="/media/%s" width="40" height="40" />' % (self.image)
        else:
            return('')
    image_thumb.short_description = 'Thumb'
    image_thumb.allow_tags = True

    def __str__(self):
        return self.name

class SubCategory(models.Model):
    category = models.ForeignKey(
        'Category',
        related_name='subcategory',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
)
    name = models.CharField(max_length=30)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(SubCategory, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = "Subcategories"

    def __str__(self):
        return self.name

A: I'm an advocate of CBV, it can make life a lot easier when trying to reuse code. There are also a ton of pre-defined generic views that only need a small tweaks for most instances. For your example index, you can use a TemplateView:
class IndexView(TemplateView):
    template_name = "mainapp/index.html"

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['categories'] = Category.objects.select_related()
        context['subcategories'] = SubCategory.objects.all()
        return context


text:
Q: EC2 Instance Freezes I am facing sudden freezes in one of my instances.
Here are some details about the instance:
Type: t2.micro
Region: ap-southeast-1
Platform: Ubuntu
Platform details: Linux/UNIX

I have two apps running on this instance, and also I have a celery service working there.
these freezes start to happen since I run the celery service.
I am not really sure how to find and trace the issue.
Thanks.

A: When an EC2 instance freezes that is quite often due to it running out of memory. So what you can do is to enable memory metrics (there is a guide in the AWS documentation how to do it) on your EC2 Celery nodes, and next time this happens check memory utilisation to confirm that machine was out of memory when it froze.

A: You instance probably has high memory usage (probably memory leak) or high CPU usage (we had also this case)
you can use the tool 'atop' to monitor your CPU, Memory resources. This tool gives historical data of which process was utilizing maximum resources For more information, please refer the below links :
[+] https://www.tecmint.com/how-to-install-atop-to-monitor-logging-activity-of-linux-system-processes/
[+] https://haydenjames.io/use-atop-linux-server-performance-analysis/
You have mentioned that the issue gets resolved on rebooting the instance. It might be possible that memory crunch is happening on the instance. Rebooting the instance frees up the resources for sometime. However, as soon as the processes start coming up they may start consuming more resources making the instance unresponsive again and again.
I would recommend you to install(if already not installed) tools like atop, which will store the historical data of resource utilization and that will helps to find out more details like which process was consuming most of the resource etc and it will helps to troubleshoot the issue better. If based on atop logs you believe that your application requires more resources than offered by t2.micro then you may consider upgrading the instance type to one which offers more cpu/memory


text:
Q: Parasoft c++ test link unit test error My project can build & link successfully, and there is no compile error about unit test.
The error information only "Test execution: error linking test executable for Test unit for selected sources."
So, anyone can give some suggestion? Thanks.
I use VS2005, and parasoft c++ test for VS 9.1.

A: If you have any questions about Parasoft products, I suggest emailing their support team at support@parasoft.com, you could also call them toll free at (888) 305-0041.
In addition you will probably get your question answered faster if you post this on their forum. link provided below.
http://forums.parasoft.com/


text:
Q: Calculating proportion of polygon by value in QGIS? Using QGIS, I have a single-band raster with with multiple counties.  I have reclassified the pixels into  2 categories, using a singleband pseudocolor, based on their value ( > or < 3800), corresponding to non-forest or forest land.
How do I calculate the proportion of pixels that is in each of the 2 categories, in each county?
I have a lot of images over a lot of years so I would prefer to not take the route the I figured out - converting to shp, exporting as csv, sorting csv and calculating percentages in Excel.

A: Zonal Statistics https://docs.qgis.org/2.2/en/docs/user_manual/plugins/plugins_zonal_statistics.html
Or just extract the rasters by the polygons Clip raster layer with *raster* mask layer in QGIS
It has been while since I used the zonal statistics but I remember it give a count value.

A: I know this is an old question, but I wanted to give input as this is something I just had to do. I have a raster with a single band and unique values representing land cover usage and polygons representing historical wildfires. I used the Zonal Histogram tool in QGIS 3.8:

to add columns with each value and the count of pixels that contain that value within the wildfire footprint (i.e. i want to get % land use within fire footprint):


text:
Q: mssql query results order not matching the select clause I'm using npm mssql lib with NodeJS to execute a query from SQL Server with the following query
select name, surname, id from clients

the query result is correct, (in SQL Server management studio), but the structure of the JSON object returned to the server is mixed like so:
{
  surname :"foo",
  id:"bar",
  name:"foo bar"
}

How can I tell the SQL Server or the mssql to keep the order of the returned JSON identical to the select clause in the query?


text:
Q: Python code is weirdly jumping to the except block So I am going nuts here trying to figure out what is happening, I have added a TON of print statements to see what is going on with the code and I cannot make any sense of why it is jumping around like it is...
I know the code looks hacky, and it is, but I cannot see why it is jumping into the except block....
The output I get is this:
add audio function
makinf file list
doing if statement
[]
before try
inside try
Is there an audio file_URL ready?:

The code is below, it seems to be missing print statement and just disintegrating somewhere and jumping to the except block....
def add_audio(self, word):
    '''function for adding audio path to a word'''
    print "add audio function"
    path = "mypath/%s/" % (self.language_ISO)
    print 'makinf file list'
    existing_file = glob.glob("%s/%s.*" % (path, word)) + glob.glob('%s/%s[0-9].*' % (path, word))
    print ' doing if statement'
    print existing_file
    if existing_file:
        print 'into if statement'
        if self.choice("\nThere is an existing audio file for this word...\nWould you like to add another?: "):
            add_another = True
            print add_another
        else:
            return (existing_file, "N/A")
    print 'before try'
    try:
        print "inside try"
        if add_another:
            print 'about to raise error'
            #Made this variable and thre an error to force the except loop to run and add another file
            raise NameError('throwing an intentional error as a hack')
        print 'made it past try but failed somewhere else'
        wiktionary_page = urllib2.urlopen("http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.wiktionary_prefix, word))
        print 'made it past try but failed somewhere fromstring'
        wiktionary_page = fromstring(wiktionary_page.read())
        print 'made it past try but failed somewhere xpath'
        file_URL = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0]
        print 'made it past try but failed somewhere wget'
        os.popen("wget -O %s/%s.ogg --progress=bar 'http:%s'" % (path, word, file_URL))
        print("\nFile Downloaded from wiktionary successfully!\n")
        return ("%s/%s.ogg" % (path, word), file_URL)
    except:
        if self.choice("Is there an audio file_URL ready?: "):
            file_URL = raw_input("What is the file_URL?: ")
            print "\n%s\n" % (file_URL)
            while not self.choice("Is this correct?: "):
                file_URL = raw_input("What is the file_URL")
                time.sleep(.5)
                print "\n%s\n" % (file_URL)
            file_extension = file_URL.split('.')[-1]
            file_number = len(existing_file)
            file_path_name = "%s/%s%d.%s" % (path, word, file_number, file_extension)
            os.popen("wget -O %s --progress=bar '%s'" % (file_path_name, file_URL))
            return ("%s/%s%d.%s" % (file_path_name, file_URL))
        elif not existing_file:
            with open(self.logfile, 'a') as f:
                f.write("AUDIO: Need to record audio for %s\n" % (word))
            return ("/", "N/A")

A: What I should have been doing was exactly what @smarx said. I should have been printing the exception by doing this
except Exception as e:
    print str(e)

That will print the exception that is being raised and help me to debug where it went wrong. Outside of that I should have been custom handling different kinds of exceptions


text:
Q: Is this the correct way to compile if I am using explicit instantiation? For maintainability reasons, I need to split the declaration and the definition of a template class. I want to know what is the correct way to compile the file if I'm using this design choice.
So, as a minimal reproducible example (using templated function just to be more compact) consider:
Header file foo.hpp where I declare a templated function myfun
//file foo.hpp
#ifndef foo_hpp
#define foo_hpp

template <typename T>
void myfun();

#endif /* foo_hpp */

Source file foo.cpp file where I define the function myfun
//file foo.cpp
#include "foo.hpp"
#include <iostream>

template <typename T>
void myfun(){
    std::cout << "Call to myfunc \n";
}

template void myfun<int>();

Finally, the main.cpp file that uses myfun<int>
#include "foo.hpp"

int main(){

    myfun<int>();
    return 0;
}

I would compile and generate the executable test from command line just by doing:
g++ -o test foo.cpp main.cpp

because in this way the linker is able to see the instantiation of myfun<int>.
Is this the correct way to compile ?

EDIT:
Another possibility is to use a `.tpp file
//file foo.tpp
#include "foo.hpp"
#include <iostream>

template <typename T>
void myfun(){
    std::cout << "Call to myfunc \n";
}

and put it into the .hpp file
//file foo.hpp
#ifndef foo_hpp
#define foo_hpp

template <typename T>
void myfun();

#include "foo.tpp"

#endif /* foo_hpp */

Finally, the main.cpp file that uses myfun<int>
#include "foo.hpp"

int main(){

    myfun<int>();
    return 0;
}

Now, I compile just by doing:
g++ -o test main.cpp

This works, but as I include the .tpp (which includes the header) into the header, it seems I am including the header into itself, and it's pretty weird


text: Q: Dropbox LAN sync - hint for an IP address In my work network UDP broadcast networks are isolated between the WiFi and wired channels, so LAN sync discovery does not work. Is there a way to explicitly tell Dropbox to try a specific IP address for LAN sync?


text:
Q: (Cross platform) check a file path is absolute without using Pathname library I need a cross platform way to check if a given file path is absolute without using the Pathname library. The only library I'd wish to rely on for this would be File. It needs to be cross-platform and cross-implementation, so it should work regardless of it being Ruby MRI, JRuby, Rubinius… etc.
I wish to use pure Ruby, no C or Java. I can't think of a robust way.

A: def absolute_path?(path)
  File.expand_path(path) == path
end


text:
Q: autoplay slider for ionic 4 Hi have been trying to achieve auto slide for Ionic 4 but it seems like is not working...below is the code

page.ts
=========
 @ViewChild(IonSlides) slider: IonSlides;
  options: {
    autoplay: true
  }
HTML
========
     <ion-slides #IonSlides pager="true" [options]="options" (ionSlidesDidLoad)="stopSlideAutoplay()">
          <ion-slide>
             <ion-img src="assets/whitebg.svg"></ion-img>
            </ion-slide>

          <ion-slide>
              <ion-img src="assets/whitebg.svg"></ion-img>
          </ion-slide>
          </ion-slides>

A: page.ts file:
import {IonSlides}          from '@ionic/angular';
import {ViewChild } from '@angular/core';

export class page implements OnInit {
    @ViewChild('mySlider') slider: IonSlides;
    sliderOpts = {
        autoplay: true,
        speed: 1000,
        zoom: {
          maxRatio: 5
        }
      };
    }

page.html file:
 <ion-slides #mySlider pager="true"
         [options]="sliderOpts" >
        <ion-slide></ion-slide>
   </ion-slides>

A: Try this code by setting autoplay: true,
<ion-slides [options]="sliderOpts" #slider>
     <ion-slide>
             <ion-img src="assets/whitebg.svg"></ion-img>
            </ion-slide>

          <ion-slide>
              <ion-img src="assets/whitebg.svg"></ion-img>
          </ion-slide>
</ion-slides>

and in TS
@ViewChild('slider', { read: ElementRef })slider: ElementRef;
  img: any;

  sliderOpts = {
    autoplay: true,
    zoom: {
      maxRatio: 5
    }
  };

A: in your .ts file
import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";

 @ViewChild("slider", { read: ElementRef }) slider: ElementRef;

  sliderOpts = {
    autoplay: true,
    zoom: {
      maxRatio: 5
    }
  };

in html file
<ion-slides
    (ionSlideDidChange)="slideChanged()"
    #slider
    [options]="sliderOpts"
  >
    <ion-slide>

        {{ "onboard.welcome" | translate }}

{{ "onboard.welcomeSub" | translate }}

    </ion-slide>
    <ion-slide>

{{ "onboard.pay" | translate }}

{{ "onboard.paySub" | translate }}

    </ion-slide>
    <ion-slide>

{{ "onboard.send&received" | translate }}

        {{ "onboard.send&receivedSub" | translate }}

        {{ "onboard.send&receivedSub2" | translate }}

    </ion-slide>

    <ion-slide>

{{ "onboard.wallet" | translate }}

{{ "onboard.walletSub" | translate }}

    </ion-slide>
  </ion-slides>


text:
Q: Showing summation is bounded I'm currently taking a Comp Sci class that is reviewing Calculus 2. I have a question:
Show that the summation $\sum_{i=1}^{n}\frac{1}{i^2}$ is bounded above by a constant
I realize that this question is already answered here
Showing that the sum $\sum_{k=1}^n \frac1{k^2}$ is bounded by a constant
Could anyone explain it to me further? I believe I'm supposed to use p-series test or integral test to complete

A: You can try the following, pretty similar to that link's, approach:
$$\frac1{k^2}\le\frac1{k(k-1)}=\frac1{k-1}-\frac1k\implies$$
$$\sum_{k=2}^N\frac1{k^2}\le\sum_{k=2}^N\left(\frac1{k-1}-\frac1k\right)=1-\frac12+\frac12-\frac13+\frac13-\frac14+\ldots+\frac1{N-1}-\frac1N=$$
$$=1-\frac1N\le 1$$
and you've proved boundedness for any $\;N\in\Bbb N$
Notes:  Observe that in the above we take the sum from $\;n=2\;$ and not, as you did, from $\;n=1\;$ . Answer:
(1) Why?
(2) Explain why the above doesn't affect the boundedness of the original series.

A: Here is an approach
$$ \sum_{k=1}^{n}\frac{1}{i^2} = 1 + \sum_{k=2}^{n}\frac{1}{i^2} \leq 1 + \int_{1}^{n}\frac{dx}{x^2}= 2 - \frac{1}{n}\leq 2,\, \quad \forall n\in \mathbb{N}.$$


text:
Q: how to convert webp image to jpeg or png by using intervention image laravel I am developing an app in Laravel Framework (PHP). I want to upload image which have webp format and then convert it to jpeg or png image format. After converting the image i also want to upload it to s3 bucket.

A: Firstly we can use Intervention Image library. We must have php 7 and gd library installed. I am writing the commands to install gd library and webp library below (for ubuntu) :
sudo apt-get update
sudo apt-get install webp
sudo apt-get install php7.0-gd (check php version and then install accordingly)

now check file extension and if extension is webp, select your output file extension
$extension = $this->file->extension();

if($this->file->getMimeType() == 'image/webp'){
    $extension = 'png';
}
// Generate a random filename
$fileName = time() . '_' . strtolower(uniqid()) . '.' . $extension;

Now encode the image to desired format
if($this->file->getMimeType() == 'image/webp'){
    $image = $image->encode($extension);
}
$image = $image->stream();

Now upload the image to s3 bucket
Storage::disk('s3')->put($folderName . '/' . $fileName, $imageNormal->__toString());


text:
Q: Backup Error (.bak) I need to backup the database in SQL Server 2014.
When I am trying to do so, I am facing this problem which is not saving backup as a (.bak) extension.
And when I try to select (Files and filegroups) and then select (the database needed to be backed up) but nothing seems to work right.

A: For Backup component, click Database.

*

*Either accept the default backup set name suggested in the Name text box, or enter a different name for the backup set.

*Optionally, in the Description text box, enter a description of the backup set.

*Choose the type of backup destination by clicking Disk, Tape or URL. To select the paths of up to 64 disk or tape drives containing a single media set, click Add. The selected paths are displayed in the Backup to list box.
To remove a backup destination, select it and click Remove. To view the contents of a backup destination, select it and click Contents.
OR
you can simply use T-SQL to achieve this:
To backup the database:
Use <your database name here>
BACKUP DATABASE <your database name here>
TO DISK = 'path where you want to  backup.bak';

To backup filegroup :
    Use <your database name here>
    BACKUP DATABASE <your database name here>
    FILEGROUP = 'name of the file group'
    TO DISK = 'path where you want to save backup.bak';

A: 1) select your database and press right-click , then choose tasks then backup.
2) Then change the backup type to transaction log.
3)Then press Add and click on the box (...)
4) write the database name.bak in the (File name) and don't forget to write this extension (.bak)
5)Finally write ok 3 times it should work fine


text:
Q: Passing arguments to runnable class in Spring's Taskexecutor I have a trouble understanding how to connect all the parts with Taskexecutor.
I have a task I created, BidProposalTask. (a class which implements Runnable)
the task constuctor has one argument, and needs Autowiring for DB access, etc.
I came up with this code for the executor class:
public class ExecuteBidProposalTask {

    private TaskExecutor taskExecutor;
    private BidProposalTask bidProposalTask;

    public ExecuteBidProposalTask(TaskExecutor taskExecutor,
        BidProposalTask bidProposalTask) {
    super();
    this.taskExecutor = taskExecutor;
    this.bidProposalTask = bidProposalTask;
    }

    public void start() {
    taskExecutor.execute(bidProposalTask);
    }

}

and the following XML context configuration:
<bean id="taskExecutor"
    class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="queueCapacity" value="25" />
</bean>

as I saw in Spring's documentation, I created a TaskExecutor bean, however, the problem is that the BidProposalTask also needs to be injected. it isn't a singleton, I need to create it over and over in the project with different argument for the constructor.
basically the question is how to autowire a non-singleton bean, so it's autowiring will also work ?
This is quite complicated to explain, so I hope you understand my question...

A: You could make your ExecuteBidProposalTask class ApplicationContextAware (essentially injecting the application context into the bean). Then you can declare your BidProposalTask bean in your context file and make the scope="prototype". Then in your start method in ExecuteBidProposalTask you can do: context.getBean("bidProposalTask"); and pass that to the executor. Since you declared the scope as prototype, a new instance (not a singleton) will be constructed and returned when you request the bean.


text:
Q: Azure AppService URL Rewriting I have three web applications that I am trying to host in one single AppService in Azure.
One of the Web Applications is a simple SPA Angular App and the other two are ASP.NET Core WebAPI Applications.
Each of the two WebAPI apps have their routes defined in code as;
/api/{endpoint}

These routes cannot be changed and must remain as is.
In my AppService, I have multiple Virtual Directories defined to host all these separate applications.
the directory structure is as follows;

The Angular app is hosted in the /atlanta and /colton virtual directories and is accessible without issue.
Each of the WebAPI Applications are hosted in each of the other two Virtual Directories.
When the angular app makes a request to one of the APIs, it issues an HTTP request to either /{region}/api or /{region}/security respectively.
The issue I am having is that the APIs are returning 404 errors because the route /{region}/security/{endpoint} is not defined. The correct route would be /api/{endpoint}.
I am pretty sure I can resolve this issue by using URL Rewriting in my web.config, but thus far I have been unable to get this work correctly. Here is one of my URL Rewrite attempts;
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <rewrite>
        <globalRules>
          <rule name="SecurityAPI">
            <match url="/atlanta/security/*" />
            <action type="Rewrite" url="/api/{R:0}"  />
          </rule>
        </globalRules>
      </rewrite>
      <handlers>
        <add name="aspNetCore" path="/atlanta/security/*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments="HMS.Security.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
    </system.webServer>
  </location>
</configuration>

How can I resolve this issue and get the HTTP requests to get routed to the correct endpoints?


text:
Q: Submit button not effective in a form using selenium in IE11 after inserting data in inputs and selecting dropdown option My form (which is inside a dropdown menu) has 3 dropdowns (select option) and 2 texts input. This form is used to apply filters to a list of items. I am able to fill my inputs and to select my options without the use of a JavascriptExecutor, it works fine with .sendKeys("Text") for text inputs and sendKeys(Keys.ARROW_DOWN) for the dropdown options.
But, when I do btn.submit() or btn.sendKeys("\n") or btn.sendKeys(Keys.ENTER) or btn.click(), it clicks the button and the dropdown menu which contains the form disappears, but the page doesn't refresh. So I am able to click the button with selenium (and even if I force it manually I cannot click the submit button, but the button does not trigger anything.
I have been stuck on this issue for 3 days. I tried to find the answer to my problem but the IEDriver click issue's solution seems to be the diagnostic but it is not, because I am able to click the button.
Also, when I do the same tests on chrome using the chromedriver, everything works fine.
When I launch IE myself, navigate to the form, fill it in myself and submit it, everything works fine. So, the problem is when I insert data with java, it "disables" the submit button.
Using Kendo UI in IE11, IEDriverServer 64x 3.0.0 (also tried 32x ver.), Java JDK 1.8.0_25 in Windows 10 Pro
I set these capibilities to my IE driver
cap.setCapability("nativeEvents", false);
cap.setCapability("unexpectedAlertBehaviour", "accept");
cap.setCapability("ignoreProtectedModeSettings", true);
cap.setCapability("disable-popup-blocking", true);
cap.setCapability("enablePersistentHover", true);

I have been using selenium  for only two weeks but I am very familiar with Java. I read that IE has difficulties with forms here but they do not suggest a fix or a workaround.

A: After hours and hours trying to fix the second input in the form, the only way I was able to make it work is with a Robot Object.
I used this thread to help me convert my strings into robot.keyPress(KeyEvent.VK_EXAMPLE); and send them to the input. So, as soon as the form was opened, my java procedures looked like this:
    if (System.getProperty("browser").equals("ie")) {
        try {
            Robot robot = new Robot();
            //...
            //Rest of the robot code
            //...
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    } else {
        textField.clear();
        textField.sendKeys(textStr);
    }

So every action I had to do, I did them with Robot until I sublitted the form with a btn.click(); on the fom


text:
Q: How do socket.io implements the authorization I want to set the Authorization header in my websocket request to send a token.
I have found no native ways to do so (I settled for passing a token in the query parameters). I see that socket.io provides this functionality (altough I have not tryed it) and I'm wondering how it works under the hood

A: As a work around I use express-session, with express-socket.io-session (https://www.npmjs.com/package/express-socket.io-session)
This way I found it is easy to set an identifier when a user logs in.
p.s. all the methods in express-session docs, are available to you in express-socket.io-session.


text:
Q: Creating a trace plot in R I'm fairly new to using R so I'm sure I'm probably making a few rookie mistakes, but I can't seem to figure out how to create a trace plot for this homework question.
Here's the question:
On any given day, Gary is either cheerful (C), so-so (S), or glum (G). If he is cheerful today then he will be C, S, or G tomorrow with respective probabilities 0.5, 0.4, 0.1. If he is so-so today then he will be C, S, or G with probabilities 0.3, 0.4, 0.3. If he is glum today, he will be C, S, or G with probabilities 0.2, 0.3, 0.5. This can be used to make a 3-state Markov Chain with the following transition matrix:
[0.5 0.4 0.1
 0.3 0.4 0.3
 0.2 0.3 0.5]

Let the chain run for 50 times and create a trace plot for these 50 steps in R. You may write the code yourself or find an appropriate R package to simulate this.
I've made the matrix and I think I've run the chain 50 times, but can't get the traceplot() function to work.
library(coda)
library(markovchain)

p <- c(0.5, 0.4, 0.1, 0.3, 0.4, 0.3, 0.2, 0.3, 0.5)
PP <- matrix(p, 3, 3, byrow = TRUE)
mc1 <- new("markovchain", transitionMatrix = PP, states = c("C", "S", "G"), name = "Weather Forecast")
outs <- markovchainSequence(n = 50, markovchain = mc1, t0 = "C")
my_outs <- mcmc(outs)
traceplot(my_outs, smooth = FALSE, col = 1:6, type = "1", xlab = "Iterations", ylab = "oxygen", xlim = 50, ylim = 1)

This is the error I've been getting and I'm at a loss of what I need to do to get this to work or what other errors I've made before hand.
Error in plot.window(...) : invalid 'xlim' value
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log = log) :
  NAs introduced by coercion
2: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion

Here's the example trace plot our professor gave us


text:
Q: Toggle panning and marker movement lock in Google Maps API v3 I have and interface where a user can manage multiple locations for their business, adding additional locations and removing locations they no longer need.
In my interface I show a list of locations each with their own map.
My question is how do I lock a map to prevent the user from panning or moving the marker until they click on the "edit location" button?
Is there any sort of toggleMapLock function?
So far I have the following two methods. The lock(); method works fine, but the unlock(); method doesn't work for some reason.
lock: function() {
  this.map.disableDoubleClickZoom = true;
  this.map.draggable = false;
  this.map.keyboardShortcuts = false;
  this.map.navigationControl = false;
  this.map.scaleControl = false;
  this.map.scrollwheel = false;
  this.map.streetViewControl = false;
  this.marker.draggable = false;
},

unlock: function() {
  this.map.disableDoubleClickZoom = false;
  this.map.draggable = true;
  this.map.keyboardShortcuts = true;
  this.map.navigationControl = true;
  this.map.scaleControl = true;
  this.map.scrollwheel = true;
  this.map.streetViewControl = true;
  this.marker.draggable = true;
  console.log("unlock");
},

A: disableDoubleClickZoom (and the other properties listed) are not public properties on the Map class - they are properties of the MapOptions class. To change their value you need something similar to the following:
lock: function() {
  this.map.setOptions({
    disableDoubleClickZoom: true,
    draggable: false
  });
},

unlock: function() {
  this.map.setOptions({
    disableDoubleClickZoom: false,
    draggable: true
  });
}

This creates a MapOptions object (inside the {}'s) and passes it to SetOptions, which updates the current state of the Map based on the values passed in.


text:
Q: Can't download a GWT Plug In For IE I am not able to install the GWT Developer plugin for Internet Explorer.
After getting the yellow patch saying:
Development Mode requires the Google Web Toolkit Developer Plugin

I click on Download plugin. Instead of redirecting to a download site it shows:
Internet Explorer cannot display the webpage

What might be the probable cause?
Actually the page is not redirecting to :
"https://dl-ssl.google.com/tag/s/appguid%3D%7B9a5e649a-ec63-4c7d-99bf-75adb345e7e5%7D%26lang%3Den%26appname%3DGWT%2520Developer%2520Plugin%2520for%2520IE%2520%2528x86%2529%26needsadmin%3Dfalse/gwt/plugins/ie/GwtDevPluginSetup.exe"
Is there any alternate way to install that plugin?
Please help!!

A: I faced the same problem and i think that there is no development mode for IE8. it didn't work when i tried to run it in IE. So i advice you to use Chrome it is the best browser supports GWT dev mode. Why do you need IE anyway ?
read this article about IE http://googlewebtoolkit.blogspot.com/2010/12/support-for-gwt-dev-mode-in-ie-9.html

A: Even I had the same issue in installing the plugin for IE, what i did was just copy and pasted the missing plugin url in address bar and hit the enter button. And installed it, so finally it worked. The issue was, the browser was unable to redirect to the plugins update site, after clicking on download link.
Hope this might fix your problem.


text:
Q: How should I use UUID with JavaDB/Derby and JDBC? I currently use INT as type for primary key in JavaDB (Apache Derby), but since I'm implementing an distributed system I would like to change the type to java.util.UUID. A few questions about this:

*

*What datatype in JavaDB/Derby should I use for UUID? I have seen CHAR(16) FOR BIT DATA been mentioned but I don't know much about it. Is VARCHAR(16) an alternative?

*How should I use it with JDBC? E.g. in an PreparedStatement, how should I set and get an UUID?

*If I later would likte to change database to SQL Server, is there a compatible datatype to java.util.UUID?
Simply, How should I use UUID with JavaDB/Derby and JDBC?

A: If you still want to use the UUID object in your code you can use fromString to create UUID objects from the DB and toString to store them in the DB.

A: UUID is a 128 bit value.  The CHAR(16) FOR BIT DATA type reflects that it is bit data stored in character form for conciseness.  I don't think VARCHAR(16) would work because it doesn't have the bit flag.  The database would have to be able to convert the binary data to character data which deals with encoding and is risky.  More importantly, it wouldn't buy you anything.  Since a UUID is always 128 bits, you don't get the space savings from using VARCHAR over CHAR.  So you might as well use the intended CHAR(16) FOR BIT DATA.
With JDBC, I think you use the get/setBytes() method since it is dealing with small amounts of binary data. (Not positive, would have to try this)
And no idea about the SQL Server part.

A: You could convert the UUID to a string and store it as VARCHAR. Most UUID string formats are similar to this one: 32 digits separated by hyphens: 00000000-0000-0000-0000-000000000000, so then you'd want a VARCHAR(36), or make it something like VARCHAR(64) if you please, since it doesn't hurt to have extra 'space' available in your VARCHAR -- only the actual digits are stored.
Once you've converted it to a string, just call Statement.SetString to include it in your INSERT statement.


text:
Q: Excel - How to automatically convert Text URL to active hyperlinks? I have an Excel file which needs to be sent to my colleagues. However, there is a column "link" which includes the text URL, the URL only can be activated when I double click this cell. How can I automatically activate these text URLs so my colleagues don't need to double click on each cell?

Thanks,
Jennifer.

A: With inactive links in column A, in B2 (or some other column) enter:
=HYPERLINK(A2,A2)

and copy downward.
This costs you an extra column, but it minimizes the need for "special handling".  An alternative approach might be to activate all the cell in the column with a small SendKeys macro.


text:
Q: How to auto submit a JavaScript web form in some website using cusom form data? I would like to see if this is possible. I go to a website and find some signup page. I want to fill it with my data and submit it. The form is not directly written on the web page, but is appended / loaded using some JavaScript. What I want is I want to do this without using my browser, like using some tools / script. Here is an example page.
Is this possible?

A: This has been made by passing data to the server via the URL. If you are interested in passing data in through the server, you should learn node.js. With node.js you can run code based on the URL.
The main idea is that this is somewhat server side (or node.js). Learning node.js will reveal some ways to solve this.


text: Q: name element in sklearn.compose.ColumnTransformer() In sklearn.compose.ColumnTransformer(), we can specify a list of tuples, where every tuple represents a transformer object. Every tuple of a transformer must includes three elements : name, transformer, columns. According to my understanding, name can be any string, but the problem is that I don't understand its usage. So can someone explain its usage with an example please ?


text:
Q: How to substitute a particular word followed by a alphanumeric / numeric in pandas python? How do I substitute a particular word(i.e. ABC) followed by a alphanumeric / numeric as shown below in pandas
Input data
what is ABC s123 doing 77 here?
what is abc  aA574 doing 89 here?
what is ABC-X187 doing here?
what is aBC^984 doing here?
what is Abc647 doing here?

Expected output data
what is ABCS123 doing 77 here?
what is ABCAA574 doing 89 here?
what is ABCX187 doing here?
what is ABC984 doing here?
what is ABC647 doing here?

Note: Any alphanumeric can follow ABC. The numbers shown here are just example and dont hardcode the number in the solution.
EDIT1: Just tried the proposed solution. It doesn't work when the special character is space. So please remove the duplicate tag.
EDIT2: Kindly handle the case of ABC as per the question.

A: You can use:
df['col'] = df['col'].str.replace(r'(?<=ABC)\W+(?=\d\d\d)', '')

or
df['col'] = df['col'].map(lambda x: re.sub(r'(?<=ABC)\W+(?=\d\d\d)', '', x))

A: You can use this code:
import re

regex = r"(.*[A-Z]+).*?(\d+.*)"

test_str = """what is ABC 123 doing here?
what is ABC  574 doing here?
what is ABC-187 doing here?
what is ABC^984 doing here?
what is ABC647 doing here?"""

subst = r"\1\2"

result = re.sub(regex, subst, test_str)
print (result)
# what is ABC123 doing here?
# what is ABC574 doing here?
# what is ABC187 doing here?
# what is ABC984 doing here?
# what is ABC647 doing here?

Details at regex101: https://regex101.com/r/gGK8fJ/2

A: from the documentation of Series.str.replace
s = pd.Series("""what is ABC 123 doing here?
what is ABC  574 doing here?
what is ABC-187 doing here?
what is ABC^984 doing here?
what is ABC647 doing here?""".split("\n"))

pattern = r"ABC.*?(\d+)"
s.str.replace(pattern, r"ABC \1")

0    what is ABC 123 doing here?
1    what is ABC 574 doing here?
2    what is ABC 187 doing here?
3    what is ABC 984 doing here?
4    what is ABC 647 doing here?
dtype: object


text:
Q: Move menu next to logo instead of below or above in WordPress theme (header.php) I want to move the menu next to the logo instead of under it in an WordPress theme.
See the actual page I'm working on here: http://wwconsult.no/client/alive/
I found the code for the menus placement in the header.php, here's the snippet:
<?php
if ( $smof_data['head_menu_style'] == "menu_default" ){

    if ( has_nav_menu('top_navigation', 'GoGetThemes') ) {
        echo '
';
            menu_back();
        echo '
';
    }
      echo'
'.$logo.'

                            '.$parallax_menu.'

';
                    if(!is_page_template('home-index.php')){
                        echo '
'.$parallax_menu.'
';
                    } else{
                        echo '
'.$parallax_menu.'
';
                    }
        echo        '
';

}   else if ( $smof_data['head_menu_style'] == "menu_dropdown" ) {

    echo'
'.$logo.'

                                '.$smof_data["home_menu_name"].'

                        '.$parallax_menu.'

'.$parallax_menu.'

';

    if ( has_nav_menu('top_navigation', 'GoGetThemes') ) {
        echo '
';
            menu_back();
        echo '
';
    }
    // Header Border
    echo'

';
}
?>

I'm no php wizard, but I have tried to make it work without much succsses. Got it above the logo, got blank page, but that about it... Any help would be highly appreciated.

A: replace below line
echo'
'.$logo.'

with
 echo'
'.$logo;
if ( has_nav_menu('top_navigation', 'GoGetThemes') ) {
    echo '
';
        menu_back();
    echo '
';
}
echo '


text:
Q: Detect when all flows produced value I''m having two functions which upload some data to database.
suspend fun addOverallRatingValue(productId: String): Flow<FirebaseEventResponse>
suspend fun markProductAsRatedByUser(productId: String): Flow<FirebaseEventResponse>

Both of them are callbackFlow
override suspend fun markProductAsRatedByUser(productId: String) = callbackFlow {
        try {
            firebaseInstance
                ...
                .addOnSuccessListener {
                    trySend(FirebaseEventResponse.SuccessSetValue)
                }
                .addOnFailureListener {
                    trySend(FirebaseEventResponse.ExceptionOccurred.Event(it))
                }
        } catch (e: Exception) {
            trySend(FirebaseEventResponse.ExceptionOccurred.Event(e))
        }
        awaitClose { this.cancel() }
    }

How can I combine these two flows and react when both of them send any FirebaseEventResponse?

A: There are combine and zip functions you can use to combine flows:
combine(
    flow1,
    flow2,
) { result1, result2 ->
    // ... check results
}.launchIn(viewModelScope)

The difference between them is that combine fires when the most recent value is emitted by each flow, and zip fires when each pair of value is emitted. Here is a good article about Flow operators.
There is also merge function which merges the given flows into a single flow without preserving an order of elements:
merge(flow1, flow2).onEach { result ->
    // ... use result
}.launchIn(viewModelScope)


text:
Q: is there a scaffolding tool for asp mvc 4? is there a tool that I can use to automaticaly create CRUD + ui for a model in asp mvc 4?

A: There's ASP.NET MVC Scaffolding.
Here's a series of blog posts about the package by Steven Sanderson

A: You could try an online tool like CamoteQ Architecture


text:
Q: Columns misaligned in email from shell script I am trying to create a script to alert me when a unix FS exceeds a certain %used.  I have successfully created the script and am able to trigger the alert to my email but I am stuck trying to format the output to be easy to read.  Below is my code:
#!/bin/sh
#****************************************************************************************************************************
#Check all Filesystems and see how much space is being used
#****************************************************************************************************************************
set -x

# Load the .profile for the user
. /home/user/.profile

hostname=`uname -n`
Mail_ID="mail@mail.com"

subject="Check File Systems on $hostname"
dfoutput=/tmp2/user/logs/$hostname/dfoutput.txt
dfcleanoutput=/tmp2/user/logs/$hostname/dfcleanoutput.txt
badfilesizelog=/tmp2/user/logs/$hostname/badfs.txt
limit=70

rm $badfilesizelog

df -g | awk '{if ($1 != "Filesystem") print $1, $4, $7}' > $dfoutput

sed -e 's/%//' -e '/-/d' -e '/.*ora/d' -e '/.*var/d' -e '/.*usr/d' -e '/.*monitor/d' $dfoutput > $dfcleanoutput

cat $dfcleanoutput |
while read var1 var2 var3;
do
if [ $var2 -ge $limit ]
then
printf '%-90s %-50s %50s\n' $var1 $var2 $var3>> $badfilesizelog
fi
done

[ -f $badfilesizelog ] && cat $badfilesizelog | mail -s "$subject" $Mail_ID || echo "Do Nothing"

This is the output that is in the email from this script:
/dev/fs                  70                  /apps
host:/disk_test                75               /test_software
host:/schema_backup              71               /schema_backup

As you can see it is not aligning everything as I would want it to like below:
/dev/fs                  70                  /apps
host:/disk_test          75                  /test_software
host:/schema_backup      71                  /schema_backup

How can I get the formatting to work correctly?  I have tried many different ways but always end up with the same alignment issues.
Thank you

A: I was able to find a working solution using sendmail instead of mail as mail was causing the format problem I was experiencing.  Below is what I used:
[ -f $badfilesizelog ] && awk ' BEGIN {
 print "From: eaimgr@'$hostname'.com"
 print "To: '$Mail_ID'"
 print "MIME-Version: 1.0"
 print "Content-Type: text/html"
 print "Subject: Check File Systems on '$hostname'"
 print "
"
 print "
"
 print "Filesystem	";
 print "%Used	";
 print "Mounted On	";
 print "
"
} {
 print "
"
 print ""$1"	";
 print ""$2"	";
 print ""$3"	";
 print "
"
} END {
 print "
"
} ' $badfilesizelog | sendmail -t


text:
Q: ANTLR4 line comments and text parsing issue I'm writing the parser of c++ header style file and facing the issue with correct line comment handling.
CustomLexer.g4
lexer grammar CustomLexer;

SPACES          : [ \r\n\t]+ -> skip;
COMMENT_START   : '//' -> pushMode(COMMENT_MODE);
PRAGMA          : '#pragma';
SECTION         : '@section';
DEFINE          : '#define';
UNDEF           : '#undef';
IF              : '#if';
ELIF            : '#elif';
ELSE            : '#else';
IFDEF           : '#ifdef';
IFNDEF          : '#ifndef';
ENDIF           : '#endif';
ENABLED         : 'ENABLED';
DISABLED        : 'DISABLED';
EITHER          : 'EITHER';
ANY             : 'ANY';
DEFINED         : 'defined';
BOTH            : 'BOTH';
BOOLEAN_LITERAL :  'true' | 'false';
STRING          : '"' .*? '"';
HEXADECIMAL     : '0x' ([a-fA-F0-9])+;
LITERAL_SUFFIX  : 'L'|'u'|'U'|'Lu'|'LU'|'uL'|'UL'|'f'|'F';
IDENTIFIER      : [a-zA-Z_] [a-zA-Z_0-9]*;
BLOCK_COMMENT   : '/**' .*? '*/';
NUMBER          : ('-')? Int ('.' Digit*)? | '0';
CHAR_SEQUENCE   : [a-zA-Z_] [a-zA-Z_0-9.]*;
ARRAY_SEQUENCE  : '{' .*?  '}';
OPAREN          : '(';
CPAREN          : ')';
OBRACE          : '{';
CBRACE          : '}';
ADD             : '+';
SUBTRACT        : '-';
MULTIPLY        : '*';
DIVIDE          : '/';
MODULUS         : '%';
OR              : '||';
AND             : '&&';
EQUALS          : '==';
NEQUALS         : '!=';
GTEQUALS        : '>=';
LTEQUALS        : '<=';
GT              : '>';
LT              : '<';
EXCL            : '!';
QMARK           : '?';
COLON           : ':';
COMA            : ',';
OTHER           : .;

fragment Int    : [0-9] Digit* | '0';
fragment Digit  : [0-9];

mode COMMENT_MODE;
  COMMENT_MODE_DEFINE     : '#define' -> type(DEFINE), popMode;
  COMMENT_MODE_SECTION    : '@section' -> type(SECTION), popMode;
  COMMENT_MODE_IF         : '#if' -> type(IF), popMode;
  COMMENT_MODE_ENDIF      : '#endif' -> type(ENDIF), popMode;
  COMMENT_MODE_LINE_BREAK : [\r\n]+ -> skip, popMode;

  COMMENT_MODE_PART       : ~[\r\n];

CustomParser.g4:
parser grammar CustomParser;

options { tokenVocab=CustomLexer; }

compilationUnit
 : statement* EOF
 ;

statement
 : comment? pragmaDirective
 | comment? defineDirective
 | comment? undefDirective
 | comment? ifDirective
 | comment? ifdefDirective
 | comment? ifndefDirective
 | sectionLineComment
 | comment
 ;

pragmaDirective
 :   PRAGMA char_sequence
 ;

subDirectives
 : ifDirective+
 | ifdefDirective+
 | ifndefDirective+
 | defineDirective+
 | undefDirective+
 | comment+
 ;

ifdefDirective
 : IFDEF IDENTIFIER subDirectives+ ENDIF
 ;

ifndefDirective
 : IFNDEF IDENTIFIER subDirectives+ ENDIF
 ;

ifDirective
 : ifStatement elseIfStatement* elseStatement? ENDIF
 ;

ifStatement
 : IF expression (subDirectives)*
 ;

elseIfStatement
 : ELIF expression (subDirectives)*
 ;

elseStatement
 : ELSE (subDirectives)*
 ;

defineDirective
 : BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER BOOLEAN_LITERAL info_comment?
 | BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER (char_sequence COMA?)+ info_comment?
 | BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER OPAREN? NUMBER LITERAL_SUFFIX? CPAREN? info_comment?
 | BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER HEXADECIMAL info_comment?
 | BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER STRING info_comment?
 | BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER OBRACE? (ARRAY_SEQUENCE COMA?)+ CBRACE? info_comment?
 | BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER expression info_comment?
 | BLOCK_COMMENT? COMMENT_START? DEFINE IDENTIFIER info_comment?
 ;

undefDirective
 : BLOCK_COMMENT? COMMENT_START? UNDEF IDENTIFIER info_comment?;

sectionLineComment
 : COMMENT_START COMMENT_MODE_PART? SECTION char_sequence
 ;

comment
 : BLOCK_COMMENT
 | line_comment+
 ;

expression
 : simpleExpression
 | customExpression
 | enabledExpression
 | disabledExpression
 | bothExpression
 | eitherExpression
 | anyExpression
 | definedExpression
 | comparisonExpression
 | arithmeticExpression
 ;

arithmeticExpression
 : arithmeticExpression  (MULTIPLY | DIVIDE) arithmeticExpression
 | arithmeticExpression (ADD | SUBTRACT) arithmeticExpression
 | OPAREN arithmeticExpression CPAREN
 | expressionIdentifier
 ;

comparisonExpression
 : comparisonExpression (EQUALS | NEQUALS | GTEQUALS | LTEQUALS | GT | LT) comparisonExpression
 | comparisonExpression (AND | OR) comparisonExpression
 | EXCL? OPAREN comparisonExpression CPAREN
 | eitherExpression
 | enabledExpression
 | bothExpression
 | anyExpression
 | definedExpression
 | disabledExpression
 | customExpression
 | simpleExpression
 | expressionIdentifier
 ;

enabledExpression : EXCL? OPAREN? ENABLED OPAREN IDENTIFIER CPAREN CPAREN?;
disabledExpression : EXCL? OPAREN? DISABLED OPAREN IDENTIFIER CPAREN CPAREN?;
bothExpression : EXCL? OPAREN? BOTH OPAREN identifiers identifiers CPAREN CPAREN?;
eitherExpression : EXCL? OPAREN? EITHER OPAREN identifiers+ CPAREN CPAREN?;
anyExpression : EXCL? OPAREN? ANY OPAREN identifiers+ CPAREN CPAREN?;
definedExpression : EXCL? OPAREN? DEFINED OPAREN IDENTIFIER CPAREN CPAREN?;
customExpression : EXCL? IDENTIFIER OPAREN IDENTIFIER CPAREN;
simpleExpression : EXCL? IDENTIFIER;
expressionIdentifier : IDENTIFIER | NUMBER;

identifiers
 : IDENTIFIER COMA?
 ;

line_comment
 : COMMENT_START COMMENT_MODE_PART*
 ;

info_comment
 : COMMENT_START COMMENT_MODE_PART*
 ;

char_sequence
 : CHAR_SEQUENCE
 | IDENTIFIER
 ;

It is working fine with 95% of the directives and comments I have in my header file but few scenarios still not correctly handled:
1. Line comments
Input:
//1
//#define ID1 //2

This is the list of tokens:
01. compilationUnit
02.  statement:2
03.    comment:2
04.      line_comment
05.        COMMENT_START: "//"
06.        COMMENT_MODE_PART: "1"
07.      line_comment
08.        COMMENT_START: "//"
09.    defineDirective:8
10.      DEFINE: "#define"
11.      IDENTIFIER: "ID1"
12.      info_comment
13.        COMMENT_START: "//"
14.        COMMENT_MODE_PART: "2"
15.<EOF>

I want to achieve that the token on line 07 is a part of the token on line 09 and resolved as COMMENT_START token
2. Define directive with text
Other define rules are working correctly but:
#define USER_DESC_2 "abc " DEF "ABC2 \" M100 (100)
#define USER_GCODE_2 "M140 S" STRINGIFY(PREHEAT_1_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND)

These "define" directives are parsing with an exception
I would appreciate any help with resolving these 2 problems I have at this moment or any recommendations on how my lexer/parser can be optimized.
Thanks in advance!
=================================Update===================================
First test case:
Input:
//1
//#define ID1 //2

Current result:
01. compilationUnit
02.  statement:2
03.    comment:2
04.      line_comment
05.        COMMENT_START: "//"
06.        COMMENT_MODE_PART: "1"
07.      line_comment
08.        COMMENT_START: "//"
09.    defineDirective:8
10.      DEFINE: "#define"
11.      IDENTIFIER: "ID1"
12.      info_comment
13.        COMMENT_START: "//"
14.        COMMENT_MODE_PART: "2"
15.<EOF>

Expected result:
01. compilationUnit
02.  statement:2
03.    comment:2
04.      line_comment
05.        COMMENT_START: "//"
06.        COMMENT_MODE_PART: "1"
07.    defineDirective:8
08.      COMMENT_START: "//"
09.      DEFINE: "#define"
10.      IDENTIFIER: "ID1"
11.      info_comment
12.        COMMENT_START: "//"
13.        COMMENT_MODE_PART: "2"
14.<EOF>

Second test case:
Input:
#define USER_DESC_2 "Preheat for " PREHEAT_1_LABEL

Current result:
01.compilationUnit
02. statement:2
03.  defineDirective:5
04.   DEFINE: "#define"
05.   IDENTIFIER: "USER_DESC_2"
06.   STRING: "\"Preheat for \""
07.  IDENTIFIER: "PREHEAT_1_LABEL"
<EOF>

Expected result:
01.compilationUnit
02. statement:2
03.  defineDirective:5
04.   DEFINE: "#define"
05.   IDENTIFIER: "USER_DESC_2"
06.   STRING: "\"Preheat for \" PREHEAT_1_LABEL"
<EOF>

In the expected result, STRING represents the result text. Here I do not really know if it is better to enhance STRING Lexer token definition or introduce new parsing rule to cover this case

A: Mixing this post, your previous question and Bart's answer, and supposing that a define directive is in the form
optional_// #define IDENTIFIER replacement_value optional_line_comment

and given the input file input.txt
/**
 * BLOCK COMMENT
 */
#pragma once
//#pragma once

/**
 * BLOCK COMMENT
 */
#define CONFIGURATION_H_VERSION 12345

#define IDENTIFIER abcd
#define IDENTIFIER_1 abcd
#define IDENTIFIER_1 abcd.dd

#define IDENTIFIER_2 true // Line
#define IDENTIFIER_20 {ONE, TWO} // Line
#define IDENTIFIER_20_30   { 1, 2, 3, 4 }
#define IDENTIFIER_20_30_A   [ 1, 2, 3, 4 ]
#define DEFAULT_A 10.0

//================================================================
//============================= INFO =============================
//================================================================

/**
 * SEPARATE BLOCK COMMENT
 */

// Line 1
// Line 2
//

//======================= this is a section ======================
// @section test

// Line 3
#define IDENTIFIER_TWO "(ONE, TWO, THREE)" // Line 4
//#define IDENTIFIER_3 Version.h // Line 5

// Line 6
#define IDENTIFIER_THREE

//1
//#define ID1 //2

#define USER_DESC_2 "Preheat for " PREHEAT_1_LABEL

#define USER_DESC_2 "abc " DEF "ABC2 \" M100 (100)
#define USER_GCODE_2 "M140 S" STRINGIFY(PREHEAT_1_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND)

if I have well understood your two questions, the grammar must produce a statement for each directive or comment not followed by a directive. A directive can be preceded by a comment, which becomes part of the statement. A directive can be commented out and followed by an inline line comment (that is, on the same line).
Grammar Header.g4 (without trace) :
grammar Header;

compilationUnit
    @init {System.out.println("Last update 1253");}
    :   ( statement {System.out.println("Statement found : `" + $statement.text + "`");}
        )* EOF
    ;

statement
    :   comment? pragma_directive
    |   comment? define_directive
    |   section
    |   comment
    ;

pragma_directive
     :   PRAGMA char_sequence
     ;

define_directive
    :   define_identifier replacement_comment[$define_identifier.statement_line]
    ;

define_identifier returns [int statement_line]
    :   LINE_COMMENT_DELIMITER? DEFINE {$statement_line = getCurrentToken().getLine();} IDENTIFIER
    ;

replacement_comment [int statement_line]
    :   anything+ line_comment?
    |   {getCurrentToken().getLine() == $statement_line}? line_comment
    |   {getCurrentToken().getLine() != $statement_line}?
    ;

section
    :   LINE_COMMENT_DELIMITER OTHER? SECTION char_sequence
    ;

comment
    :   BLOCK_COMMENT
    |   line_comment
    |   SEPARATOR ( IDENTIFIER | EQUALS )*
    ;

line_comment
    :   LINE_COMMENT_DELIMITER anything*
    ;

anything
    :   IDENTIFIER
    |   CHAR_SEQUENCE
    |   STRING
    |   NUMBER
    |   OTHER
    ;

char_sequence
    :   CHAR_SEQUENCE
    |   IDENTIFIER
    ;

LINE_COMMENT_DELIMITER : '//' ;
PRAGMA        : '#pragma';
SECTION       : '@section';
DEFINE        : '#define';
STRING        : '"' .*? '"';
EQUALS        : '='+ ;
SEPARATOR     : LINE_COMMENT_DELIMITER EQUALS ;
IDENTIFIER    : [a-zA-Z_] [a-zA-Z_0-9]*;
CHAR_SEQUENCE : [a-zA-Z_] [a-zA-Z_0-9.]*;
NUMBER        : [0-9.]+ ;
BLOCK_COMMENT : '/**' .*? '*/';
WS            : [ \t]+ -> channel(HIDDEN) ;
NL            : (   '\r' '\n'?
                  | '\n'
                ) -> channel(HIDDEN) ;
OTHER         : . ;

Execution :
$ export CLASSPATH=".:/usr/local/lib/antlr-4.9-complete.jar"
$ alias a4='java -jar /usr/local/lib/antlr-4.9-complete.jar'
$ alias grun='java org.antlr.v4.gui.TestRig'
$ a4 Header.g4
$ javac Header*.java
$ grun Header compilationUnit -tokens input.txt
[@0,0:23='/**\n * BLOCK COMMENT\n */',<BLOCK_COMMENT>,1:0]
[@1,24:24='\n',<NL>,channel=1,3:3]
[@2,25:31='#pragma',<'#pragma'>,4:0]
[@3,32:32=' ',<WS>,channel=1,4:7]
[@4,33:36='once',<IDENTIFIER>,4:8]
[@5,37:37='\n',<NL>,channel=1,4:12]
...
[@84,315:321='#define',<'#define'>,19:0]
[@85,322:322=' ',<WS>,channel=1,19:7]
[@86,323:340='IDENTIFIER_20_30_A',<IDENTIFIER>,19:8]
[@87,341:343='   ',<WS>,channel=1,19:26]
[@88,344:344='[',<OTHER>,19:29]
[@89,345:345=' ',<WS>,channel=1,19:30]
[@90,346:346='1',<NUMBER>,19:31]
[@91,347:347=',',<OTHER>,19:32]
...
[@139,644:668='//=======================',<SEPARATOR>,34:0]
[@140,669:669=' ',<WS>,channel=1,34:25]
[@141,670:673='this',<IDENTIFIER>,34:26]
...
[@257,1103:1102='<EOF>',<EOF>,51:0]
Last update 1253
Statement found : `/**
 * BLOCK COMMENT
 */
#pragma once`
Statement found : `//#pragma once`
...
Statement found : `#define DEFAULT_A 10.0`
...
Statement found : `// Line 2`
Statement found : `//`
...
Statement found : `//#define IDENTIFIER_3 Version.h // Line 5`
Statement found : `// Line 6
#define IDENTIFIER_THREE`
Statement found : `//1
//#define ID1 //2`
Statement found : `#define USER_DESC_2 "Preheat for " PREHEAT_1_LABEL`
Statement found : `#define USER_DESC_2 "abc " DEF "ABC2 \" M100 (100)`
Statement found : `#define USER_GCODE_2 "M140 S" STRINGIFY(PREHEAT_1_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND)`

Grammar Header_trace.g4 (with trace) :
grammar Header_trace;

compilationUnit
    @init {System.out.println("Last update 1137");}
    :   statement[this.getRuleNames() /* parser rule names */]* EOF
    ;

statement [String[] rule_names]
    locals [String rule_name, int start_line, int end_line]
    @after { System.out.print("The next statement is a " + $rule_name);
             $start_line = $start.getLine();
             $end_line   = $stop.getLine();
             if ($start_line == $end_line)
                 System.out.print(" on line " + $start_line);
             else
                 System.out.print(" on lines " + $start_line + " to " + $end_line);
             System.out.println(" : ");
             System.out.println("`" + $text + "`");
           }
    :   comment? pragma_directive [rule_names] {$rule_name = $pragma_directive.rule_name;}
    |   comment? define_directive [rule_names] {$rule_name = $define_directive.rule_name;}
    |   section [rule_names]                   {$rule_name = $section.rule_name;}
    |   comment_only [rule_names]              {$rule_name = $comment_only.rule_name;}
     // comment_only can be replaced by comment when the trace is removed
    ;

pragma_directive [String[] rule_names] returns [String rule_name]
     :   PRAGMA char_sequence
            { $rule_name = rule_names[$ctx.getRuleIndex()]; }
     ;

define_directive [String[] rule_names] returns [String rule_name]
    locals [String dir_rule_name, int statement_line = 0]
    @init {$dir_rule_name = rule_names[_localctx.getRuleIndex()];}
    :   define_identifier replacement_comment[$dir_rule_name, $define_identifier.statement_line]
            { $rule_name = $replacement_comment.rule_name; }
    ;

define_identifier returns [int statement_line]
    :   LINE_COMMENT_DELIMITER? DEFINE {$statement_line = getCurrentToken().getLine();} IDENTIFIER
    ;

replacement_comment [String dir_rule_name, int statement_line] returns [String rule_name]
    :   any+=anything+ line_comment?
            { $rule_name = $dir_rule_name + " with replacement value";
              System.out.print("          anything matched : " );
              if ($any.size() > 0)
                  for (AnythingContext r : $any)
                      System.out.print(r.getText());
              else
                  System.out.print("(nothing)");

              System.out.println();
            }
    |   {getCurrentToken().getLine() == $statement_line}?
        line_comment
            { $rule_name = $dir_rule_name + " WITHOUT replacement value and with inline line comment"; }
    |   {getCurrentToken().getLine() != $statement_line}?
            { $rule_name = $dir_rule_name + " WITHOUT replacement value"; }
    ;

section [String[] rule_names] returns [String rule_name]
    :   LINE_COMMENT_DELIMITER OTHER? SECTION char_sequence
            { $rule_name = rule_names[$ctx.getRuleIndex()]; }
    ;

comment_only [String[] rule_names] returns [String rule_name]
    :   comment
            { $rule_name = rule_names[$ctx.getRuleIndex()]; }
    ;

comment
    :   BLOCK_COMMENT
    |   line_comment
    |   SEPARATOR ( IDENTIFIER | EQUALS )*
    ;

line_comment
    :   LINE_COMMENT_DELIMITER anything*
    ;

anything
    :   IDENTIFIER
    |   CHAR_SEQUENCE
    |   STRING
    |   NUMBER
    |   OTHER
    ;

char_sequence
    :   CHAR_SEQUENCE
    |   IDENTIFIER
    ;

LINE_COMMENT_DELIMITER : '//' ;
PRAGMA        : '#pragma';
SECTION       : '@section';
DEFINE        : '#define';
STRING        : '"' .*? '"';
EQUALS        : '='+ ;
SEPARATOR     : LINE_COMMENT_DELIMITER EQUALS ;
IDENTIFIER    : [a-zA-Z_] [a-zA-Z_0-9]*;
CHAR_SEQUENCE : [a-zA-Z_] [a-zA-Z_0-9.]*;
NUMBER        : [0-9.]+ ;
BLOCK_COMMENT : '/**' .*? '*/';
WS            : [ \t]+ -> channel(HIDDEN) ;
NL            : (   '\r' '\n'?
                  | '\n'
                ) -> channel(HIDDEN) ;
OTHER         : .;

Execution :
$ a4 Header_trace.g4
$ javac Header*.java
$ grun Header_trace compilationUnit -tokens input.txt
[@0,0:23='/**\n * BLOCK COMMENT\n */',<BLOCK_COMMENT>,1:0]
[@1,24:24='\n',<NL>,channel=1,3:3]
[@2,25:31='#pragma',<'#pragma'>,4:0]
[@3,32:32=' ',<WS>,channel=1,4:7]
[@4,33:36='once',<IDENTIFIER>,4:8]
[@5,37:37='\n',<NL>,channel=1,4:12]
...
[@257,1103:1102='<EOF>',<EOF>,51:0]
Last update 1137
The next statement is a pragma_directive on lines 1 to 4 :
`/**
 * BLOCK COMMENT
 */
#pragma once`
...
          anything matched : 10.0
The next statement is a define_directive with replacement value on line 20 :
`#define DEFAULT_A 10.0`
The next statement is a comment_only on line 22 :
`//================================================================`
...
The next statement is a comment_only on line 31 :
`// Line 2`
The next statement is a comment_only on line 32 :
`//`
...
          anything matched : Version.h
The next statement is a define_directive with replacement value on line 39 :
`//#define IDENTIFIER_3 Version.h // Line 5`
The next statement is a define_directive WITHOUT replacement value on lines 41 to 42 :
`// Line 6
#define IDENTIFIER_THREE`
The next statement is a define_directive WITHOUT replacement value and with inline line comment on lines 44 to 45 :
`//1
//#define ID1 //2`
          anything matched : "Preheat for "PREHEAT_1_LABEL
The next statement is a define_directive with replacement value on line 47 :
`#define USER_DESC_2 "Preheat for " PREHEAT_1_LABEL`
...

It happened that thanks to LINE_COMMENT_DELIMITER?, as you did with COMMENT_START?, at the beginning of the define directive rule, and because there is no special token after //, it was no longer necessary to switch to mode COMMENT_MODE when encountering a line comment delimiter.
There was one difficulty with this first approach :
define_directive
    :   LINE_COMMENT_DELIMITER? DEFINE IDENTIFIER anything+ line_comment?
    |   LINE_COMMENT_DELIMITER? DEFINE {$statement_line = getCurrentToken().getLine();}
        IDENTIFIER same_line_line_comment[$statement_line]
    |   LINE_COMMENT_DELIMITER? DEFINE IDENTIFIER

same_line_line_comment [int statement_line]
    :   {getCurrentToken().getLine() == $statement_line}?
        line_comment

The following lines
// Line 6
#define IDENTIFIER_THREE

//1

were parsed with the second alternative instead of the third :
compare statement line 42 with comment line 44
line 44:0 rule same_line_line_comment failed predicate: {getCurrentToken().getLine() == $statement_line}?
The next statement is a define_directive WITHOUT replacement value and with inline line comment on lines 41 to 42 :
`// Line 6
#define IDENTIFIER_THREE`

Despite the fact that the subrule same_line_line_comment was guarded with a false value, the semantic predicate had no effect. The FailedPredicateException was undesirable and the trace message was wrong. It may have to do with Finding Visible Predicates.
The solution was to split the processing of the #define directive into a fixed part define_identifier rule and a variable part replacement_comment rule with the semantic predicate (which, to be effective in the parsing decision, must be placed at the beginning of the alternative).


text:
Q: configuration for haproxy in ubuntu? I'm getting the following problem when I'm configuring haproxy stats:

Job for haproxy.service failed because the control process exited with
  error code. See "systemctl status haproxy.service" and "journalctl
  -xe" for details.

Below is my configuration file code:
listen  stats   192.168.10.10:1936
        mode            http
        log             global
        maxconn         10
        clitimeout      100s
        srvtimeout      100s
        contimeout      100s
        timeout queue   100s
        stats enable
        stats hide-version
        stats refresh 30s
        stats show-node
        stats auth admin:password
        stats uri  /haproxy?stats

global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

    # Default SSL material locations
    ca-base /etc/ssl/certs
    crt-base /etc/ssl/private

    # Default ciphers to use on SSL-enabled listening sockets.
    # For more information, see ciphers(1SSL). This list is from:
    #  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
    ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS
    ssl-default-bind-options no-sslv3

defaults
    log global
    mode    http
    option  httplog
    option  dontlognull
    timeout connect 5000
    timeout client  50000
    timeout server  50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

frontend haproxy_in
    bind *:80
    default_backend haproxy_http

backend haproxy_http
    balance roundrobin
    mode http
    server ironman 104.211.241.39:80
    server thor 104.211.246.147:80

A: if you run journalctl -xe or view your log file you would see you have severe config problems

'listen' cannot handle unexpected argument '192.168.10.10:1936'.
  parsing [/etc/haproxy/haproxy.cfg:1] : please use the 'bind' keyword
  for listening addresses. Error(s) found in configuration file :
  /etc/haproxy/haproxy.cfg

Place the keyword "bind" infront of your stats ip:port , i.e:
listen  stats
        bind            192.168.10.10:1936