text:
Q: Filling holes in image with OpenCV or Skimage I m trying to fill holes for a chessboard for stereo application. The chessboard is at micro scale thus it is complicated to avoid dust... as you can see :

Thus, the corners detection is impossible. I tried with SciPy's binary_fill_holes or similar approaches but i have a full black image, i dont understand.

A: Here is a function that replaces the color of each pixel with the color that majority of its neighbor pixels have.
import numpy as np
import cv2

def remove_noise(gray, num):
    Y, X = gray.shape
    nearest_neigbours = [[
        np.argmax(
            np.bincount(
                gray[max(i - num, 0):min(i + num, Y), max(j - num, 0):min(j + num, X)].ravel()))
        for j in range(X)] for i in range(Y)]
    result = np.array(nearest_neigbours, dtype=np.uint8)
    cv2.imwrite('result2.jpg', result)
    return result

Demo:
img = cv2.imread('mCOFl.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

remove_noise(gray, 10)

Input image:

Out put:

Note: Since this function replace the color of corner pixels too, you can sue cv2.goodFeaturesToTrack function to find the corners and restrict the denoising for that pixels
corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 30)
corners = np.squeeze(np.int0(corners))

A: You can use morphology: dilate, and then erode with same kernel size.

A: A faster, more accurate way is to use skimage.morphology.remove_small_objects docs
im = imread('a.png',cv2.IMREAD_GRAYSCALE)
im = im ==255
from skimage import morphology
cleaned = morphology.remove_small_objects(im, 200)


text:
Q: Two onClickListeners and interaction between them Lets say I have two onClickListeners, A and B, and some buttons asigned to them. Is there a way for each clicked button that "belongs" to onClickListener A to listen, wait or whatever until next button is clicked and if it's from onClickedListener B to do some code after that, it's not important what, and if it's from onClickListener A to stay put and do nothing but wait next click and also wait like the previous button and so on?

A: Ok so I edited my answer to kind of do what the other question asked. Let me know if it makes sense. I won't do the work for you, so this is a simple example that kind of shows you what the logic is.
//This is how you set the TAG so you have it. But I know you use getTag, so I am not sure
//what you are using it for.
a1 = (Button) findViewById(R.id.bA1);
a2 = (Button) findViewById(R.id.bA2);
b1 = (Button) findViewById(R.id.bB1);
b2 = (Button) findViewById(R.id.bB2);
a1.setTag("A");
a2.setTag("A");
b1.setTag("B");
b2.setTag("B");

View.OnClickListener listener = new View.onClickListener() {
    public void onClick(View view) {
        String tag = (String)view.getTag();
        if(tag.equals("A")
            //example on one B button with assumed TAG of "B"
            someButton.setOnClickListener(listener);
            //deregister all your A Views, but again, I'll do one as an example
            //in this case I'll quickly just deregister the A button or view just clicked
            view.setOnClickListener(null);
        else
            if(tag.equals("B")) {
                /*I guess do your thing here but deregister all the B views again
                and register all the A views again*/
                someButton.setOnClickListener(null);
                otherAButton.setOnClickListener(listener);
            }
    }
});

So I make some assumptions to shorten the code up. For example. Set all your A Views with the "A" tag using the setTag method, vice versa with the B Views. Also I assume you want the A views to start off listening to clicks, so when the Activity or Fragment is first launched, thats where you set listener to the A views via setOnClickListener.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is strace a suitable tool for finding out where a program wrote to the filesystem? I'd like to determine where a certain app (as an example, surf) writes to the filesystem in order to make sure it leaves no traces. Without a dedicated sandboxing system this probably isn't easy, but I'm wondering if there is a better way than simply using strace.
For example here is a simple script called run:
#!/bin/bash

mkdir history
echo foo bar > history/hist.db
echo hello > test

I run strace like this:
strace ./run 2>&1 | sed -n '/^open.*WRONLY/p' | sed 's/.*"\(.*\)"[^"]*$/\1/'

to see all the files (but not directories) that were written (I don't think this will capture files that were created, but not written to, like those created by touch). Output:
history/hist.db
test

Is there a better way to do this, since this gets unwieldy for anything besides trivial applications, or are there options I can pass to strace (or better regexes maybe?) that make this a bit more robust? Do I run the risk of missing files that are written to the filesystem?

A: You can also use lsof to "watch" a process as it writes files out to the disk. This is more of a polling solution so you'll possibly miss some files if they're small and quickly written to the disk, but if the application that's writing files out to disk is a server/service you can use lsof to watch these types of processes fairly easily.
$ lsof -p PID

Example
$ lsof -p `pidof gnome-terminal` | head -5
COMMAND    PID USER   FD   TYPE             DEVICE SIZE/OFF      NODE NAME
gnome-ter 7423 saml  cwd    DIR              253,2    32768  10354689 /home/saml
gnome-ter 7423 saml  rtd    DIR              253,0     4096         2 /
gnome-ter 7423 saml  txt    REG              253,0   338632   1220790 /usr/bin/gnome-terminal
gnome-ter 7423 saml  mem    REG              253,0   614032   1192949 /usr/lib64/libfreetype.so.6.6.0


text:
Q: NetLogo: "Code can't be run by a patch" Running Program developed in v 4.0.3 in v5.1.0 I am trying to run a NetLogo program developed in version 4.0.3 in NetLogo Version 5.1.0. The program itself runs fine in the older version of NetLogo but when I try to run it in Version 5.1.0, I receive the following error message:
" this code can't be run by a patch, only the observer
error while patch 19 32 running TICK
  called by procedure GO
  called by Button 'go'"
I tried making some of the obvious adjustments offered in the transition guide but was unable to debug the program. Any thoughts or suggestions would be greatly appreciated.  Code for the whole program is below:
globals [z diver clrrand simp vviolet oorange bbrown yyellow bblue llime total sumdiver matrix-list yellowtrans p
redtrans browntrans violettrans bluetrans orangetrans limetrans]

to setup
  ;; (for this model to work with NetLogo's new plotting features,
  ;; __clear-all-and-reset-ticks should be replaced with clear-all at
  ;; the beginning of your setup procedure and reset-ticks at the end
  ;; of the procedure.)
  __clear-all-and-reset-ticks
  setup-patches
  set sumdiver 0

  set redtrans       (list 0.0  0.9  0.1  0.0  0.0  0.0  0.0)
  set yellowtrans    (list 0.0  0.8  0.1  0.1  0.0  0.0  0.0)
  set browntrans     (list 0.0  0.0  0.8  0.1  0.1  0.0  0.0)
  set violettrans    (list 0.0  0.0  0.0  0.8  0.1  0.1  0.0)
  set bluetrans      (list 0.0  0.0  0.0  0.0  0.8  0.1  0.1)
  set orangetrans    (list 0.0  0.0  0.0  0.0  0.0  0.8  0.2)
  set limetrans      (list 0.0  0.0  0.0  0.0  0.0  0.0  1.0)

end

to setup-patches
  ask patches [
  set z random 100
  if z <= 100 [ set pcolor yellow ]
        ]
end

to go
  ignite
  fire_spread
  succession
  do_plots
  tick
end

to ignite
  ask patches [if pcolor != black
      [if random-float 1 < start
          [set pcolor red]
        ]
      ]
end

to fire_spread

   while [any? patches with [pcolor = red]]  [ask patches [
    if pcolor = red   [set pcolor 14
                      ask neighbors4 [

      if (random-float 1) < p_fire_spread and pcolor != 14 and pcolor != black
        [ set pcolor red]
        ]
      ]
    ]
  ]

end

to succession

  ask patches [

  if pcolor = 14 [
       set clrrand random-float 1
       set p 0
       (foreach redtrans [ 14 yellow brown violet blue orange lime]  [

           if clrrand > p and clrrand <= (p + ?1) [set pcolor ?2  stop]
           set p (p + ?1)
                 ])
        stop
      ]

   if pcolor = yellow [
       set clrrand random-float 1
       set p 0
       (foreach yellowtrans [ 14 yellow brown violet blue orange lime]  [

           if clrrand > p and clrrand <= (p + ?1) [set pcolor ?2  stop]
           set p (p + ?1)
                 ])
        stop

      ]

   if pcolor = brown [
       set clrrand random-float 1
       set p 0
       (foreach browntrans [ 14 yellow brown violet blue orange lime]  [

           if clrrand > p and clrrand <= (p + ?1) [set pcolor ?2  stop]
           set p (p + ?1)
                 ])
        stop
      ]

    if pcolor = violet [
       set clrrand random-float 1
       set p 0
       (foreach violettrans [ 14 yellow brown violet blue orange lime]  [

           if clrrand > p and clrrand <= (p + ?1) [set pcolor ?2  stop]
           set p (p + ?1)
                 ])
        stop

      ]

    if pcolor = blue [
       set clrrand random-float 1
       set p 0
       (foreach bluetrans [ 14 yellow brown violet blue orange lime]  [

           if clrrand > p and clrrand <= (p + ?1) [set pcolor ?2  stop]
           set p (p + ?1)
                 ])
        stop
      ]

     if pcolor = orange [
       set clrrand random-float 1
       set p 0
       (foreach orangetrans [ 14 yellow brown violet blue orange lime]  [

           if clrrand > p and clrrand <= (p + ?1) [set pcolor ?2  stop]
           set p (p + ?1)
                 ])
        stop
      ]

     if pcolor = lime [
       set clrrand random-float 1
       set p 0
       (foreach limetrans [ 14 yellow brown violet blue orange lime]  [

           if clrrand > p and clrrand <= (p + ?1) [set pcolor ?2  stop]
           set p (p + ?1)
                 ])
        stop
      ]

    ]

end

;;  yellow is 45, brown is 35,  violet is 115, sky is 95, green is 55,lime is 65,

to do_plots

set oorange count patches with [pcolor = orange]
set bbrown count patches with [pcolor = brown]
set vviolet count patches with [pcolor = violet]
set llime count patches with [pcolor = lime]
set yyellow count patches with [pcolor = yellow]
set bblue count patches with [pcolor = blue]
set-current-plot "abundances"
set-current-plot-pen "orange"
plot oorange
set-current-plot-pen "brown"
plot bbrown
set-current-plot-pen "violet"
plot vviolet
set-current-plot-pen "lime"
plot llime
set-current-plot-pen "yellow"
plot yyellow
set-current-plot-pen "blue"
plot bblue

 set total bbrown + oorange + vviolet + llime + yyellow + bblue
   set diver (1 / ((bbrown / total) ^ 2 + (oorange / total) ^ 2 + (vviolet / total) ^ 2 + (llime / total) ^ 2 + (yyellow / total) ^ 2 + (bblue / total) ^ 2))
   set-current-plot "Simpson's diversity index"
   plot diver
   if ticks > 50 and ticks < 201 [set sumdiver sumdiver + diver]

   if ticks = 201 [
       set sumdiver sumdiver / 150
       output-type "mean = "
       output-type precision sumdiver 2
      ]
end

Thanks!

A: This is a previously unreported bug in NetLogo. I'm glad you discovered it. I have minimized it and reported it here: https://github.com/NetLogo/NetLogo/issues/683
In order to work around it, you need to find a way to rewrite the code so it avoids using stop inside foreach.


text:
Q: Unit testing setup in Qt Creator I am using Qt Creator with qmake to create my project and my test project (QTest-tests). I have the test project running on its own now, but I have a hard time to understand how to test classes from my normal project. I can include the .h files from my project in the test cases, but that's of course not enough.
It throws my linker errors since it does have not the code or a library to look up the code for the class. Is there a simple way to tell qmake to look up all source files in a specific folder to load them? Or what is the correct way to set up such a test project without having to add each source file also to the test project or compiling your application into an library to include?

A:
Is there a simple way to tell QMake to look up all source files in a specific folder to load them?

qmake supports wildcards so you can have something like
SOURCES += *.cpp
HEADERS += *.h

in your project file.
Also make sure to adjust MOC_DIR and RCC_DIR to point somewhere else than the source folder. You don't want to include generated source files in your SOURCES.

Or what is the correct way to set up such an test project without having to add each source file also to the test project or compiling your app into an lib to include

I prefer to separate my automated tests into two classes:

*

*Unit tests testing single components (usually living in a source file). I mock away dependencies to other parts of the system. Each unit test is a Qt project of its own and only includes the source files being tested + test code + mock code.

*Integration tests testing components as whole without mock code. Usually it's the application engine part built as a library and then linked to the test project.


text:
Q: Как перебрать всех детей игрового объекта Unity
Изучаю Unity неделю
Первоначально стоит задача: каждые 2 секунды спавнить одну монетку на каждом споте поочередно.
То есть 2 сек - спавним в первой точке. 4 сек - во второй точке, 6 сек - в третьей точке.
Я хочу в массив _points поместить всех детей игрового объекта Path (см. скриншот), чтобы потом через обращение по индексу вызывать метод CreateEnemy. Но происходит конфликт, у массива тип SpawnEnemy[], а у _path.transform.GetChild(i)тип данных Transform
Собственно вопрос, как я могу поместить всех детей в этот массив?
скрипт ChoosePoint (будет висеть на объекте Path):
    private SpawnEnemy[] _points;
    private GameObject _path;

    private void Start()
    {
        _points = new SpawnEnemy[_path.transform.childCount];
        for (int i = 0; i < _path.transform.childCount; i++)
        {
           _points[i] = _path.transform.GetChild(i); //  <---- Смотреть сюда
        }
    }

скрипт SpawnEnemy (будет висеть на каждом Point):
[SerializeField] private GameObject _template; // здесь будет монетка
private Vector3 _pointPosition;

private void Start()
{
    _pointPosition = GetComponent<Transform>().position;
}

public void CreateEnemy()
{
    GameObject newObject = Instantiate(_template, _pointPosition, Quaternion.identity);
}

A: private SpawnEnemy[] _points;
private GameObject _path;

private void Start()
{
    _points = _path.GetComponentsInChildren<SpawnEnemy>();
}


text:
Q: Quicksort recursiveness I am trying to write a quicksort function in python, yet I am having trouble regarding the implementation of it. I understand the logic, however I've never written a recursive function before.
I've looked up YouTube tutorials, however the logic they use is often different to my logic.
As their are several ways to do a quicksort I will post my logic.
My logic is as follows:

*

*A pivot is a randomly chosen item in the list

*The pivot is moved to the right most position in the list.

*Each item in the List is then compared to the pivot to see if it is bigger than the pivot.

*The first item which is bigger than the pivot is designated as the FirstBigNumber.

*The list is then iterated through again. The first item which is smaller than the pivot swaps position in the list with the FirstBigNumber, Swapped=True

*A new FirstBigNumber is then found

*Repeat steps 4,5,6 until pivot reached.

*Swap pivot with FirstBigNumber.

*The list should be sorted.

My code:
import random
List=[3,5,1,7,2,8]
pivot_pos=0
def getpivot(List):
    #Get pivot position
    pivot_pos=random.randint(0,len(List)-1)
    return pivot_pos

def quicksort(List,pivot_pos):
    #Calling Get Pivot function
    getpivot(List)
    print(List)
    #Obtain pivot
    pivot=List[pivot_pos]
    print("Pivot is ",pivot)
    #Swap pivot to right of list
    List[len(List)-1],List[pivot_pos]=List[pivot_pos],List[len(List)-1]
    Swapped=True
    print(List)
    #Loop through List
    for j in range(0,len(List)-1):
        print("Checking if",List[j],"is bigger than",pivot)
        #Marks first num larger than
        if List[j]>pivot and Swapped==True:
            #FirstBigNum stores the index of the First number bigger than pivot
            FirstBigNum=List[j]
            IndexOfBigNum=j
            print("BigNum is",FirstBigNum)
            #This new Big number has not been swapped
            Swapped=False
        for i in range(0,len(List)-1):
            if List[i]<pivot:
                    #Swap the index of smaller num with first big num
                    print("Swapped",List[i]," with ",List[IndexOfBigNum])
                    List[IndexOfBigNum],List[i]=List[i],List[IndexOfBigNum]
                    print(List)
                    Swapped=True
            elif List[i]<pivot:
                print("Pivot is bigger than",List[i])
                #If Value greater than pivot
                pass
            elif i == (len(List)-1):
                #We have reached the end of the List
                #So we need to swap the pivot with the FirstBigNum
                List[FirstBigNum],List[i]==List[i],List[FirstBigNum]
                print("Here")
                print(List)
            else:
                #Is equal to pivot
                pass

getpivot(List)
quicksort(List,pivot_pos)

The output I receive is:
[5, 8, 7, 2, 1, 3]

The output I should get is:
[1, 2, 3, 5, 7, 8]

A: Here is a standard implementation of Quicksort using recursion with the Lomuto partition. I included a main driver with a random list so you can test it:
import random

def quick_sort(a, l=0, r=None):
    # Recusrion requires a Base Case
    if r is None :
        r = len(a) - 1
    if l >= r :
        return 0
    # If the Base Case is not encountered then proceed to partion
    s = lomuto_partition(a, l, r)
    # call quicksort recursively
    quick_sort(a, l, s-1)
    quick_sort(a, s+1, r)
    return a

def lomuto_partition(a, l, r):
    p = a[l]
    s = l
    for i in range(l+1, r+1) :
        if a[i] < p :
            s += 1
            a[s], a[i] = a[i], a[s]
    a[l], a[s] = a[s], a[l]
    return s

def random_seq(n=10, lo=0, hi=100):
    seq = []
    for i in range(n):
        seq.append(random.randint(lo, hi))
    return seq

if __name__ == '__main__' :
    n = 16
    print('n:', n)

    a = random_seq(n)
    print("Unsorted Random List: ", a)

I hope this helps


text:
Q: Node.js hosting platform Heroku-like I want to create something similar to Heroku (first I was thinking in EngineYard-like but I prefer Heroku) for node.js (I know they already support node.). However, It's for a personal project so it doesn't need to be anything overcomplicated or super expensive. I believe I can learn a lot creating a product like this.
Before I start, I have several doubts:

*

*Heroku uses a reverse proxy to receive the requests. However, reverse proxy doesn't work fine with websockets. How can this be fixed?

*1 instance supports several dynos. How can an instance be divided by RAM, processing, etc?

*I guess if I have an answer to the last questions I'll be able to create a route mesh. However, what can be the tricks here?
Regards.
Donalds

A: So you want to be a node Paas?
Nodejitsu opensourced their hosting solution: haibu (Japanese for Hive). It's well documented and you'll also get real time support if you hope onto #nodejitsu on efnet irc network.
As a user of their service, I can vouch for the simplicity of the solution. You use their client jitsu to provision, configure and deploy the applications. Applications are watched over by their tweaked version of forever.

A: Go for the simplest possible implementation.

*

*Use HAProxy, Apache Traffic Server or
mongrel2 as your reverse proxy.  They
all support the HTTP 1.1 protocol and
should work with websockets.

*Don't worry about limiting resources.

*Also don't worry about a routing mesh.
Just update and reload the
config on your reverse proxy any time
you're spinning up a backend process.

Good luck.


text:
Q: How automated is too automated when it comes to deployment? I have ci, so our staging environment builds itself.
Should I have a script that not only builds production but does all the branching for it as well?
When you have one code base on two different urls with skinning, should they be required to build at once?

A: The only way to be too automated is if you are spending more time fighting with building or fixing automation scripts than you would just doing the job manually.  As long as your automation scripts take less time and produce fewer errors than doing the job manually, then automation is great.
Scripts to build and branch for production are a great idea!

A: In my opinion anything the computer is capable of doing automatically it should do, because it can do it faster, easier and without thought from you. Within reason of course, but stuff like that can be very trivial to automate, so I've always been a proponent of automating that whole process.
and plus it can be fun too!

A: I like to separate the build and deploy steps into two separate steps. The output of the build step should be a package that is placed in a repository or staging area. This package should be independent of the target environments.
The deploy step is responsible for configuring the target environment and installing the package.
The reasons I prefer this approach are:

*

*I have one package that can run in my development, test and production environments. That should cut down the arguments between QA and development.

*There may be different elements that need to be configured during deployment. Application server settings, database schemas, data loads, etc. that might not be as easy to do from the automated build script.

A: In my opinion it's only too automated if no one in your production support group can deploy an application manually in a pinch. Automated deployments really cut down on simple but common errors such as configuration mistakes. However, a manual deployment must always be an option.


text:
Q: Is this induced action transitive? Let $G$ be a group of order $n$ and let $k$ be a smallest integer such that
we have a injection from $G$ to $S_k$. Denote $\bar G$  as a image of $G$.
Is the action of $\bar G$ on $\{1,2,...,k\}$  transitive ?

A: Not necessarily.  For example, if $G=\mathbb{Z}/6$, then the smallest symmetric group containing a copy of $G$ is $S_5$.  But the elements of order $6$ of $S_5$ are products of two disjoint cycles, one of length $2$ and one of length $3$.  The group generated by such an element is never transitive (it admits two orbits).

A: Not necessarily, when $G=C_6$, $k=5$ with $\overline{G} = \langle (1,2)(3,4,5) \rangle$.
More generally, if $G$ and $H$ are groups with $G \le S_k$ and $H \le S_l$, then $G \times H \le S_k \times S_l$ and that will nearly always give you the smallest embedding for $G \times H$.

A: To give a smaller example, let $G = \mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/2\mathbb{Z}$.  Then, in order for there to be an injection $\iota: G \to S_k$, we require that $S_k$ have at least $3$ commutinge elements of order $2$.  The least such $k$ is $k=4$.  But then, we can choose $\iota$ so that $\overline{G} = \{(1), (1\;2), (3\;4), (1\;2)(3\;4)\}$.  Then, the orbit of $1$ under the action of $\overline{G}$ does not include $3$ or $4$, so $\overline{G}$ does not act transitively.

In fact, the only finite abelian groups for which $\overline{G}$ acts transitively on $\{1,2,\cdots k\}$ are $G \cong \mathbb{Z}/p^r\mathbb{Z}$ (EDIT: and, as Derek Holt points out in the comments, $\mathbb{Z}/2\mathbb{Z} \times \mathbb{Z}/2\mathbb{Z}$), where $p$ is a prime.  To see why, we first observe that the minimal $k$ such that $\iota: \mathbb{Z}/p^r\mathbb{Z} \to S_k$ is injective is $k = p^r$ (since for smaller $k$, $S_k$ fails to have an element of order $k$), and that $\overline{G}$ acts on the set $\{1,2,\cdots, k\}$ by cyclically permuting its elements.
On the other hand, if $G$ is not isomorphic to a group of the form $\mathbb{Z}/p^r\mathbb{Z}$, then we can write $G$ as
$$G \cong \prod_{i=1}^t \mathbb{Z}/p_i^{n_i}\mathbb{Z}$$
where the $p_i$ are (nont necessarily distinct) primes.  Such a $G$ can be realized as a subgroup $\overline{G}$ of $S_k$ for $k = \sum_i p_i^{n_i}$ defining $\iota$ to send the generator $g_i$ of each of the component subgroups $\mathbb{Z}/p_i^{n_i}\mathbb{Z}$ to a disjoint $p_i^{n_i}$ cycle.  In fact, this is the minimum such $k$, since in order that $\iota(g_i)\iota(g_j) = \iota(g_j)\iota(g_i)$ we require that $\iota(g_i)$ and $\iota(g_j)$ are disjoint.  But then, the orbit of any element contained in the cycle of $\iota(g_i)$ will be the elements contained in $\iota(g_i)$, so for $t > 1$ the set $\{1,2,\cdots, k\}$ has multiple orbits under the action of $\overline{G}$.


text:
Q: RowFilter in HBase I have 20 rows in an HBase table and the rowkey is in long format starting from 1 to 20. I want to query the records from this where the rowkey starts with 1. I tried with PrefixFilter and BinaryPrefixComparator but it is working fine only if the rowkey is in string fromat. if it is in long the query returns all the records. How can I achieve this?
Filter expression
Scan scan=new Scan();
Filter rowFilter=new RowFilter(CompareOp.EQUAL, new BinaryPrefixComparator(Bytes.toBytes("1")));
//Filter rowFilter=new RowFilter(CompareOp.NOT_EQUAL, new BinaryPrefixComparator(Bytes.toBytes("1")));
scan.setFilter(rowFilter);
ResultScanner resultscanner=htable.getScanner(scan);

A: If the row keys are long, you have to refer them as long in your query rather than String. I.e: instead of Bytes.toBytes("1") use Bytes.toBytes(1L).
You can set the range to be scanned:
scan.setStartRow(Bytes.toBytes(1L));
scan.setStopRow(Bytes.toBytes(21L));  //since stopRow is exclusive


text:
Q: GC overhead limit exceeded with large RDD[MatrixEntry] in Apache Spark I have a csv file stored a data of user-item of dimension 6,365x214 , and i am finding user-user similarity by using columnSimilarities() of org.apache.spark.mllib.linalg.distributed.CoordinateMatrix.
My code looks like this:
import org.apache.spark.mllib.linalg.{Vector, Vectors}
import org.apache.spark.mllib.linalg.distributed.{RowMatrix,
MatrixEntry, CoordinateMatrix}
import org.apache.spark.rdd.RDD

def rddToCoordinateMatrix(input_rdd: RDD[String]) : CoordinateMatrix = {

    // Convert RDD[String] to RDD[Tuple3]
    val coo_matrix_input: RDD[Tuple3[Long,Long,Double]] = input_rdd.map(
        line => line.split(',').toList
    ).map{
            e => (e(0).toLong, e(1).toLong, e(2).toDouble)
    }

    // Convert RDD[Tuple3] to RDD[MatrixEntry]
    val coo_matrix_matrixEntry: RDD[MatrixEntry] = coo_matrix_input.map(e => MatrixEntry(e._1, e._2, e._3))

    // Convert RDD[MatrixEntry] to CoordinateMatrix
    val coo_matrix: CoordinateMatrix  = new CoordinateMatrix(coo_matrix_matrixEntry)

    return coo_matrix
}

// Read CSV File to RDD[String]
val input_rdd: RDD[String] = sc.textFile("user_item.csv")

// Read RDD[String] to CoordinateMatrix
val coo_matrix = rddToCoordinateMatrix(input_rdd)

// Transpose CoordinateMatrix
val coo_matrix_trans = coo_matrix.transpose()

// Convert CoordinateMatrix to RowMatrix
val mat: RowMatrix = coo_matrix_trans.toRowMatrix()

// Compute similar columns perfectly, with brute force
// Return CoordinateMatrix
val simsPerfect: CoordinateMatrix = mat.columnSimilarities()

// CoordinateMatrix to RDD[MatrixEntry]
val simsPerfect_entries = simsPerfect.entries

simsPerfect_entries.count()

// Write results to file
val results_rdd = simsPerfect_entries.map(line => line.i+","+line.j+","+line.value)

results_rdd.saveAsTextFile("similarity-output")

// Close the REPL terminal
System.exit(0)

and, when i run this script on spark-shell
i got following error, after running line of code simsPerfect_entries.count() :
java.lang.OutOfMemoryError: GC overhead limit exceeded

Updated:
I tried many solutions already given by others ,but i got no success.
1  By increasing amount of memory to use per executor process  spark.executor.memory=1g
2  By decreasing the number of cores to use for the driver process
spark.driver.cores=1
Suggest me some way to resolve this issue.

A: All Spark transformations are lazy until you actually materialize it. When you define RDD-to-RDD data manipulations, Spark just chains operations together, not performing actual computation. So when you call simsPerfect_entries.count(), the chain of operations is executed and you got your number.
Error GC overhead limit exceeded means that JVM garbage collector activity was so high that execution of your code was stopped. GC activity can be so high due to these reasons:

*

*You produce too many small objects and immediately discarding them. Looks like that you're not.

*Your data does not fit into your JVM heap. Like if you try to load 2GB text file into RAM, but have only 1GB of JVM heap. Looks like that it's your case.

To fix this issue try to increase the amount of JVM heap on:

*

*your worker nodes if you have a distributed Spark setup.

*your spark-shell app.


text: Q: Что значит Link DLL и With Runtime Package? Для нормальной компиляции требуют снять галочки у этих параметров, но что они значат никто не знает. Причем если комплировать приложение под х64, то появляется ошибка "Out of Memory", "Exited with code 2". Почему?


text:
Q: How can I change the colors of the icon and underline of the SearchBar using AppThemColor? Currently, I'm using these AppThemeColors.
<AppThemeColor x:Key="PrimaryColor"
               Light="Teal"
               Dark="Indigo"/>

<AppThemeColor x:Key="SecondaryColor"
               Light="White"
               Dark="Black"/>

How can I change the color of the SearchBar icon and underline using these AppThemeColors?

A: There is an issue on iOS 13 onwards in the search bar for iOS. According to the issue filed in Xamarin's GitHub, you can use a PlatformEffect to implement that:
public class SearchBarBackgroundEffect : PlatformEffect
{
    public SearchBarBackgroundEffect()
    {
    }

    private UIKit.UISearchBar NativeSearchBar => (UIKit.UISearchBar)Control;
    private SearchBar XamarinSearchBar => (SearchBar)Element;

    protected override void OnAttached()
    {
        if (UIKit.UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
            NativeSearchBar.SearchTextField.BackgroundColor = XamarinSearchBar.BackgroundColor.ToUIColor();
    }
    protected override void OnDetached()
    {

    }
}


text:
Q: How do I achieve this layout without using Javascript? I want a basic full width layout with a 250px sidebar on the right. Here's roughly what I want:
<-------Content-------><--250px sidebar-->
<---------------100% width--------------->

Is this possible without Javascript or tables?

A:

  ..... content ......

 ..... sidebar .....

... other content

This is the CSS for the class="clear":
div.clear {
    clear:both;
}

You can set the first div width when you see how much space you have.
Is this helpful?

A: Yes, of course:
see http://jsfiddle.net/whTwg/4/
HTML:

Sidebar

Main

CSS:
#wrapper{
    overflow:hidden;
}
#main-wrapper{
    overflow:hidden;
}
#sidebar-wrapper{
    float:right;
    width:250px;
    max-width:50%;/* You should set a max-width */
}
/*Here you can add borders, paddings and margins */
#main{
    background:#aaf;
    border:10px solid blue;
}
#sidebar{
    background:#faa;
    border:10px solid red;
}

Note: instead of #wrapper{overflow:hidden} (or something different than visible), you could add

 after main-wrapper.
Edit:
You are right, I forgot to add #main-wrapper{overflow:hidden;}. I have fixed the link and the code.


text:
Q: I develop now login-register system, but got one error and don't know how to fix it public class RegisterPage extends AppCompatActivity {

    SQLiteOpenHelper openHelper;
    SQLiteDatabase db;
    Button _btnreg;
    EditText  _txtlname, _txtpass, _txtemail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_page);

        openHelper = new DatabaseHelper(this);
        _txtlname = (EditText)findViewById(R.id.username);
        _txtpass = (EditText)findViewById(R.id.password);
        _txtemail = (EditText)findViewById(R.id.email);
        _btnreg=(Button)findViewById(R.id.register);

    }

    _btnreg.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            db=openHelper.getWritableDatabase();
            String lname=_txtlname.getText().toString();

            String pass=_txtpass.getText().toString();
            String email=_txtemail.getText().toString();

            insertdata(lname,pass,email);
            Toast.makeText(getApplicationContext(), "register successfully",Toast.LENGTH_LONG).show();

        }
    }
    public void insertdata(String lname, String pass, String email){
        ContentValues contentValues = new ContentValues();
        contentValues.put(DatabaseHelper.COL_2, lname);
        contentValues.put(DatabaseHelper.COL_4, pass);
        contentValues.put(DatabaseHelper.COL_5, email);
        long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
    }
}

This is code line that is with error. setOnClickListener is in red color and View v too, what is wrong there?

A: depending on your updated question
you cant add listener to the button outside a method your listener should be inside a method so your code should be like this
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register_page);

    openHelper = new DatabaseHelper(this);
    _txtlname = (EditText)findViewById(R.id.username);
    _txtpass = (EditText)findViewById(R.id.password);
    _txtemail = (EditText)findViewById(R.id.email);
    _btnreg=(Button)findViewById(R.id.register);

_btnreg.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v){
        db=openHelper.getWritableDatabase();
        String lname=_txtlname.getText().toString();

        String pass=_txtpass.getText().toString();
        String email=_txtemail.getText().toString();

        insertdata(lname,pass,email);
        Toast.makeText(getApplicationContext(), "register successfully",Toast.LENGTH_LONG).show();

    }
}

}


text:
Q: F# - keeping track of state I'm building a cache system in F#.  One of the things I want to do is keep track of the total cache hits and cache misses for the duration of the programs runtime.  So, for instance I may have a function like this:
member this.Exists key =
            match HttpRuntime.Cache.Get(key) with
            | null -> false
            | result -> true

Where in the true null case I want to also increment a miss counter, and in the false case I want to also increment a hit counter.  Now I can use a mutable variable and do this no problem, but I'm wondering how one would go about this with a pure functional approach, or more idiomatic F# approach, with the end goal of being able to display the current count of cache hits and misses to user as the program runs.

A: I would also not worry too much about performance counting being pure. It is a side-effect by definition and so it makes sense to keep some mutable state for it.
For example, you could add static (or not static) member to your class and just mutate it:
type Cache() =
  static let mutable missCounter = 0
  static let mutable hitCounter = 0
  member this.Exists key =
    match HttpRuntime.Cache.Get(key) with
    | null -> missCounter <- missCounter + 1; false
    | result -> hitCounter <- hitCounter + 1; true


text:
Q: Loading resultset using cursors - DB2 stored procedure I have created a stored procedure in Db2 which is something like
Declare c1 CURSOR WITH RETURN FOR
              select * from table,...... -- joins and filters;
Declare c2 CURSOR WITH RETURN FOR
              select * from table,...... -- joins and filters ;
Declare c3 CURSOR WITH RETURN FOR
              select * from table,...... -- joins and filters ;

In the end of the procedure, I open the cursor based on the condition. Something like this:
IF (input_value="employees") THEN
     OPEN c1;
ELSEIF (input_value="management") THEN
     OPEN c2;
ELSEIF (input_value="admin") THEN
     OPEN c3;

My concern is, when I execute this procedure, would it load all the three result sets in the memory and return the correct one based on condition, or would it just load one based on the input?

A: Firstly, results sets in general are not loaded into memory in their entirety. Db2 will materialize portions of a result set as you FETCH from its open cursor and send them to the client in blocks.
Secondly, until you OPEN a cursor no resources whatsoever are allocated, apart from those occupied by the cursor variable in your procedure code.
So, to answer your question, only one cursor will be opened in your code, and only rows from that result set will ever occupy any memory.
See also this related answer.


text:
Q: How can I use AzD/Azure Developer CLI environment values in my script? AzD shows me values like these after my deployment:
$ azd env get-values
...
AZURE_CONTAINER_REGISTRY_ENDPOINT="contreg.azurecr.io"
AZURE_CONTAINER_REGISTRY_NAME="contreg"
SERVICEBUS_ENDPOINT="https://sb.servicebus.windows.net:443/"
SERVICE_TESTDATA_IMAGE_NAME="contreg.azurecr.io/test-data/test-data:azdev-deploy-1665835078"
TESTDATA_URI="https://test-data.nicedune-eccf12fx.westeurope.azurecontainerapps.io"

How can I get e.g. TESTDATA_URI in a bash script to work with the endpoint?

A: Output from azd env get-values can be piped into source statement to have these values available:
#!/bin/bash

source <(azd env get-values)

curl -X POST "$TESTDATA_URI/api/Generate"


text:
Q: How do I format Date/Time with jQuery Templates? i've just started using jQuery Templates as my javascript template engine.  My question is, how can i format a date (returned from a ASP.NET Json ActionResult) in the form:
/Date(1288709830000)/

I tried doing the following:
{{= $.format(new Date(parseInt(comment.DateCreated.substr(6))), 'd')}}

Note the above uses the new jquery globalization plugin to add the $.format method.  Also note that {{= comment.DateCreated }} is long hand for saying ${comment.DateCreated}.
I'd really appreciate it if you could help.

A: This is what I used
var formatDate = function (datetime) {
    var dateObj = new Date(parseInt(datetime.replace("/Date(", "").replace(")/", ""), 10));
    return dateObj.format("dd-MMM-yyyy"); //01-Jun-2001
}

And this in my JQuery Template
${formatDate(InceptionDate)}

A: This does actually work.  I was using the beta version hosted on the Microsoft CDN.  If you download the latest version everything works as expected.

A: I've come up with a very hacky solution.  If you add the following function to the page:
function format(o, t) {
    return $.format(o, t);
}

You can then change the expression to:
{{= format(new Date(parseInt(comment.DateCreated.substr(6))), 'd') }}

And it works fine.  This seems strange that two plugins both created by Microsoft would conflict in this way.

A: To format a datetime within a jQuery template you could write a function like:
function formatDate(datetime) {
    var dateObj = new Date(datetime);
    var dateStr = (dateObj.getMonth()+1) + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();
    return dateStr; // will return mm/dd/yyyy
}

You can then call this function from within your jQuery template like so: ${formatDate(comment.DateCreated)}
For more details see: http://api.jquery.com/template-tag-equal


text:
Q: How to get rid of the xmlns when using xml serialization I don't want the following to be appended to the root element
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
what should I do when using XML serialization.

A: By using the Serialize method:
public class Foo { }

class Program
{
    static void Main()
    {
        var foo = new Foo();
        var serializer = new XmlSerializer(foo.GetType());
        var ns = new XmlSerializerNamespaces();
        ns.Add(string.Empty, string.Empty);
        serializer.Serialize(Console.Out, foo, ns);
    }
}

Notice the last argument (ns).


text:
Q: Отображения .txt в бразере без сохранения Помогите найти информацию по данному вопросу.
Есть txt файл, который создаётся и заменяется на новый каждый день. Нужно сделать так, чтобы этот файл отображался в самом браузере, но он выдаёт окно сохранения. Не знаю с чем это связано, но если зайти на сервер и открыть этот файл и сохранить его(ctrl+s) то после этого он начинает отображаться, а не скачиваться.
Доп информация.
Сервер tomcat. Content-type до и после text/plain. Размер файла не изменяется после сохранения.

A: <mime-mapping>
    <extension>txt</extension>
    <mime-type>text/plain;charset=UTF-8</mime-type>
</mime-mapping>

Помогло. Спасибо.


text:
Q: Getting error for checkbox binding in knockout during serialization I'm getting an error:

Uncaught InvalidStateError: Failed to read the 'selectionDirection' property from 'HTMLInputElement': The input element's type ('checkbox') does not support selection.

on:
<div class="panel-heading paddingRight20px">
  <input style="position: absolute;" type="checkbox" data-bind="checked: IsSelectedCoverage" />
</div>

When I am debugging the code, I found that it was giving this error when I am trying to serialize the viewmodel (which has the IsSelectedCoverage observable).
Ajax call where I am serializing:
self.finish = function () {
    debugger;
    var CorrespondenceData = ko.toJSON(self);
    $.ajax({
        url: endPoints.Finish + '/' + self.MemberId(),
        type: 'POST',
        dataType: 'json',
        data: CorrespondenceData,
        contentType: 'application/json; charset=utf-8',
        beforeSend: function () {
            startSpinner();
        }
    })

I am not sure if this is due to serializing the model.

A: Like @Jeroen says, we'd need to see at least your view-model to determine the cause, but here's something which might help: you're relying on the out-of-the-box serialisation provided by Knockout, but you can override this to be more certain of what's being returned.
If you add a function called toJSON to your view-model then this will be called by Knockout (although you can just as easily call it yourself). This then gives you more fine-grained control over what's being serialised and how.
[source]
In this toJSON function, if you don't want to monotonously write out the whole JSON string then you can build a very simple object and call toJSON on that.
For example, let's say you're view-model has 15 observables but that the server is interested in only 2 of these, firstName and lastName:
var toJSON = function() {
    return JSON.stringify({
                                firstName: this.firstName(),
                                lastName: this.lastName()
                          });

Where this.firstName() gets the value of the firstName observable on the same view-model.
Calling toJSON or ko.toJSON on that view-model will now return a JSON string with only those two properties
It may be that you have some extraneous property on your view-model which is sending something unexpected back to the server.


text:
Q: Monodroid JNI for Java reflection to call a private method In a Monodroid project, I need to be able to call a private method on a class.  From an answer on a related question, it seems that this is possible in Java via reflection:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.os.ParcelFileDescriptor;

...

ParcelFileDescriptor pipe[] = null;

try {
    Method createPipeMethod = ParcelFileDescriptor.class.getDeclaredMethod("createPipe");
    pipe = (ParcelFileDescriptor[]) createPipeMethod.invoke(null);
} catch (NoSuchMethodException e) {
    throw new RuntimeException(e);
} catch (IllegalAccessException e) {
        throw new RuntimeException(e);
} catch (InvocationTargetException e) {
    throw new RuntimeException(e);
}

I need to use this code from Monodroid.  Unfortunately, java.lang.reflect is not available in Monodroid.  However, it has been suggested that I can run this code using JNI from my Monodroid project.  The Xamarin documentation states that inline JNI is possible, without having to bind a whole JAR.  Unfortunately, further documentation doesn't say anything more on the subject.  Furthermore, the documentation on JNIEnv is blank.
It looks like I need JNIEnv.CallVoidMethod(), but I have no idea how to do it.  I can't find an example, or further documentation.
How can I use java.lang.reflect in my Monodroid project, or in some other way call the private method .createPipe on ParcelFileDescriptor?

A: Did you try to use C# reflection on Android.OS.ParcelFileDescriptor?
http://docs.mono-android.net/index.aspx?link=T%3AAndroid.OS.ParcelFileDescriptor
I did not yet try it, but if Mono for Android even wraps private members of a Java class, simply using C# reflection might be enough.
If this failed, you can pursue on the JNI attempt.

A: It should be possible with JNI: http://docs.xamarin.com/guides/android/advanced_topics/java_integration_overview/working_with_jni#_Static_Methods
A rough untested sketch:
var methodId = JNIEnv.GetStaticMethodID(ParcelFileDescriptor.Class.Handle,
                                        "createPipe",
                                        "()[Landroid/os/ParcelFileDescriptor;");
var result = JNIEnv.CallStaticObjectMethod(myCSharpFileDescriptorInstance.Handle,
                                           methodId);


text:
Q: In selenium webdriver, verify that all products are sorted by name In Selenium WebDriver, if I select drop down value by 'name' then how do I verify that all products are sorted by name?
This is my code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Magneto
{

    public static void main(String[] args) throws Exception {

        WebDriver d1 = new FirefoxDriver();
        d1.navigate().to("http://live.guru99.com/index.php/");
        d1.manage().window().maximize();
        if (d1.getTitle().equals("Home page")) {
            System.out.println("title matched");
        } else {
            System.out.println("title not matched expected title is "
                + d1.getTitle());
        }
        d1.findElement(By.xpath("//nav[@id='nav']/ol/li[1]/a")).click();
        Thread.sleep(2000);
        if (d1.getTitle().equals("Mobile")) {
            System.out.println("title matched");
        } else {
            System.out.println("title not matched expected title is "
                + d1.getTitle());
        }
        Select s1 = new Select(d1.findElement(By.xpath("//html[@id='top']/body/div[1]/div/div[2]/div/div[2]/div[1]/div[3]/div[1]/div[1]/div/select")));
        s1.selectByVisibleText("Name");}}

A: Add the following code to your main method
//create an LinkedList instead of arraylist because it preserves insertion order

List<WebElement> products_Webelement = new LinkedList<WebElement>();

//store the products (web elements) into the linkedlist

products_Webelement = d1.findElements(By.xpath("//img[contains(@id, 'product-collection-image')]"));

//create another linked list of type string to store image title

LinkedList<String> product_names =  new LinkedList<String>();

//loop through all the elements of the product_webelement list get it title and store it into the product_names list

for(int i=0;i<products_Webelement.size();i++){

    String s = products_Webelement.get(i).getAttribute("alt");

    product_names.add(s);

}

//send the list to chkalphabetical_order method to check if the elements in the list are in alphabetical order

boolean result = chkalphabetical_order(product_names);

//print the result

System.out.println(result);

In the method chkalphabetical_order we check if the elements are in alphabetical order by using compareTo method because string class in java implements Comparable and the comparison will be done by using the strings natural ordering.This method will return true if the elements are in alphabetical order else return false
    public static boolean chkalphabetical_order(LinkedList<String> product_names){

    String previous = ""; // empty string

    for (final String current: product_names) {
        if (current.compareTo(previous) < 0)
            return false;
        previous = current;
    }

    return true;

    }

Hope this helps you . I tested the above code it was working perfectly.If you have any doubts kindly get back

A: String sortElement = driver.findElement(By.xpath("//li[1]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "IPhone");
sortElement = driver.findElement(By.xpath("//li[2]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "Samsung Galaxy");
sortElement = driver.findElement(By.xpath("//li[3]//a[@class=\"product-image\"]")).getAttribute("title");
Assert.assertEquals(sortElement, "Xperia");

A: I had a scenario in which i had to verify the sorted menu
try{
        List<WebElement> lst = driver.findElements(By
                .xpath(".//*[@id='global-wrapper']/nav/ul/li"));
        String[] str = new String[lst.size()];
        String[] ORGstr = new String[lst.size()];

    int i = 0;
    int l = 0;
    for (WebElement ele1 : lst) {
        if (ele1.getText() != null)
            ORGstr[l] = ele1.getText();
        l++;
    }

    for (WebElement ele : lst) {
        if (ele.getText() != null)
            str[i] = ele.getText();
        i++;
    }

    for (int b = 0; b < str.length; b++) {

        for (int j = b + 1; j < str.length; j++) {
            if (str[b].compareTo(str[j]) > 0) {
                String temp = str[b];
                str[b] = str[j];
                str[j] = temp;
            }

        }
    }
    int o = 1;
    int s = 0;

    for (int k = 0; k < str.length; k++) {
        //System.out.println("Sorted Order " + str[s] + " ");
        //System.out.println("Original Order " + ORGstr[o] + " ");
        if (!(str[s].equalsIgnoreCase("Dashboard"))) {
            if (str[s].equalsIgnoreCase(ORGstr[o])) {
                assertEquals(str[s], ORGstr[o]);
                o++;
                log.debug("verified dashboard menu is sorted");
            } else {

                Assert.fail();
            }
        }
        s++;

    }

    }catch(Exception e){

        ErrorLog.fatal("Error: Element not located in menu");
    }

In my code i had to skip a menu item called dashboard i wrote it according to my requirement you can change accordingly!!!!

A: List<WebElement> li=new LinkedList<>(obj.findElements(By.xpath("//h2[@class='product-name']/a")));
        LinkedList<String> pn=new LinkedList<String>();
        for(int i=0;i<li.size();i++)
        {
             //just displaying the product names
            //System.out.println(li.get(i).getText());
            pn.add(li.get(i).getText());
        }
        boolean result = comp_order(pn);

you need to add one more method

//alphabetical order checking
    public static boolean comp_order(LinkedList<String> pn)
    {
        String prev=""; // empty string
        for (final String cur: pn)
        {
            if (cur.compareTo(prev) < 0)
            {
                return false;
            }
            prev=cur;
        }
        return true;
        }

i did nothing just improved previous solution its working

A: This Sorting method fails if Products' names start with both Lowercase letters and Uppercase Letters.
if you run, and check
public class Testing
{
    public static void main(String[] args)
    {
        String name1= "pro";
        String name2= "TestPro";
        int tmp=name2.compareTo(name1);
        System.out.println(tmp);
    }
}
Output: -28

Although, we were expecting it to return some positive integer.
So, to get rid of this problem we need to convert all names to lowercase and then Check if they are sorted or not?
Here is how i did it, My code has some other functions as well to which you can ignore.
public class SortingTest
{
    static WebDriver driver;

    @Test
    public static void AnchorTags() throws InterruptedException
    {

        driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        Thread.sleep(5000);
        driver.get("http://xyz21314131.co");

        driver.findElement(By.linkText("Ascending Order")).click();
        Thread.sleep(5000);
        WebElement Row=driver.findElement(By.xpath("//* [@id='content']/div/div[2]"));
        List<WebElement> Anchortags=Row.findElements(By.tagName("a"));

        //Linked List to Store ProductNames
        LinkedList<String> productNames=new LinkedList<String>();

        int size=Anchortags.size();

        for(WebElement temp:Anchortags)
        {
            String sTemp=temp.getText();
          //Important
           **// to remove extra spaces and to Lowercase Every product name**
            productNames.add(sTemp.toLowerCase().trim());
        }
        System.out.println(productNames);

        //Check SortedOr NOt?

        Boolean num=checkDescendingOrder(productNames);
        System.out.println("boolean value"+ num);
        if(num==true)
        {

            System.out.println("Products names are Sorted in ascending Order");
        }
        else {
            System.out.println("Products names are not Sorted in ascending Order");
            }
        System.out.println("New List:--"+productNames);
        System.out.println("Size is " + size);
    }

public static boolean checkAscendingOrder(LinkedList<String> Names)
{
    String previous = ""; // empty string

    for (String current: Names) {
        if (current.compareTo(previous) < 0)
        {
            return false;
        }
        previous = current;
    }
    return true;
    }
}


text:
Q: Radio button selection is slow if apply conditions on it I have a radio button. When I click on it more than 50 fields are disabled, some texts are changed and few classes are added using jquery. Everything works fine except the radio button selection shows a delay in getting selected.
I know that DOM manipulation slows down the UI rendering. Is there any possible solution for this problem?
Unfortunately I can't show the exact code, but I can provide some sample for better understanding -
$(document).ready(callMe);
function callMe() {
    $("#text-field").on("change", function(){
        var value = $("#text-field").val();
        $("#value").html("yo" + value);
    }).trigger("change");
}

<input type="text" id="text-field">

Please Note - This is just a sample manipulation, In actual code there are plenty of manipulations required which takes time and hence slows down the rendering of selection of radio button.

A: Okay Try something like this:
$(document).ready(function () {
    const $val = $("#value");
    const $textField = $("#textField");
    textField.on("change", function ( val ){
        $val.html("yo" + this.value);
    });
    $val.html("yo" + $textField.val() );
});

<input type="text" id="textField">


text:
Q: TwinCAT 3.0 Broadcast search without Automation Interface Is there any way to perform a broadcast search using the general TwinCAT.Ads.* namespace?
Using the automation system for this seems extremely overkill, not to mention that it takes almost a full minute to initialize the EnvDTE, generate a solution, and finally be able to do the search.
Even just finding a way to get a list of the currently configured routes would probably be good enough.
The TwinCat 3 service in the sys-tray seems to be able to do it without this extra baggage, so I'm hoping there's some public interface for this.
It will have the added benefit of not needing references to the Visual Studio SDK.

A: There is a file C:\TwinCAT\3.1\Target\StaticRoutes.xml which contains all the active static routes of that computer. At least I have always though so. So I think that the system tray service just reads that file?
Of course, that doesn't tell you if the route is really in operation. About that I have no idea.
You can just parse the XML. Example of the file contents:
<?xml version="1.0" encoding="UTF-8"?>
<TcConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <RemoteConnections>
        <Route>
            <Name>PLC_1</Name>
            <Address>192.168.1.2</Address>
            <NetId>192.168.1.2.1.1</NetId>
            <Type>TCP_IP</Type>
        </Route>
        <Route>
            <Name>PLC_2</Name>
            <Address>192.168.1.3</Address>
            <NetId>192.168.1.3.1.1</NetId>
            <Type>TCP_IP</Type>
        </Route>
    </RemoteConnections>
</TcConfig>


text:
Q: doubble scroll bar on wordpress home page I have a WordPress website and I changed some CSS with Custom CSS Plugin  to adjust the position of the Footer. Here my CSS Changes:
.page-id-736 .main-title {
  visibility: visible;
  display: none;
}

.page-id-1981 .main-title {
  visibility: visible;
  display: none;
}

.page-id-2005 .main-title {
  visibility: visible;
  display: none;
}

.page-id-1989 .main-title {
  visibility: visible;
  display: none;
}

.page-id-1992 .main-title {
  visibility: visible;
  display: none;
}

.page-id-1997 .main-title {
  visibility: visible;
  display: none;
}

.page-id-3318 .main-title {
  visibility: visible;
  display: none;
}

.page-id-3339 .main-title {
  visibility: visible;
  display: none;
}

.page-id-3345 .main-title {
  visibility: visible;
  display: none;
}

.page-id-3348 .main-title {
  visibility: visible;
  display: none;
}

.page-id-3351 .main-title {
  visibility: visible;
  display: none;
}

.page-id-3354 .main-title {
  visibility: visible;
  display: none;
}

.page-id-736 .main-title + .breadcrumbs {
  display: none;
}

.page-id-1981 .main-title + .breadcrumbs {
  display: none;
}

.page-id-2005 .main-title + .breadcrumbs {
  display: none;
}

.page-id-1989 .main-title + .breadcrumbs {
  display: none;
}

.page-id-1992 .main-title + .breadcrumbs {
  display: none;
}

.page-id-1997 .main-title + .breadcrumbs {
  display: none;
}

.page-id-3318 .main-title + .breadcrumbs {
  display: none;
}

.page-id-3339 .main-title + .breadcrumbs {
  display: none;
}

.page-id-3345 .main-title + .breadcrumbs {
  display: none;
}

.page-id-3348 .main-title + .breadcrumbs {
  display: none;
}

.page-id-3351 .main-title + .breadcrumbs {
  display: none;
}

.page-id-3354 .main-title + .breadcrumbs {
  display: none;
}

.hentry__content .page-box p {
  display: none;
}

.comment {
  display: none;
}

.col-xs-12.form-group {
  display: none;
}

#comments.comments-post-1 {
  display: none;
}

.page-id-2362 .footer {
  margin: -45px;
}

.page-id-2362 .row {
  text-align: center;
}

and this is what my homepage looks like now:

Could someone please help me?
Thanks,
Nico

A: The problem is your footer has a -45px margin on it.
I think you were looking to limit this vertically.
so it should be margin-top: -45px on your footer.
Then you can remove the overflow-x: hidden; from your body .boxed-container{}
which is why the second scroll bar is appearing ( once you have defined a scroll behavior this is your problem ) just removing the overflow-x on the body .boxed-container will solve your problem but the footer having that -45px margin is what is the root cause of all your problems.

A: How could it help with the power of the code in question? If you can not share the URL of your site (understandable), at least share enough code with which we can recreate the situation / problem and be able to respond accordingly.


text:
Q: Using .NET Core to create windows applications Can I create windows services with .NET Core or do I still need using .NET Framework?

A: Based on the comments the windows service creation is not possible with .NET Core right now.


text:
Q: Rime of the Ancient Mariner? I recently read the beautiful poem by Samuel Coleridge. Why did he call it a rime? I looked up rime on the dictionary, and it means a thin layer of ice; so was the name playing around with the rhyme of the words "rime" and "rhyme" at the same time, referring to the icy time when the Ancient Mariner killed the albatross (that was when the ship was somewhere near the Southern Pole)?

A: The poem was first published in 1798 - but even by the standards of the time, it had a lot of archaic words and spellings.
It was substantially revised by Coleridge before being republished some 20 years later, but he kept lots of archaic spellings, including rime.
I'd just say Coleridge did this for artistic effect, and leave it at that. But here's some more detail if you want to follow it up.

A: Look at the age of the book, 1798, pre-dictionary.
It was originally called The Rime of the Ancyent Marinere, some of the words have been corrected.  Not all of them have.  Rime can still be used for rhyme.

A: It's simply an archaic, variant spelling. From Wikipedia:

The spelling rhyme (from original rime) was introduced at the beginning of the Modern English period, due to a learned (but etymologically incorrect) association with Greek ῥυθμός (rhythmos, rhythm).
The older spelling rime survives in Modern English as a rare alternative spelling. A distinction between the spellings is also sometimes made in the study of linguistics and phonology, where rime/rhyme is used to refer to the nucleus and coda of a syllable. In this context, some prefer to spell this rime to separate it from the poetic rhyme covered by this article (see syllable rime).


text:
Q: `UnityEngine.LineRenderer.SetColors(UnityEngine.Color, UnityEngine.Color)' is obsolete: `Use startColor, endColor or colorGradient instead.'
Receiving this error in Unity version 5.6.0b7 : Assets/GoogleVR/Scripts/UI/GvrLaserPointer.cs(83,18): warning CS0618: UnityEngine.LineRenderer.SetColors(UnityEngine.Color, UnityEngine.Color)' is obsolete:Use startColor, endColor or colorGradient instead.'
Can't seem to get this right. Any ideas?

A: You need to do what it tells to do:
 lineRenderer.SetColors(Color.white, Color.black);

becomes
lineRenderer.startColor = Color.white;
lineRenderer.endColor = Color.black

Same will apply to SetWidth => start/endWidth
And for the SetVertexCount => numPositions


text:
Q: Custom template for Essential grid posts Wordpress plugin I use Essential Grid Posts plugin, I would like to create a custom template for posts I create in Ess. Grid Posts
Usually to create custom template for post that belong to a category I use the following code:
<?php

$post = $wp_query->post;

if ( in_category('3') ) {

include(TEMPLATEPATH . '/single-1.php');

} elseif ( in_category('7') ) {

include(TEMPLATEPATH . '/single-2.php');

} else {

include(TEMPLATEPATH . '/single-default.php');

}

?>

But it doesn't work with the id category of Essential grid post. What's wrong?

A: Repost from FAQ plugin:

Duplicate your theme's "single.php" and/or "archive.php" file, and
  rename it to one of the following: single-essential_grid.php
  archive-essential_grid.php

http://www.themepunch.com/faq/apply-specific-theme-template-file-to-ess-grid-posts-advanced/


text:
Q: Treeview Control - ContextSwitchDeadlock workarounds I have built a treeview control that lists the directory structure of any drive or folder.  However, if you select a drive, or something with a large structure of folders and sub folders the control takes a long time to load and in some instances shows an MDA ContextSwitchDeadlock message.  I have disabled the MDA deadlock error message and it works, but I don't like the time factor and the app looking like it has locked.  How can I modify the code so that it keeps pumping messages, and rather than buffering the whole view and passing it in its entirety to the control, is there a way of pushing it, to the control, as it is being built?
//Call line
treeView1.Nodes.Add(TraverseDirectory(source_computer_fldbrowser.SelectedPath));

private TreeNode TraverseDirectory(string path)
    {
        TreeNode result;
        try
        {
            string[] subdirs = Directory.GetDirectories(path);
            result = new TreeNode(path);
            foreach (string subdir in subdirs)
            {
                TreeNode child = TraverseDirectory(subdir);
                if (child != null) { result.Nodes.Add(child); }
            }
            return result;
        }
        catch (UnauthorizedAccessException)
        {
            // ignore dir
            result = null;
        }
        return result;
    }

Thanks R.

A: If you not need the whole structure loaded in the TreeView but only see what is being expanded, you can do it this way:
// Handle the BeforeExpand event
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
   if (e.Node.Tag != null) {
       AddTopDirectories(e.Node, (string)e.Node.Tag);
   }
}

private void AddTopDirectories(TreeNode node, string path)
{
    node.BeginUpdate(); // for best performance
    node.Nodes.Clear(); // clear dummy node if exists

    try {
        string[] subdirs = Directory.GetDirectories(path);

        foreach (string subdir in subdirs) {
            TreeNode child = new TreeNode(subdir);
            child.Tag = subdir; // save dir in tag

            // if have subdirs, add dummy node
            // to display the [+] allowing expansion
            if (Directory.GetDirectories(subdir).Length > 0) {
                child.Nodes.Add(new TreeNode());
            }
            node.Nodes.Add(child);
        }
    } catch (UnauthorizedAccessException) { // ignore dir
    } finally {
        node.EndUpdate(); // need to be called because we called BeginUpdate
        node.Tag = null; // clear tag
    }
}

The call line will be:
TreeNode root = new TreeNode(source_computer_fldbrowser.SelectedPath);
AddTopDirectories(root, source_computer_fldbrowser.SelectedPath);
treeView1.Nodes.Add(root);


text:
Q: Coef not defined because of similarity and pvalues I have a CRM data set used for an experiment, where the dummy W corresponds to the treatment/control group (see code below). When I tested for the independence of W from the other features, I realized two things:

*

*When using model.matrix, some coefficients (1 in this dummy dataset) were not defined because of similarity. This did not happen when feeding the DT straight to lm()

*The model obtained in both cases produces different results i.e., the p-values of the individual features changes

I (think that I) understand the concept of multi-collinearity but in this particular case I don't quite understand a) why it comes up b) why it has a different impact on model.matrix and lm
What am I missing?
Thanks a lot!
set.seed(1)

n = 302

DT = data.table(
    zipcode = factor(sample(seq(1,52), n, replace=TRUE)),
    gender = factor(sample(c("M","F"), n, replace=TRUE)),
    age = sample(seq(1,95), n, replace=TRUE),
    days_since_last_purchase = sample(seq(1,259), n, replace=TRUE),
    W = sample(c(0,1), n, replace=TRUE)
)

summary(DT)

m = model.matrix(W ~ . +0, DT)
f1 = lm(DT$W ~ m)
f2= lm(W~ ., DT)

p_value_ratio <- function(lm)
{
    summary_randomization = summary(lm)
    p_values_randomization = summary_randomization$coefficients[, 4]
    L = length(p_values_randomization)
    return(sum(p_values_randomization <= 0.05)/(L-1))
}

all.equal(p_value_ratio(f1), p_value_ratio(f2))

alias(f1)
alias(f2)

A: Your problem is the + 0 in model.matrix. The second fit includes the intercept in the model matrix. If you exclude it, less factor levels (which are normally represented by the intercept) get excluded:
colnames(model.matrix(W ~ ., DT))
#excludes zipcode1 and genderf since these define the intercept

colnames(model.matrix(W ~ . + 0, DT))
#excludes only genderf

Note that f1 includes an intercept, which is added by lm (I believe by an internal call to model.matrix, but haven't checked):
m = model.matrix(W ~ . + 0, DT);
f1 = lm(DT$W ~ m );
model.matrix(f1)

You might want this:
m = model.matrix(W ~ ., DT);
f1 = lm(DT$W ~ m[,-1]);

(Usually you construct the model matrix only manually if you want to use lm.fit directly.)
f2= lm(W~ ., DT);
all.equal(unname(coef(f1)), unname(coef(f2)))
#[1] TRUE

In the end, this boils down to your understanding of treatment contrasts. Usually, you shouldn't exclude the intercept from the model matrix.


text:
Q: how to normalize this below json using panda in django using this view.py query my output is showing something like this. you can see in choices field there are multiple array so i can normalize in serial wise here is my json
{"pages":[{"name":"page1","title":"SurveyWindow Pvt. Ltd. Customer Feedback","description":"Question marked * are compulsory.",
    "elements":[{"type":"radiogroup","name":"question1","title":"Do you like our product? *","isRequired":true,
        "choices":[{"value":"Yes","text":"Yes"},{"value":"No","text":"No"}]},{"type":"checkbox","name":"question2","title":"Please Rate Our PM Skill","isRequired":false,"choices":[{"value":"High","text":"High"},{"value":"Low","text":"Low"},{"value":"Medium","text":"Medium"}]},{"type":"radiogroup","name":"question3","title":"Do you like our services? *","isRequired":true,"choices":[{"value":"Yes","text":"Yes"},{"value":"No","text":"No"}]}]}]}

this is my view.py
    jsondata=SurveyMaster.objects.all().filter(survey_id='1H2711202014572740')
    q = jsondata.values('survey_json_design')
    qs_json = pd.DataFrame.from_records(q)
    datatotable = pd.json_normalize(qs_json['survey_json_design'], record_path=['pages','elements'])
    qs_json = datatotable.to_html()

A: Based on your comments and picture here's what I would do to go from the picture to something more SQL-friendly (what you refer to as "normalization"), but keep in mind this might blow up if you don't have sufficient memory.
Create a new list which you'll fill with the new data, then iterate over the pandas table's rows, and then over every item in your list. For every iteration in the inner loop use the data from the row (minus the column you're iteration over). For convenience I added it as the last element.
# Example data
df = pd.DataFrame({"choices": [[{"text": "yes", "value": "yes"},
                                {"text": "no", "value": "no"}],
                               [{"ch1": 1, "ch2": 2}, {"ch3": "ch3"}]],
                   "name": ["kostas", "rajesh"]})

data = []
for i, row in df.iterrows():
    for val in row["choices"]:
        data.append((*row.drop("choices").values, val))

df = pd.DataFrame(data, columns=["names", "choices"])
print(df)

    names                          choices
0  kostas  {'text': 'yes', 'value': 'yes'}
1  kostas    {'text': 'no', 'value': 'no'}
2  george             {'ch1': 1, 'ch2': 2}
3  george                   {'ch3': 'ch3'}

This is where I guess you want to go. All that's left is to just modify the column / variable names with your own data.


text:
Q: In C, how to add 3rd party Libraries and call from my existing code base using Makefile I am new to IOT and cloud.
For IOT project, we are trying to send on the fly data to cloud for Analytics.
We are using only c, cpp code in my target board. Debian OS.
Every one second, 2 seconds, 3 seconds different types of data will come.
In my target board, I want to use 3rd party libraries(https_client) to send data to the cloud. I need to hit the service(URL) in the cloud with data (using only GET method).
For this, I downloaded https_client code and trying to integrate into my code base.
In the below 1st make file is original Makefile, 2nd one is only 3rd party s/w Makefile, the 3rd one is modified original Makefile to integrate 3rd party library.
In my target board, we don't have much space, so what is best light weight approach to send data to the cloud? My cloud will support only https and WSS.
Is my approach is correct? Any other easy way is available?
In the modified Makefile I am getting below error.

make: *** No rule to make target
  `https_client-master/https_client-master/main.c', needed by `all'.
  Stop.

My changes in Makefile is not the standard way. Can anyone review my modified Makefile and correct me.
Waiting for your valuable suggestion.
#---------------------------------------------------------------------------
-
--
#1.  Below is the original make file of my existing code base
#---------------------------------------------------------------------------
---
SOURCES=./SRC/MMC/Main.cpp \
    ./SRC/MMC/ModbusMasterController.cpp \
    ./SRC/DM/DeviceManager.cpp \
    .......
    ./Wrapper/MtrWrapper.cpp

OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=BusMaster
CFLAGS = -c -w -I/usr/include/libxml2 -I./INC/Common -I./INC/ADM -I./INC/MMC
-I./INC/DM  -I./INC/CM  -I./INC/MMT -I./INC/MPI -I./INC/MMT/DataProc -
I./INC/MMT/CmdProc -I./INC/MMT/CmdProc/Fileoperations -I./INC/SH -
I./INC/FT_MBUS -I./INC/Timer -I./Wrapper -I./INC/DC -Wall

LDFLAGS = -Bdynamic -lSharedMemory -lMessageQueue -luspepc -lxml2 -
lmbusmaster -lrt

CC=g++

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
$(CC) $(OBJECTS) -o $@ $(LDFLAGS)

.cpp.o:
$(CC) $(CFLAGS) $< -o $@

clean:
rm -rf $(OBJECTS) $(EXECUTABLE)

#----------------------------------------original make end------------------
 -
-------------------

#----------------------------------------2. Below is the 3rd pary Library
Makefile I want to add--------------------------------------
#CROSS = arm-linux-gnueabihf-

MAKE = make

CC = $(CROSS)gcc
LD = $(CROSS)ld
STRIP = $(CROSS)strip

ROOT_DIR = $(CURDIR)
MBEDTLS = $(ROOT_DIR)/mbedtls

CFLAGS = -fPIC -DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -O2
LDFLAGS =

INCLUDES = -I$(MBEDTLS)/include
LIBS = $(MBEDTLS)/library/libmbedx509.a $(MBEDTLS)/library/libmbedtls.a
$(MBEDTLS)/library/libmbedcrypto.a

SOURCES = main.c https.c

OBJS = $(SOURCES:.c=.o)

.SUFFIXES:.c .o

all: https_client

mbedtls_make:
@for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir ; \
    if [ $$? != 0 ]; then exit 1; fi; \
done

https_client: mbedtls_make $(OBJS)
@echo Linking: $@ ....
$(CC) -o $@ $(OBJS) $(LDFLAGS) $(LIBS)
$(STRIP) -s $@

.c.o:
@echo Compiling: $< ....
$(CC) -c $(CFLAGS) $(INCLUDES) -o $@ $<

clean: mbedtls_clean
rm -f https_client *.o

mbedtls_clean:
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir clean; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done
#----------------------------------------3rd pary Library Makefile end------
  -
-------------------------------

#----------------------------------------3. Modified original Makefile to
add
3rd party library----------------

SOURCES=./SRC/MMC/Main.cpp \
    ./SRC/MMC/ModbusMasterController.cpp \
    ./SRC/DM/DeviceManager.cpp \
    .......
    ./Wrapper/MtrWrapper.cpp

 SOURCES2=./https_client-master/https_client-master/main.c \
    ./https_client-master/https_client-master/https.c

OBJECTS=$(SOURCES1:.cpp=.o)
OBJS=$(SOURCES2:.c=.o)
.SUFFIXES:.c .o
ROOT_DIR = $(CURDIR)
MBEDTLS = $(ROOT_DIR)/https_client-master/https_client-master/mbedtls
EXECUTABLE1=BusMaster
EXECUTABLE2=https_client
CFLAGS = -c -w -I/usr/include/libxml2 -I./INC/Common -I./INC/ADM -I./INC/MMC
-I./INC/DM  -I./INC/CM  -I./INC/MMT -I./INC/MPI -I./INC/MMT/DataProc -
I./INC/MMT/CmdProc -I./INC/MMT/CmdProc/Fileoperations -I./INC/SH -
I./INC/FT_MBUS -I./INC/Timer -I./Wrapper -I./INC/DC -Wall
CFLAGS2 = -fPIC -DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -O2
INCLUDES = -I$(MBEDTLS)/include
LIBS = $(MBEDTLS)/library/libmbedx509.a $(MBEDTLS)/library/libmbedtls.a
$(MBEDTLS)/library/libmbedcrypto.a
LDFLAGS = -Bdynamic -lSharedMemory -lMessageQueue -luspepc -lxml2 -
lmbusmaster -lrt
LDFLAGS2 =
STRIP = strip

CC1=g++
CC2=gcc

 all: $(SOURCES1) $(EXECUTABLE1) $(SOURCES2) $(EXECUTABLE2)
 #$(SOURCES2)
 $(EXECUTABLE1): $(OBJECTS)
 @echo EXECUTABLE1:
 $(CC1) $(OBJECTS) -o $@ $(LDFLAGS)

 mbedtls_make:
 @echo mbedtls_make: ....
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir ; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done

 $(EXECUTABLE2): mbedtls_make $(OBJS)
 @echo Linking: $@ ....
 $(CC1) -o $@ $(OBJS) $(LDFLAGS2) $(LIBS)
 $(STRIP) -s $@

 .c.o:
 @echo Compiling c: $< ....
 $(CC2) -c $(CFLAGS2) $(INCLUDES) -o $@ $<

 .cpp.o:
 @echo Compiling cpp: $< ....
 $(CC1) $(CFLAGS) $< -o $@

 clean: mbedtls_clean
 rm -rf $(OBJECTS) $(EXECUTABLE1)
 rm -f https_client *.o
 mbedtls_clean:
 @for dir in $(MBEDTLS); do \
    $(MAKE) -C $$dir clean; \
    if [ $$? != 0 ]; then exit 1; fi; \
 done

 #------------------------------------------Modified original Makefile end--
 -
 ---------------------------------

A: I don't think you should have 2 lists of sources. Below is snippet of how MBEDTLS is included in Makefile.
https://github.com/acornblue/AZURE_LAB
#####################################################
# Projects/Multi/Applications/Azure_Sns_DM/Makefile
#####################################################
C_SOURCE = \
...
Middlewares/Third_Parties/mbedtls/library/aes.c \
Middlewares/Third_Parties/mbedtls/library/aesni.c \
...
-DUSE_MBED_TLS \
-DMBEDTLS_CONFIG_FILE='<mbedtls_config.h>'
...
-IMiddlewares/Third_Parties/mbedTLS/include \


text:
Q: background image not cover menu icon after resizing I am implementing a toggle navbar. The side nav bar will become a hamburger menu icon in smaller screen size.
The background image does not cover the menu icon in smaller screen size. But it looks fine with the side navbar in a larger screen.
content: {
        flexGrow: 1,
        padding: theme.spacing(3),
        fontSize: 20,
        backgroundImage: `url(${bg})`,
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center center",
        backgroundSize: "cover",
        backgroundAttachment: "fixed",
        height: "100%"

    },

 drawer: {
        [theme.breakpoints.up('md')]: {
            width: drawerWidth,
            flexShrink: 0,
        },
    },

    menuButton: {
        marginRight: theme.spacing(2),
        [theme.breakpoints.up('md')]: {
            display: 'none',
        },
    },
    drawerPaper: {
        width: drawerWidth,
        opacity:0.8
    },

A: You have to set Background Attachment back to scroll and not fixed.


text:
Q: SQL Server Integration Services (SSIS) Package Failing with no error I have some SSIS packages that are executed as steps in a Server Agent Job. The Steps often fail with no error and I have had to add retries. Now the jobs complete but I get the warning exclamation mark telling me there has been a failure and its these steps that nearly always require a retry.
When looking at the failed step in the Job History I can see the package execution log and then it just randomly cuts off and the step beings a retry. There is no consistency with where it stops and I know there isn't a problem with the package as it eventually succeeds.
Does this sound like a network related issue? Is there anyway to find out what is causing these failures to happen?

A: Working backwards from the job, have you been able to run the package straight from the server? In older versions of SQL Server it might be in the Integration Services server, that you can connect to through Management Studio, or in newer versions of SQL Server it could be in the Integration Services Catalog on the database server. If you can run the package directly through there, then I would take a look the job credentials, or any configuration settings that are being set in the job. If the package fails when running it directly, then it may be the package itself that's the problem, which then I would go back to running and troubleshooting it from Visual Studio\BIDS to see where the problem is occurring.
On a more unusual path, if the package is doing a lot over an unsteady network, then you might be getting network related problems, or timeouts that aren't being reported as such to SQL. This might need you to get creative in staging data or breaking up the tasks into smaller packages and then calling those packages as additional steps.


text:
Q: Can Safari receive desktop notifications from YouTube or Facebook? Since switching from Chrome to Safari, I've noticed that I no longer have an option to enable desktop notifications from YouTube or Facebook. For example, going to YouTube's settings > account notifications would yield this on Chrome:

from which I could turn on desktop notifications. On Safari, I only see this:

Likewise, going to Facebook's notification settings would reveal an option to receive desktop notifications on Chrome, but not on Safari. Is there any way I can enable them?

A: If you go to your Messenger messages on Facebook, at the bottom, click on "show in Messenger". Then click on the gear icon and go to settings. You can enable notifications there, but I don't know if this will also enable Facebook messages, it will ask you if you want to receive messages from "facebook.com", so I guess it should work.
Most websites ask you if they can send messages the first time you open that website, but for some reason Facebook and YouTube don't do that.


text: Q: How can I implement this scrolling effect inside recycler view? How can I implement this scrolling effect? As you see text is scrolling with delay. Can child view ignore or override scrolling by parent?


text:
Q: React-Router 404 solution working on dev but not on aws I'm trying to avoid the 404 page in my react js app in production. In local host the solution I had worked (path="*"), but when I deploy to aws it doesn't. This is are my routes:
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
    <Route path="/" component={k.App}>
        <IndexRoute component={k.Home}/>
        <Route path="/signin" component={k.SignIn}/>
        <Route path="/signup" component={k.SignUp}/>
        ...
        <Route path="*" component={k.NotFound}/>
    </Route>
</Router>

Apparently the server is looking for the specific file, and how this is a single-page app it throws the 404. How can I solve this in the client side?
As well, when I refresh any specific page, I get a 404. I guess the problem is the same.
Thanks!
react-router v2.8.1
react v15.3.2


text:
Q: extract particular xml nodes from xml list in mulesoft i have a below xml request
<root>
<base>
<status>
<type>A</type>
<set>B</set>
</status>
<status>
<type>A</type>
<set>B</set>
</status>
<status>
<type>A</type>
<set>B</set>
</status>
</root>
</base>

And i want to extract below xml from above xml
<status>
<type>A</type>
<set>B</set>
</status>
<status>
<type>A</type>
<set>B</set>
</status>
<status>
<type>A</type>
<set>B</set>
</status>

**I dont want to use dataweave , how can achieve this logic thru xpath expression and let me any other way do to it **

A: Pls note your input xml is invalid, pls fix the root & base tag to make it valid
#Solution1   Since you are not ready to use Dataweave here is another solution below using xslt transformer and XPath as you required:-:-
   <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>

      <flow name="testFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
         <mulexml:dom-to-xml-transformer doc:name="DOM to XML"/>
        <logger message="input xml:- #[payload]" level="INFO" doc:name="Logger"/>
        <mulexml:xslt-transformer xsl-file="transform.xsl" maxIdleTransformers="2" maxActiveTransformers="5" doc:name="XSLT" mimeType="application/xml">
        </mulexml:xslt-transformer>
    </flow>

Put the transform.xsl under src/main/resource location   :
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />

    <xsl:template match="/">
        <xsl:for-each select="root/base/status">
                <status>
                <type>
                    <xsl:value-of select="type" />
                </type>
                <set>
                    <xsl:value-of select="set" />
                </set>
                </status>
            </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

#Solution2: Using XPath3 and and for-each within the flow:
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>

       <flow name="testFlow">
         <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
          <expression-component doc:name="Expression">
         <![CDATA[
          StringBuffer sb = new StringBuffer();
          flowVars.stBuffer=sb;
           ]]>
        </expression-component>
         <foreach collection="#[xpath3('//root/base/status', message.payload, 'NODESET')]" doc:name="For Each">
             <mulexml:dom-to-xml-transformer doc:name="DOM to XML"/>
             <logger message="#[payload.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "")]" level="INFO" doc:name="Logger"/>
             <set-payload value="#[payload.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "")]" doc:name="Set Payload"/>
              <set-payload value="#[flowVars.stBuffer.append(message.payload).toString()]" doc:name="Set Payload"/>
         </foreach>
         <set-payload value="#[flowVars.stBuffer]" doc:name="Set Payload" mimeType="application/xml"/>
         <mulexml:dom-to-xml-transformer doc:name="DOM to XML"/>

     </flow>

Both cases, the response will be as follows:


text:
Q: Sublime Text 3 package control seems gone I need to install the package control, but the relevant sites seem not to work at this moment. https://packagecontrol.io/ is down. Scott Granneman's page is working, but it only tells you how to install it. It refers to  http://wbond.net/sublime_packages/package_control/installation which is down too. https://github.com/wbond/package_control is available, but I have no idea at all what I should do to install it. What do I need to do to install the package control?

A: Like @jaswanth-jesse mentioned, Linode is undergoing a DDos attack. The status can be checked here:
https://status.linode.com/


text:
Q: Python - search for files, matching given name in a directory recursively I am trying to make a script to search for a file (given name) i a given directory recursively, the following format:
pi@pi ~ $ ./lect4_first.py /home dranie

Here is the complete script:
#!/usr/bin/python3

import sys
import os
flag = False

dir_path, file_name = sys.argv[1], sys.argv[2]

for root, directories, filenames in os.walk(dir_path):
  if file_name.startswith("*") or file_name.endswith("*"):
    for filename in filenames:
      if str(filename).endswith(file_name[1:]):
        flag = True
        print(os.path.join(root, filename))
      elif str(filename).startswith(file_name[:-2]):
        flag = True
        print(os.path.join(root, filename))
  else:
    for filename in filenames:
      if str(filename) == file_name:
        flag = True
        print(os.path.join(root, filename))

if flag == False:
    print("'{}' not found in the '{}' directory".format(file_name, dir_path))

So far the script works, but if it does not find match - it prints multiple not found messages:
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home
dranie not found in /home

I want to print only one not found message, if no file with the given name is found under the directory or its sub directories, but so far I am not able to figure it out...

A: I dont know what "lect4_first.py" contains?
you can try this :
import os
import sys
args = sys.argv
if len(args) == 3:
    directory,filename = args[1],args[2]
    for root, dirs, files in os.walk(directory):
        if filename in files:
           f_name = os.path.join(root, filename)
           print "File exists and its path is : "+f_name
           break
    else:
        print "File does not exist"

Output :
root:~/learn/python# python file_exist.py /root test_file_exists_1.txt
File does not exist
root:~/learn/python# python file_exist.py /root test_file_exists.txt
File exists and its path is : /root/learn/python/test_file_exists.txt


text:
Q: Border and borderless div does not start at top baseline How do I make the first and last div start at the top?

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.box {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 10px solid black;
  text-align: center;
  margin-right: 8px;
  text-decoration: none;
}
div.arrow {
  border: none;
  background-color: lightgray;
}

←

1

2

3

→

A: Just use border: 10px solid lightgray; to the div.arrow.
Because the only dimensional difference between .box and div.arrow is their border value.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.box {
    display: inline-block;
    width: 40px;
    height: 40px;
    border: 10px solid black;
    text-align: center;
    margin-right: 8px;
    text-decoration: none;
}

div.arrow {
    border: 10px solid lightgray;
    background-color: lightgray;
}

←

1

2

3

→

A: One way:
.box {
    display: block;
    float: left;
}


text:
Q: nestjs runs dist bugs that are not in the root directory When you modify or add files while running in nestjs, it generates the dist directory in the current file instead of the root directory
I want the generated file to be in the root directory instead of the current directory


text:
Q: PySpark - map with lambda function I'm facing an issue when mixing python map and lambda functions on a Spark environment.
Given df1, my source dataframe:
Animals     | Food      | Home
----------------------------------
Monkey      | Banana    | Jungle
Dog         | Meat      | Garden
Cat         | Fish      | House
Elephant    | Banana    | Jungle
Lion        | Meat      | Desert

I want to create another dataframe df2. It will contain two columns with a row per column of df1 (3 in my example).
The first column would contain the name of df1 columns. The second column would contain an array of elements with the most occurrences (n=3 in the example below) and the count.
Column      | Content
-----------------------------------------------------------
Animals     | [("Cat", 1), ("Dog", 1), ("Elephant", 1)]
Food        | [("Banana", 2), ("Meat", 2), ("Fish", 1)]
Home        | [("Jungle", 2), ("Desert", 1), ("Garden", 1)]

I tried to do it with python list, map and lambda functions but I had conflicts with PySpark functions:
def transform(df1):
    # Number of entry to keep per row
    n = 3
    # Add a column for the count of occurence
    df1 = df1.withColumn("future_occurences", F.lit(1))

    df2 = df1.withColumn("Content",
        F.array(
            F.create_map(
                lambda x: (x,
                    [
                        str(row[x]) for row in df1.groupBy(x).agg(
                            F.sum("future_occurences").alias("occurences")
                        ).orderBy(
                            F.desc("occurences")
                        ).select(x).limit(n).collect()
                    ]
                ), df1.columns
            )
        )
    )
    return df2

The error is:
TypeError: Invalid argument, not a string or column: <function <lambda> at 0x7fc844430410> of type <type 'function'>. For column literals, use 'lit', 'array', 'struct' or 'create_map' function.

Any idea how to fix it?
Thanks a lot!

A: Here is one possible solution, in which the Content column will be an array of StructType with two named fields: Content and count.
from pyspark.sql.functions import col, collect_list, desc, lit, struct
from functools import reduce

def transform(df, n):
    return reduce(
        lambda a, b: a.unionAll(b),
        (
            df.groupBy(c).count()\
                .orderBy(desc("count"), c)\
                .limit(n)\
                .withColumn("Column", lit(c))\
                .groupBy("Column")\
                .agg(
                    collect_list(
                        struct(
                            col(c).cast("string").alias("Content"),
                            "count")
                    ).alias("Content")
                )
            for c in df.columns
        )
    )

This function will iterate through each of the columns in the input DataFrame, df, and count the occurrence of each value. Then we orderBy the count (descending) and the column value it self (alphabetically) and keep only the first n rows (limit(n)).
Next, collect the values into an array of structs and finally union together the results for each column. Since the union requires each DataFrame to have the same schema, you will need to cast the column value to a string.
n = 3
df1 = transform(df, n)
df1.show(truncate=False)
#+-------+------------------------------------+
#|Column |Content                             |
#+-------+------------------------------------+
#|Animals|[[Cat,1], [Dog,1], [Elephant,1]]    |
#|Food   |[[Banana,2], [Meat,2], [Fish,1]]    |
#|Home   |[[Jungle,2], [Desert,1], [Garden,1]]|
#+-------+------------------------------------+

This isn't exactly the same output that you asked for, but it will probably be sufficient for your needs. (Spark doesn't have tuples in the way you described.) Here's the new schema:
df1.printSchema()
#root
# |-- Column: string (nullable = false)
# |-- Content: array (nullable = true)
# |    |-- element: struct (containsNull = true)
# |    |    |-- Content: string (nullable = true)
# |    |    |-- count: long (nullable = false)