问:
Bar demonstration of Shaker sort sorts all bars at once -Java
I found this code here in the accepted answer:  Java swing repainting while computing: animating sorting algorithm

And I've been trying to modify it so it works for shaker sort but my code sorts the whole thing all at once.

```<code>import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collections;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ShakerSortAnimate extends JPanel {
private static final int NUM_OF_ITEMS = 20;
private static final int DIM_W = 400;
private static final int DIM_H = 400;
private static final int HORIZON = 350;
private static final int VERT_INC = 15;
private static final int HOR_INC = DIM_W / NUM_OF_ITEMS;

private JButton startButton;
private Timer timer = null;
private JButton resetButton;

Integer[] list;
int currentIndex = NUM_OF_ITEMS - 1;

public ShakerSortAnimate() {
    list = initList();

    timer = new Timer(200, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (isSortingDone()) {
                ((Timer) e.getSource()).stop();
                startButton.setEnabled(false);
            } else {
                sortOnlyOneItem();
            }
            repaint();
        }
    });

    //button to run the program
    startButton = new JButton("Start");
    startButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            timer.start();
        }
    });

    //resets screen
    resetButton = new JButton("Reset");
    resetButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            list = initList();
            currentIndex = NUM_OF_ITEMS - 1;
            repaint();
            startButton.setEnabled(true);
        }
    });
    add(startButton);
    add(resetButton);
}

//boolean checks when array is sorted
public boolean isSortingDone() {
    return currentIndex == 0;
}

//initializes the array
public Integer[] initList() {
    Integer[] nums = new Integer[NUM_OF_ITEMS];
    for (int i = 1; i <= nums.length; i++) {
        nums[i - 1] = i;
    }
    Collections.shuffle(Arrays.asList(nums)); //shuffles array
    return nums;
}

//draws each bar
public void drawItem(Graphics g, int item, int index) {
    int height = item * VERT_INC;
    int y = HORIZON - height;
    int x = index * HOR_INC;
    g.fillRect(x, y, HOR_INC, height);
}

//My shaker sort code
public void sortOnlyOneItem()
{
    boolean swapped = true;
    int start = 0;
    int end = currentIndex;

    while (swapped==true)
    {
        swapped = false;

        for (int i = start; i < end; ++i)
        {
            if (list[i] > list[i + 1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        if (swapped==false)
            break;

        swapped = false;

        end = end-1;

        for (int i = end; i >=start; i--)
        {
            if (list[i] > list[i+1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        start = start + 1;
    }

   currentIndex--; //currentIndex is updated each time shaker sort runs
}

//draws all bars
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int i = 0; i < list.length; i++) {
        drawItem(g, list[i], i);
    }
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(DIM_W, DIM_H);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame("Sort");
            frame.add(new ShakerSortAnimate());
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}
  }
</code>```

I do realize that my Shaker Sort code has to do it for each comparison, not the entire thing but honestly, I don't even know how to begin to code that.  If anyone of you here knows how to code each comparison in shaker sort, can you help me out?

Btw, I posted the entire thing so you can try running this as well.

Thanks in advance!

答:
So, you need this...

```<code>public void sortOnlyOneItem()
{
    boolean swapped = true;
    int start = 0;
    int end = currentIndex;

    while (swapped==true)
    {
        swapped = false;

        for (int i = start; i < end; ++i)
        {
            if (list[i] > list[i + 1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        if (swapped==false)
            break;

        swapped = false;

        end = end-1;

        for (int i = end; i >=start; i--)
        {
            if (list[i] > list[i+1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        start = start + 1;
    }

   currentIndex--; //currentIndex is updated each time shaker sort runs
}
</code>```

To only run ONCE per call.  It's not doing that right now because if the while-loop, so, we need to get rid of that.

In doing so, the second loop should only be run if swapped is true AND the currentIndex should only be decremented if swapped is still true

Which brings us to something like...

```<code>public void sortOnlyOneItem() {
    boolean swapped = true;
    int start = 0;
    int end = currentIndex;

    for (int i = start; i < end; ++i) {
        if (list[i] > list[i + 1]) {
            int temp = list[i];
            list[i] = list[i + 1];
            list[i + 1] = temp;
            swapped = true;
        }
    }

    if (swapped) {
        swapped = false;

        end = end - 1;

        for (int i = end; i >= start; i--) {
            if (list[i] > list[i + 1]) {
                int temp = list[i];
                list[i] = list[i + 1];
                list[i + 1] = temp;
                swapped = true;
            }
        }
    }

    if (swapped) {
        currentIndex--; //currentIndex is updated each time shaker sort runs
    }
}
</code>```

Which still isn't quite right, as the two for-loops can make multiple changes.

Instead, we need a iteration which will only make, at most, two changes, one at the start and one at the end

Which, might, look something like...

```<code>protected void swap(int a, int b) {
    int tmp = list[a];
    list[a] = list[b];
    list[b] = tmp;
}

int endIndex = NUM_OF_ITEMS - 1;

//My shaker sort code
public void sortOnlyOneItem() {

    int startIndex = 0;
    while (startIndex < NUM_OF_ITEMS - 1 && list[startIndex] < list[startIndex + 1]) {
        startIndex++;
    }

    if (startIndex < NUM_OF_ITEMS - 1 && list[startIndex] > list[startIndex + 1]) {
        swap(startIndex, startIndex + 1);
        int end = endIndex;
        while (end > 0 && list[end - 1] < list[end]) {
            end--;
        }
        if (end > 0 && list[end - 1] > list[end]) {
            swap(end - 1, end);
        } else {
            endIndex--;
        }
    } else {
        endIndex = 0;
    }
}
</code>```

Now, this basically looks for the two indices which might be changeable (at the start and end) and swaps them if possible.  When you can iterate from the start to the end without making a change, the sort is finished.

Now, I make no claims over if this is accurate or not, only that it does the best effort to mimic the algorithm you supplied

Body:
I found this code here in the accepted answer:  Java swing repainting while computing: animating sorting algorithm

And I've been trying to modify it so it works for shaker sort but my code sorts the whole thing all at once.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collections;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ShakerSortAnimate extends JPanel {
private static final int NUM_OF_ITEMS = 20;
private static final int DIM_W = 400;
private static final int DIM_H = 400;
private static final int HORIZON = 350;
private static final int VERT_INC = 15;
private static final int HOR_INC = DIM_W / NUM_OF_ITEMS;

private JButton startButton;
private Timer timer = null;
private JButton resetButton;

Integer[] list;
int currentIndex = NUM_OF_ITEMS - 1;

public ShakerSortAnimate() {
    list = initList();

    timer = new Timer(200, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (isSortingDone()) {
                ((Timer) e.getSource()).stop();
                startButton.setEnabled(false);
            } else {
                sortOnlyOneItem();
            }
            repaint();
        }
    });

    //button to run the program
    startButton = new JButton("Start");
    startButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            timer.start();
        }
    });

    //resets screen
    resetButton = new JButton("Reset");
    resetButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            list = initList();
            currentIndex = NUM_OF_ITEMS - 1;
            repaint();
            startButton.setEnabled(true);
        }
    });
    add(startButton);
    add(resetButton);
}

//boolean checks when array is sorted
public boolean isSortingDone() {
    return currentIndex == 0;
}

//initializes the array
public Integer[] initList() {
    Integer[] nums = new Integer[NUM_OF_ITEMS];
    for (int i = 1; i <= nums.length; i++) {
        nums[i - 1] = i;
    }
    Collections.shuffle(Arrays.asList(nums)); //shuffles array
    return nums;
}

//draws each bar
public void drawItem(Graphics g, int item, int index) {
    int height = item * VERT_INC;
    int y = HORIZON - height;
    int x = index * HOR_INC;
    g.fillRect(x, y, HOR_INC, height);
}

//My shaker sort code
public void sortOnlyOneItem()
{
    boolean swapped = true;
    int start = 0;
    int end = currentIndex;

    while (swapped==true)
    {
        swapped = false;

        for (int i = start; i < end; ++i)
        {
            if (list[i] > list[i + 1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        if (swapped==false)
            break;

        swapped = false;

        end = end-1;

        for (int i = end; i >=start; i--)
        {
            if (list[i] > list[i+1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        start = start + 1;
    }

   currentIndex--; //currentIndex is updated each time shaker sort runs
}

//draws all bars
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int i = 0; i < list.length; i++) {
        drawItem(g, list[i], i);
    }
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(DIM_W, DIM_H);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame("Sort");
            frame.add(new ShakerSortAnimate());
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}
  }

I do realize that my Shaker Sort code has to do it for each comparison, not the entire thing but honestly, I don't even know how to begin to code that.  If anyone of you here knows how to code each comparison in shaker sort, can you help me out?

Btw, I posted the entire thing so you can try running this as well.

Thanks in advance!

Body:
So, you need this...

public void sortOnlyOneItem()
{
    boolean swapped = true;
    int start = 0;
    int end = currentIndex;

    while (swapped==true)
    {
        swapped = false;

        for (int i = start; i < end; ++i)
        {
            if (list[i] > list[i + 1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        if (swapped==false)
            break;

        swapped = false;

        end = end-1;

        for (int i = end; i >=start; i--)
        {
            if (list[i] > list[i+1])
            {
                int temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;
                swapped = true;
            }
        }

        start = start + 1;
    }

   currentIndex--; //currentIndex is updated each time shaker sort runs
}

To only run ONCE per call.  It's not doing that right now because if the while-loop, so, we need to get rid of that.

In doing so, the second loop should only be run if swapped is true AND the currentIndex should only be decremented if swapped is still true

Which brings us to something like...

public void sortOnlyOneItem() {
    boolean swapped = true;
    int start = 0;
    int end = currentIndex;

    for (int i = start; i < end; ++i) {
        if (list[i] > list[i + 1]) {
            int temp = list[i];
            list[i] = list[i + 1];
            list[i + 1] = temp;
            swapped = true;
        }
    }

    if (swapped) {
        swapped = false;

        end = end - 1;

        for (int i = end; i >= start; i--) {
            if (list[i] > list[i + 1]) {
                int temp = list[i];
                list[i] = list[i + 1];
                list[i + 1] = temp;
                swapped = true;
            }
        }
    }

    if (swapped) {
        currentIndex--; //currentIndex is updated each time shaker sort runs
    }
}

Which still isn't quite right, as the two for-loops can make multiple changes.

Instead, we need a iteration which will only make, at most, two changes, one at the start and one at the end

Which, might, look something like...

protected void swap(int a, int b) {
    int tmp = list[a];
    list[a] = list[b];
    list[b] = tmp;
}

int endIndex = NUM_OF_ITEMS - 1;

//My shaker sort code
public void sortOnlyOneItem() {

    int startIndex = 0;
    while (startIndex < NUM_OF_ITEMS - 1 && list[startIndex] < list[startIndex + 1]) {
        startIndex++;
    }

    if (startIndex < NUM_OF_ITEMS - 1 && list[startIndex] > list[startIndex + 1]) {
        swap(startIndex, startIndex + 1);
        int end = endIndex;
        while (end > 0 && list[end - 1] < list[end]) {
            end--;
        }
        if (end > 0 && list[end - 1] > list[end]) {
            swap(end - 1, end);
        } else {
            endIndex--;
        }
    } else {
        endIndex = 0;
    }
}

Now, this basically looks for the two indices which might be changeable (at the start and end) and swaps them if possible.  When you can iterate from the start to the end without making a change, the sort is finished.

Now, I make no claims over if this is accurate or not, only that it does the best effort to mimic the algorithm you supplied


来源: stackexchange

问:
In Java, can the this/super keywords represent anything other than classes/enums?
I've noticed that:

```<code>class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}
</code>```

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?

答: Your initial assumption is wrong - this always represents the current instance, that is the instance of the current class, even if it's anonymous.

ContentLicense: CC BY-SA 2.5

Body:
I've noticed that:

class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?


答:
In this case the time reported by strace is a bit misleading.

strace(1) tells us:

-c Count time, calls, and errors for each system call and report a
  summary on program exit.  On Linux, this attempts to show system time
  (CPU time spent running in the kernel) independent of wall clock time.

But I suspect what it's actually counting is just the time from when epoll_wait was called until it returned. This doesn't mean your process was "running" in the kernel. It's far more likely it was sleeping, which is natural for epoll_wait.

ContentLicense: CC BY-SA 3.0

Title: epoll_wait() consume too much CPU

Body:
my epoll_wait() is consuming too much CPU, a simple strace shows that:

    strace -c -f -p 3655
    Process 3655 attached with 5 threads
    ^CProcess 3655 detached
    Process 3656 detached
    Process 3657 detached
    Process 3658 detached
    Process 3659 detached
    % time     seconds  usecs/call     calls    errors syscall
    ------ ----------- ----------- --------- --------- ----------------
     64.43   32.228205      596819        54           epoll_wait
     35.31   17.661939          17   1063312    195547 futex
      0.26    0.131803           0    448140           gettimeofday
      0.00    0.000090           3        27           write
      0.00    0.000050           1        54           epoll_ctl
      0.00    0.000000           0        54        27 read
      0.00    0.000000           0         9           sendmsg
      0.00    0.000000           0        90        54 recvmsg
    ------ ----------- ----------- --------- --------- ----------------
    100.00   50.022087               1511740    195628 total

there are just 54 epoll_wait() calls, but usecs/call of epoll_wait() is 596819, why?


问:
Javascript confirm offset on a touch screen
I have put together a kiosk consisting of a Raspberry pi 3 running Raspbian and a Hanns.G HT231HPB touch screen monitor to display a web page, because I don't want inadvertent submission I have locked a lot of the links down with Javascript confirm, these work, but the touch point is significantly offset to above the button which makes it difficult for the users. does anybody have any suggestions for controlling this better? </p>

答: As suspected this is the hardware and Raspbian failing to work well enough together. Set up the same screen with a mini PC running Windows 10 and Chrome, and eventually a PI 3 running Windows 10 IOT and the screens responsiveness improved exponentially. So the screen does support Raspbian, but only in a very primitive way and both the full and stripped down windows gave a better front end response on the touch screen.</p>


问:
Spring AOP: AopConfigException: Could not generate CGLIB subclass of class
Below is my LoggingAspect.java

```<code>import java.util.logging.Level;
import java.util.logging.Logger;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    private static Logger logger = Logger.getLogger(LoggingAspect.class.getName());
    private static final String ENTERING = "(AOP) Entering ";
    private static final String EXITING = "(AOP) Exiting ";
    private static final String RETURNING = "(AOP) Returning for class ";
    private static final String EXCEPTION = "(AOP): Exception ";

    @Pointcut("execution(* com.adminserver..*(..)) && " + "!within(is(EnumType)) && " + "!within(is(FinalType))")
    protected void loggingOperation() {
        // intentionally left blank
    }

    private String getArguments(Object[] obj) {
        String str = "{";
        for (int i = 0; i < obj.length && obj[i] != null; i++)
            str += obj[i].toString() + ",";
        str += "}";
        return str;
    }

    @Before("loggingOperation()")
    public void logEntry(final JoinPoint joinPoint) {
        String msg = ENTERING + joinPoint.getTarget().getClass().getName() + " " + joinPoint.getSignature().getName()
                + " Arguments: " + getArguments(joinPoint.getArgs());

        logger.log(Level.INFO, msg);

    }

    @After("loggingOperation()")
    public void logExit(final JoinPoint joinPoint) {
        logger.log(Level.INFO, EXITING + joinPoint.getTarget().getClass().getName() + " "
                + joinPoint.getSignature().getName() + " Arguments:" + getArguments(joinPoint.getArgs()));
    }

    @AfterReturning(pointcut = "loggingOperation()", returning = "result")
    public void logReturn(final JoinPoint joinPoint, Object result) {
        String msg = RETURNING + joinPoint.getTarget().getClass().getName() + ", Method: "
                + joinPoint.getSignature().getName() + " Return Value: ";
        if (result != null)
            logger.log(Level.INFO, msg + result.toString());
        else
            logger.log(Level.INFO, msg + "NULL");

    }

    @AfterThrowing(pointcut = "loggingOperation()", throwing = "ex")
    public void logException(JoinPoint joinPoint, Throwable ex) throws Throwable {
        String msg = EXCEPTION + joinPoint.getTarget().getClass().getName() + " " + joinPoint.getSignature().getName();
        logger.log(Level.SEVERE, msg, ex);
    }

}
</code>```

Tried with both of the below config (after searching for answers on SO):

<aop:aspectj-autoproxy proxy-target-class="true"/> and
<aop:aspectj-autoproxy proxy-target-class="false"/>

Application is running and it is working as expected for some part of the code. but for some of the other parts of the it is throwing something like this:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'onLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44': Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.adminserver.sre.bll.generatedClasses.OnLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44]: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
    at com.adminserver.utl.SpringBeanUtl.getBean(SpringBeanUtl.java:55)
    at com.adminserver.sre.helper.generator.OnLoadGenerator.generate(OnLoadGenerator.java:109)
    at com.adminserver.sre.helper.generator.OnLoadGenerator.getOnLoadProcessorBll(OnLoadGenerator.java:58)
    at com.adminserver.sre.helper.generator.OnLoadGenerator.getOnLoadProcessorBllForProcessing(OnLoadGenerator.java:35)
    at com.adminserver.sre.bll.ScreenEventBll.processLoad(ScreenEventBll.java:130)
    ... 124 more
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.adminserver.sre.bll.generatedClasses.OnLoadProcessor_PolicyOver+viewScreen_b155c215e3379a2caad2916f665ce44]: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205)
    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:469)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:349)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:298)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    ... 135 more
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:345)
    at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
    at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
    at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
    at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
    at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
    at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
    at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:55)
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:201)
    ... 142 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:459)
    at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
    ... 155 more
Caused by: java.lang.NoClassDefFoundError: com/adminserver/sre/bll/generatedClasses/OnLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    ... 160 more
Caused by: java.lang.ClassNotFoundException: com.adminserver.sre.bll.generatedClasses.OnLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    ... 162 more
</code>```

lib used:

```<code><dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
</dependency>
</code>```

As you can see I am excluding all the enum types and final classes by using

@Pointcut("execution(* com.adminserver..*(..)) && " + "!within(is(EnumType)) && " + "!within(is(FinalType))")

but in the log it still complains for Common causes of this problem include using a final class or a non-visible class;

答:
Added !within(com.adminserver..*.generatedClasses..*) in the pointcut expression and it worked.

Below is the complete expression.

```<code>@Pointcut("execution(public * com.adminserver..*(..)) && " + "!within(is(EnumType)) && " + "!within(is(FinalType)) && "+"!within(com.adminserver..*.generatedClasses..*)")
    protected void loggingOperation() {
        // intentionally left blank
    }
</code>```

Body:
Below is my LoggingAspect.java

import java.util.logging.Level;
import java.util.logging.Logger;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    private static Logger logger = Logger.getLogger(LoggingAspect.class.getName());
    private static final String ENTERING = "(AOP) Entering ";
    private static final String EXITING = "(AOP) Exiting ";
    private static final String RETURNING = "(AOP) Returning for class ";
    private static final String EXCEPTION = "(AOP): Exception ";

    @Pointcut("execution(* com.adminserver..*(..)) && " + "!within(is(EnumType)) && " + "!within(is(FinalType))")
    protected void loggingOperation() {
        // intentionally left blank
    }

    private String getArguments(Object[] obj) {
        String str = "{";
        for (int i = 0; i < obj.length && obj[i] != null; i++)
            str += obj[i].toString() + ",";
        str += "}";
        return str;
    }

    @Before("loggingOperation()")
    public void logEntry(final JoinPoint joinPoint) {
        String msg = ENTERING + joinPoint.getTarget().getClass().getName() + " " + joinPoint.getSignature().getName()
                + " Arguments: " + getArguments(joinPoint.getArgs());

        logger.log(Level.INFO, msg);

    }

    @After("loggingOperation()")
    public void logExit(final JoinPoint joinPoint) {
        logger.log(Level.INFO, EXITING + joinPoint.getTarget().getClass().getName() + " "
                + joinPoint.getSignature().getName() + " Arguments:" + getArguments(joinPoint.getArgs()));
    }

    @AfterReturning(pointcut = "loggingOperation()", returning = "result")
    public void logReturn(final JoinPoint joinPoint, Object result) {
        String msg = RETURNING + joinPoint.getTarget().getClass().getName() + ", Method: "
                + joinPoint.getSignature().getName() + " Return Value: ";
        if (result != null)
            logger.log(Level.INFO, msg + result.toString());
        else
            logger.log(Level.INFO, msg + "NULL");

    }

    @AfterThrowing(pointcut = "loggingOperation()", throwing = "ex")
    public void logException(JoinPoint joinPoint, Throwable ex) throws Throwable {
        String msg = EXCEPTION + joinPoint.getTarget().getClass().getName() + " " + joinPoint.getSignature().getName();
        logger.log(Level.SEVERE, msg, ex);
    }

}

Tried with both of the below config (after searching for answers on SO):

<aop:aspectj-autoproxy proxy-target-class="true"/> and
<aop:aspectj-autoproxy proxy-target-class="false"/>

Application is running and it is working as expected for some part of the code. but for some of the other parts of the it is throwing something like this:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'onLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44': Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.adminserver.sre.bll.generatedClasses.OnLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44]: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
    at com.adminserver.utl.SpringBeanUtl.getBean(SpringBeanUtl.java:55)
    at com.adminserver.sre.helper.generator.OnLoadGenerator.generate(OnLoadGenerator.java:109)
    at com.adminserver.sre.helper.generator.OnLoadGenerator.getOnLoadProcessorBll(OnLoadGenerator.java:58)
    at com.adminserver.sre.helper.generator.OnLoadGenerator.getOnLoadProcessorBllForProcessing(OnLoadGenerator.java:35)
    at com.adminserver.sre.bll.ScreenEventBll.processLoad(ScreenEventBll.java:130)
    ... 124 more
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.adminserver.sre.bll.generatedClasses.OnLoadProcessor_PolicyOver+viewScreen_b155c215e3379a2caad2916f665ce44]: Common causes of this problem include using a final class or a non-visible class; nested exception is org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205)
    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:469)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:349)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:298)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    ... 135 more
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:345)
    at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
    at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
    at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
    at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
    at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
    at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
    at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
    at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:55)
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:201)
    ... 142 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:459)
    at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
    ... 155 more
Caused by: java.lang.NoClassDefFoundError: com/adminserver/sre/bll/generatedClasses/OnLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    ... 160 more
Caused by: java.lang.ClassNotFoundException: com.adminserver.sre.bll.generatedClasses.OnLoadProcessor_PolicyOverviewScreen_b155c215e3379a2caad2916f665ce44
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    ... 162 more

lib used:

<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
</dependency>

As you can see I am excluding all the enum types and final classes by using

@Pointcut("execution(* com.adminserver..*(..)) && " + "!within(is(EnumType)) && " + "!within(is(FinalType))")

but in the log it still complains for Common causes of this problem include using a final class or a non-visible class;

Body:
Added !within(com.adminserver..*.generatedClasses..*) in the pointcut expression and it worked.

Below is the complete expression.

@Pointcut("execution(public * com.adminserver..*(..)) && " + "!within(is(EnumType)) && " + "!within(is(FinalType)) && "+"!within(com.adminserver..*.generatedClasses..*)")
    protected void loggingOperation() {
        // intentionally left blank
    }


问:
iOS 11 UIWebView JavaScript Pop-up Issues
I have an issue with updating an app for use with iOS 11. I have the native app, which uses a UIWebView to show a GWT JS application.

However, pop-ups are not working in this app for iOS 11. They can open, a value can be selected, and then they will save the value and close, but then they will reopen exactly as they were prior to closing, and this will continue. If I have 2 drop downs, then the first will have the issue described above, but if I then open a second I will see the values from the first drop-down until I have clicked somewhere else on the screen to close it.

The second time the drop-down comes up it does not automatically close on selection, but does seem to change the value. Additionally, if I close the drop-down without having anything selected then it will pop-up with the same number of items in the list, but all blank, as though the initial pop-up is somehow feeding values into the second pop-up.

I have eliminated the possibility that it is solely a code issue, as the same exact native and web code has the pop-ups working as intended on iOS 11.

I would appreciate any advice on how to deal with this, either because you have experienced this issue yourselves or even just in general issue debugging hints for iOS 11, as this is relatively new to me.

Thanks.

答: This is an ios issue with UIWebView, as mentioned in the previous answer. Replacing this with WKWebView will help to fix this. For anyone who is not able to replace to WKWebView, this issue is fixed in xcode 9.2 beta-2 version. So you can build your app with xcode 9.2 beta-2 (hopefully the stable version will have this fix as well), and try testing in ios 11.2. </p>


问:
Grails Issue Dealing With Tcp Client & Tcp Server
I created a Tcp Client & Tcp Server in Groovy awhile back and had no issues with it. I was only connecting to one machine at the time to gather data. This time I am attempting to connect to the script on multiple hosts and it is only saving one of the hosts information in my grails app.

My Grails application is simple, it has a domain class for Machines (basically the computers and the information on them that I seek) and it will use my TcpClient.groovy script to connect and gather information from the TcpServer.groovy on the other computers. For each host, it should save the information gathered, however, it seems to skip right over saving any host aside from the last one.

Tcp Client :

```<code>//TCP CLIENT

public void queryData(def hosts) {

 for(int aHost = 0; aHost < hosts.size; aHost++) {
         cristalClient(hosts[aHost]);
 }
}

public void cristalClient(String host) {

 commands = ["dateScan", "computerName", "ip", "quit"]

 answers = [commands.size]

 requestSocket = new Socket(host, 2000)

 r = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
 w = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()));

 String message = "Connection was successful"

 message = readAvailable(r)
 println("Sever>" + message)

 for(int n = 0; n < commands.size; n++) {
     sendMessage(commands[n]);
 answers[n] = readAvailable(r)
 }

 lastRead = answers[0]
 machineName = answers[1]
 ipAddress = answers[3]

 w.flush()
 w.close()
}

public String readAvailable(r) {

    String out = ""
    String dum = null

    while((dum = r.readLine()) !=null) {
        if(dum == ">>EOF<<") return out
        if(out.length() > 0) out += "\r\n"
            out += dum
    }
    return out
}

public void sendMessage(msg) {
    w.write(msg+"\r\n");
    w.flush();
    println("Client>" + msg);
}

public void printData(abc) {

    abc.eachWithIndex { it, index ->
    println "Drive $index"
    it.each { k, v ->
        println "\t$k = $v"
    }
    }

}
</code>```

Tcp Server :

```<code>//TCP Server

def server = new ServerSocket(2000)

println("Waiting for connection")

    server.accept() { socket ->
        socket.withStreams { input, output ->

            w = new BufferedWriter(new OutputStreamWriter(output))

            String message = "Connection was successful"

            r = new BufferedReader(new InputStreamReader(input))

            while(true) {

                if(message != null) {
                    sendMessage(message)
                    message = null
                }

                String a = r.readLine()

                if(a == "dateScan") {
            message = new Date
        } else if(a == "computerName") {
            message = InetAddress.getLocalHost().hostName
        } else if(a == "ip") {
            message = InetAddress.getLocalHost().getHostAddress()
                } else if(a == "quit") {
                    server.close()
                    return
                } else {
                    message = "$a command unknown."
                    println message
                }
            }
        }
    }

def sendMessage(String msg) {
    println( "sending: >" + msg + "<" )
    w.writeLine(msg)
    w.writeLine(">>EOF<<")
    w.flush();
}
</code>```

Grails Controller :

```<code>//Grails Controller

CollectMachines {

    def w = new tcpClient()
    def hosts = ["winXp", "Win7"]

    w.queryData(hosts)
    def abc = w.hardDrive
    abc.each { println it }

    int numberOfDrives = abc.size()

    //add new machine
    numberOfDrives.times {

        def machineName = abc.computerName[it]
        def machineInstance = Machine.findByMachineName(machineName)

        if (!machineInstance) {
            machineInstance = new Machine(machineName)
        }

        def lastScan = abc.lastScan[it]
        def scanDate = new Date().parse("E MMM dd H:m:s z yyyy", lastScan)

        def ipAddress = abc.ipAddress[it]

        machineInstance.setIpAddress(ipAddress)
        machineInstance.setDateScanned(scanDate)
        machineInstance.save()

    }
    redirect(action: "list")
}
</code>```

Do I need to put a pause in so that the server has time to send a response? My Tcp Client does send out all the commands but only gets responses for the last set of commands.

Also, sorry for the indentation issues with my code snippets, I'm not sure why they are messed up.

.

答:
There are a few problems with your code.  tcpClient never assigns to hardDrive, for example.  Assuming this is an oversight, I think the real problem is that tcpClient is querying data for multiple hosts, and storing all the results in the same instance variables answers, and ultimately lastRead, machineName, and ipAddress.

You need to store the results for each host separately.  One way would be to have answers be a map of lists.  For example, answers[host][0] would be the first answer for a given host.

I don't think any kind of pause is necessary.

Body:
I created a Tcp Client & Tcp Server in Groovy awhile back and had no issues with it. I was only connecting to one machine at the time to gather data. This time I am attempting to connect to the script on multiple hosts and it is only saving one of the hosts information in my grails app.

My Grails application is simple, it has a domain class for Machines (basically the computers and the information on them that I seek) and it will use my TcpClient.groovy script to connect and gather information from the TcpServer.groovy on the other computers. For each host, it should save the information gathered, however, it seems to skip right over saving any host aside from the last one.

Tcp Client :

//TCP CLIENT

public void queryData(def hosts) {

 for(int aHost = 0; aHost < hosts.size; aHost++) {
         cristalClient(hosts[aHost]);
 }
}

public void cristalClient(String host) {

 commands = ["dateScan", "computerName", "ip", "quit"]

 answers = [commands.size]

 requestSocket = new Socket(host, 2000)

 r = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
 w = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()));

 String message = "Connection was successful"

 message = readAvailable(r)
 println("Sever>" + message)

 for(int n = 0; n < commands.size; n++) {
     sendMessage(commands[n]);
 answers[n] = readAvailable(r)
 }

 lastRead = answers[0]
 machineName = answers[1]
 ipAddress = answers[3]

 w.flush()
 w.close()
}

public String readAvailable(r) {

    String out = ""
    String dum = null

    while((dum = r.readLine()) !=null) {
        if(dum == ">>EOF<<") return out
        if(out.length() > 0) out += "\r\n"
            out += dum
    }
    return out
}

public void sendMessage(msg) {
    w.write(msg+"\r\n");
    w.flush();
    println("Client>" + msg);
}

public void printData(abc) {

    abc.eachWithIndex { it, index ->
    println "Drive $index"
    it.each { k, v ->
        println "\t$k = $v"
    }
    }

}

Tcp Server :

//TCP Server

def server = new ServerSocket(2000)

println("Waiting for connection")

    server.accept() { socket ->
        socket.withStreams { input, output ->

            w = new BufferedWriter(new OutputStreamWriter(output))

            String message = "Connection was successful"

            r = new BufferedReader(new InputStreamReader(input))

            while(true) {

                if(message != null) {
                    sendMessage(message)
                    message = null
                }

                String a = r.readLine()

                if(a == "dateScan") {
            message = new Date
        } else if(a == "computerName") {
            message = InetAddress.getLocalHost().hostName
        } else if(a == "ip") {
            message = InetAddress.getLocalHost().getHostAddress()
                } else if(a == "quit") {
                    server.close()
                    return
                } else {
                    message = "$a command unknown."
                    println message
                }
            }
        }
    }

def sendMessage(String msg) {
    println( "sending: >" + msg + "<" )
    w.writeLine(msg)
    w.writeLine(">>EOF<<")
    w.flush();
}

Grails Controller :

//Grails Controller

CollectMachines {

    def w = new tcpClient()
    def hosts = ["winXp", "Win7"]

    w.queryData(hosts)
    def abc = w.hardDrive
    abc.each { println it }

    int numberOfDrives = abc.size()

    //add new machine
    numberOfDrives.times {

        def machineName = abc.computerName[it]
        def machineInstance = Machine.findByMachineName(machineName)

        if (!machineInstance) {
            machineInstance = new Machine(machineName)
        }

        def lastScan = abc.lastScan[it]
        def scanDate = new Date().parse("E MMM dd H:m:s z yyyy", lastScan)

        def ipAddress = abc.ipAddress[it]

        machineInstance.setIpAddress(ipAddress)
        machineInstance.setDateScanned(scanDate)
        machineInstance.save()

    }
    redirect(action: "list")
}

Do I need to put a pause in so that the server has time to send a response? My Tcp Client does send out all the commands but only gets responses for the last set of commands.

Also, sorry for the indentation issues with my code snippets, I'm not sure why they are messed up.

.


问:
Android SDK Ubuntu default path
I am trying to build my Android app in Unity on Ubuntu, but cannot find Android SDK.
What is Android SDK default path on Ubuntu?

答: It should be in your home folder under Android/Sdkfolder, i.e., ~/Android/Sdk

Title: Android SDK Ubuntu default path


问:
Throw Not found instead of Trying to get property of non-object in Laravel
I have app URL 127.0.0.1:8000. Whatever I put after this URL, Laravel returns this error. For example: 127.0.01:8000/asfs or

Trying to get property of non-object

What I want is Laravel should return Not Found error instead of Trying to get property of.... Are there any better ways?

My Route

```<code>Route::get('/{url}', 'ViewController@view')->name('view')->where('url', '[\w\d\-]+(.*)');
Route::post('/login', 'Admin\AuthsController@login');
</code>```

View

```<code><p>
<img alt="Home" src="{{ asset('public/logo.png')}}"/>
</p>
</code>```

ViewController

```<code>public function view($url)
{
    $pr = Pr::where('url', $url)->first();

    return view ('show', compact('pr'));

}
</code>```

答:
This error is typical to trying to retrieve a data that is not available in the database. Ensure that whatever data you want to retrieve, be it a picture or any data at all has been persisted in the database.  Then try retrieving the data again.

You can try this

if ( $pr->ul){

return view ('show', compact('pr'));

}else{

    return view ('errors.404');

}```

Body:
I have app URL 127.0.0.1:8000. Whatever I put after this URL, Laravel returns this error. For example: 127.0.01:8000/asfs or

Trying to get property of non-object

What I want is Laravel should return Not Found error instead of Trying to get property of.... Are there any better ways?

My Route

Route::get('/{url}', 'ViewController@view')->name('view')->where('url', '[\w\d\-]+(.*)');
Route::post('/login', 'Admin\AuthsController@login');

View

ViewController

public function view($url)
{
    $pr = Pr::where('url', $url)->first();

    return view ('show', compact('pr'));

}


问:
Removing One String CSV elements from another CSV String in java
I am trying to remove elements from one CSV string with other CSV string :

Example:

```<code>String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */

String s2="e,5,v";` /*(input string) This elements has to remove from above string S1 */
</code>```

Expected Output String s1: "a,b,c,d,f,g,h,w,p,4,12,u";

I have Tried:  For loop and remove elements and append back String.

I can to this by no. of ways, but i want to know if there is any library/method/utility available ?

答:
Try StringUtil from Spring </p>

```<code>String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */
String s2="e,5,v";
System.out.println(StringUtils.deleteAny(s1, s2));
</code>```

Body:
I am trying to remove elements from one CSV string with other CSV string :

Example:

String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */

String s2="e,5,v";` /*(input string) This elements has to remove from above string S1 */

Expected Output String s1: "a,b,c,d,f,g,h,w,p,4,12,u";

I have Tried:  For loop and remove elements and append back String.

I can to this by no. of ways, but i want to know if there is any library/method/utility available ?

Body:
Try StringUtil from Spring

String s1= "a,b,c,d,e,f,g,h,w,p,4,5,12,u,v"; /* Base String */
String s2="e,5,v";
System.out.println(StringUtils.deleteAny(s1, s2));


问:
Changes don't propagate through the component
I have the following example of a component that toggles an element (div) when a button is clicked. The problem is that the first click does absolutely nothing: the changes don't propagate at all and it is needed a second click to achieve the desired behaviour.

```<code>import { Component } from '@angular/core';

var exec = require('child_process').exec; //electron part

@Component({
    selector: 'my-component',
    template: `

        <button (click)="showDiv()">Toggle Div</button>
        <div *ngIf="show" style="width: 50px; height: 50px; background-color: green">
        </div>

    `
})
export class MyComponent {

    private show = false;

    public showDiv() {

        exec("wmic logicaldisk get caption", function(error, stdout, stderr){
            console.log(stdout);
            this.show = !this.show;
        }.bind(this));

    }

}
</code>```

So the tricky part happens when I try to execute a Windows command prompt command, i.e. wmic logicaldisk get caption using electron packages and update the component after the command returns its values.

In a scenario where some files are being copied using electron (exec("copy a.txt dir", function(error, stdout, stderr){...})) and after the operation ends my component needs to be updated with some status (let's say: Files copied successfully!), this solution won't work.

SO what could be wrong in this approach?

答:
when we change anything out of angular, angular not take account of it. Try use ngZone (I don't know if work)</p>

```<code>export class MyComponent {
    private show = false;
    constructor(private ngZone:NgZone) //<--ID NgZone
    public showDiv() {
        exec("wmic logicaldisk get caption", function(error, stdout, stderr){
            console.log(stdout);
            this.ngZone.run(()=>{
              this.show = !this.show;
             });
        }.bind(this));
    }
}
</code>```

Body:
I have the following example of a component that toggles an element (div) when a button is clicked. The problem is that the first click does absolutely nothing: the changes don't propagate at all and it is needed a second click to achieve the desired behaviour.

import { Component } from '@angular/core';

var exec = require('child_process').exec; //electron part

@Component({
    selector: 'my-component',
    template: `

        <button (click)="showDiv()">Toggle Div</button>

    `
})
export class MyComponent {

    private show = false;

    public showDiv() {

        exec("wmic logicaldisk get caption", function(error, stdout, stderr){
            console.log(stdout);
            this.show = !this.show;
        }.bind(this));

    }

}

So the tricky part happens when I try to execute a Windows command prompt command, i.e. wmic logicaldisk get caption using electron packages and update the component after the command returns its values.

In a scenario where some files are being copied using electron (exec("copy a.txt dir", function(error, stdout, stderr){...})) and after the operation ends my component needs to be updated with some status (let's say: Files copied successfully!), this solution won't work.

SO what could be wrong in this approach?

Body:
when we change anything out of angular, angular not take account of it. Try use ngZone (I don't know if work)

export class MyComponent {
    private show = false;
    constructor(private ngZone:NgZone) //<--ID NgZone
    public showDiv() {
        exec("wmic logicaldisk get caption", function(error, stdout, stderr){
            console.log(stdout);
            this.ngZone.run(()=>{
              this.show = !this.show;
             });
        }.bind(this));
    }
}


问:
Progress bar overflow div
I'm doing progress bar I added div inside bar but at 0% and 100% value is overflow and while moving also looks like a doubt after reached the point then shows full width.

Expected output:

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);
        });
    }

    progressbar();
});
```

<pre class="lang-css prettyprint-override"><code>/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
    position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
}
.testimonial_block2 .percentage {
    display: flex;
    position: absolute;
    padding: 5px;
    top: 6px;
    right: 0;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}
</code>```

5 REVIEWS

4 REVIEWS

3 REVIEWS

2 REVIEWS

1 REVIEWS

```

答:
Adding overflow: visible !important; will fix this issue

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);
        });
    }

    progressbar();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
 position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
    overflow: visible !important;
}
.testimonial_block2 .percentage {
 display: flex;
 position: absolute;
    padding: 5px;
    top: 6px;
    right: -20px;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}</code>```

5 REVIEWS

4 REVIEWS

3 REVIEWS

2 REVIEWS

1 REVIEWS

```

Title: Progress bar overflow div

Body:
I'm doing progress bar I added div inside bar but at 0% and 100% value is overflow and while moving also looks like a doubt after reached the point then shows full width.

Expected output:

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);
        });
    }

    progressbar();
});

/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
    position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
}
.testimonial_block2 .percentage {
    display: flex;
    position: absolute;
    padding: 5px;
    top: 6px;
    right: 0;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}

5 REVIEWS

4 REVIEWS

3 REVIEWS

2 REVIEWS

1 REVIEWS

Body:
Adding overflow: visible !important; will fix this issue

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);
        });
    }

    progressbar();
});

/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
 position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
    overflow: visible !important;
}
.testimonial_block2 .percentage {
 display: flex;
 position: absolute;
    padding: 5px;
    top: 6px;
    right: -20px;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="testimonial_block2">

     <!-- progress bar -->

     <div class="iva_progress_bar">
      <div class="bar_title">5 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="0">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">4 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="100">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">3 REVIEWS</div>
      <div class="bar_wrap">
       <span  class="bar_color" data-width="3">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">2 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="6">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">1 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="11">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>
        </div>


问:
Not able to load servlet context in Spring
I'm trying to load the properties data on server startup. For this I have created a class that implements ServletContextListener. This will load all the properties.

And in my DaoImpl class, I'm trying to get the properties data and get initialized to some of the strings. But it throws the exception

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'bbService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bbService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BBDAO' defined in ServletContext resource [/WEB-INF/spring-web-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bb.dao.BBDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
</code>```

Here is my Config class

```<code>public class Config implements ServletContextListener {

private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();

@Override
public void contextInitialized(ServletContextEvent event){
    try {
        Resource resource = new ClassPathResource("/uat.properties");
        config = PropertiesLoaderUtils.loadProperties(resource);
    } catch (IOException e) {
        try {
            throw new QiibException("Loading config failed");
        } catch (QiibException e1) {
            e1.printStackTrace();
        }
    }
    event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}

@Override
public void contextDestroyed(ServletContextEvent event) {
}

public static Config getInstance(ServletContext context) {
    return (Config) context.getAttribute(ATTRIBUTE_NAME);
}

public String getProperty(String key) {
    return config.getProperty(key);
}
}
</code>```

The DAOImpl class is

```<code>public class BBDaoImpl extends JdbcDaoSupport implements BBDao, ServletContextAware  {

Properties properties = null;

@Autowired
private ServletContext ctx;

public void setServletContext(ServletContext servletContext) {
    this.ctx = servletContext;
}

public BBDaoImpl() throws IOException {
    super();
    Config config = Config.getInstance(ctx); --> ctx is null here.
</code>```

What is wrong here?

Any ideas would be greatly appreciated.

答:
If you look at your exception, you will find that there is nested exception in your service class where it is trying to autowired the dao bean which is still not initialized.

first look at your configuration:-
1. are you scanning your dao Repo.
2. if yes are putting any stereotype(@Component) in your Dao class.

please look on these you will find your solution in your exception itself.

Body:
I'm trying to load the properties data on server startup. For this I have created a class that implements ServletContextListener. This will load all the properties.

And in my DaoImpl class, I'm trying to get the properties data and get initialized to some of the strings. But it throws the exception

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'bbService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bbService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BBDAO' defined in ServletContext resource [/WEB-INF/spring-web-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bb.dao.BBDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException

Here is my Config class

public class Config implements ServletContextListener {

private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();

@Override
public void contextInitialized(ServletContextEvent event){
    try {
        Resource resource = new ClassPathResource("/uat.properties");
        config = PropertiesLoaderUtils.loadProperties(resource);
    } catch (IOException e) {
        try {
            throw new QiibException("Loading config failed");
        } catch (QiibException e1) {
            e1.printStackTrace();
        }
    }
    event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}

@Override
public void contextDestroyed(ServletContextEvent event) {
}

public static Config getInstance(ServletContext context) {
    return (Config) context.getAttribute(ATTRIBUTE_NAME);
}

public String getProperty(String key) {
    return config.getProperty(key);
}
}

The DAOImpl class is

public class BBDaoImpl extends JdbcDaoSupport implements BBDao, ServletContextAware  {

Properties properties = null;

@Autowired
private ServletContext ctx;

public void setServletContext(ServletContext servletContext) {
    this.ctx = servletContext;
}

public BBDaoImpl() throws IOException {
    super();
    Config config = Config.getInstance(ctx); --> ctx is null here.

What is wrong here?

Any ideas would be greatly appreciated.


问:
AngularJS HTML audio player
I'm creating a webpage using AngularJS. I am trying to play an audio file that is loaded when the page has finished loading.
This is the html code I'm using:

```<code><audio controls="controls">
     <source ng-src="{{audioFile}}" type="audio/mp3">
</audio>
</code>```

And this is my AngularJS file where the audio player doesn't play anything.

```<code>angular.module('MyApp')
    .controller('MyCtrl', ['$scope', '$routeParams', 'Quiz',
        function ($scope, $routeParams, Quiz) {
            $scope.quiz = Quiz.get({quizId: $routeParams.quizId}, function() {
                $scope.audioFile = "Link to some audioFile";
            });
        }
    ]);
</code>```

But it works in the below code when I skip the service:

```<code>angular.module('MyApp')
    .controller('MyCtrl', ['$scope', '$routeParams', 'Quiz',
        function ($scope, $routeParams, Quiz) {
             $scope.audioFile = "Link to some audioFile";
        }
    ]);
</code>```

Is there any way to make this work when waiting for the response from the service?

答:
This is a simple directive audio player on AngularJS. Easy to insert and use, hopefully help you.</p>

```<code><player-directive ng-controller="YourCtrl" playlist="{{Your.tracks}}"></player-directive>
</code>```

Title: AngularJS HTML audio player

Body:
I'm creating a webpage using AngularJS. I am trying to play an audio file that is loaded when the page has finished loading.
This is the html code I'm using:

<audio controls="controls">
     <source ng-src="{{audioFile}}" type="audio/mp3">
</audio>

And this is my AngularJS file where the audio player doesn't play anything.

angular.module('MyApp')
    .controller('MyCtrl', ['$scope', '$routeParams', 'Quiz',
        function ($scope, $routeParams, Quiz) {
            $scope.quiz = Quiz.get({quizId: $routeParams.quizId}, function() {
                $scope.audioFile = "Link to some audioFile";
            });
        }
    ]);

But it works in the below code when I skip the service:

angular.module('MyApp')
    .controller('MyCtrl', ['$scope', '$routeParams', 'Quiz',
        function ($scope, $routeParams, Quiz) {
             $scope.audioFile = "Link to some audioFile";
        }
    ]);

Is there any way to make this work when waiting for the response from the service?

Body:
This is a simple directive audio player on AngularJS. Easy to insert and use, hopefully help you.

<player-directive ng-controller="YourCtrl" playlist="{{Your.tracks}}"></player-directive>


问:
Application (service) self-upgrade?
I'm developing a .NET4-based application in C# which runs as a windows service.

I'd like this application to be able to upgrade itself when instructed to do so by a web-service that it connects to periodically.  Is there an accepted way to accomplish this?  Is it even possible?

The way I'm thinking of it is something like this:

The windows service (.exe) code downloads its replacement and supporting DLLs as a zip and extracts them to a temporary directory.  The zip also includes a small "upgrader" executable or script.

The service forks a child process to run the upgrader, passing the destination directory and any other required information on the command-line

The service shuts down

The upgrader process waits for the service to stop completely, then moves the necessary files (new .exe, DLLs) into the final installation directory, replacing the old file(s)

The upgrader restarts the windows service, which spawns the (upgraded) .exe and quits once it starts

Would this work?  You may detect from my terminology and approach that I'm from a UNIX background and not a windows background.  I've made this approach work on UNIX, but I have no idea what sort of windows gotchas may exist...

UPDATE: My main motivation for this question is around the technical feasibility of a self-updating .NET application (how to do an in-place replacement of .DLLs, etc).  As pointed out in the comments, there are a host of other considerations involved in implementing a feature like this, in particular security concerns around verifying the new software components being applied are in fact legitimate.  These are also important, but not specific to .NET or Windows (imo).  Comments on these areas are welcome of course, but they are not my primary concern at this time...

答: You ought to take a look at this from Phil Haack, hot of the presses from earlier this week. I don't think it's exactly what you're looking for, but it might save you some time. NuGet is good times in any case.</p>

Title: Application (service) self-upgrade?


问:
How to implement a mechanism for users to block abusive users using firebase with help of JSQMessagesViewController in swift 4
I have implemented one-to-one chat using "Firebase" with the help of "JSQMessagesViewController" in swift 4 and I have submitted my app to Appstore. But, app gets rejected and asking for "A mechanism for users to block abusive users".

So, how I can achieve this mechanism in swift 4. I am not able to implement it, any code/suggestions will more appreciate.

Thank you in advance.

答:
Ok there may be many solutions for this.But i am providing the procedure which i have used to achieve the block functionality.

1.You have create a key for user's each message(for example "status")

2.When user's are chatting send "0" in status

3.When user blocks other user send a message or blank message with status "1"

4.Here status "0" means user not blocked and status "1" means user blocked

5.When user is receiving message check if status is "1" do not load that message

Hope you got an idea.


问:
How to create a simple DataFrame with random values
I am trying to create a very simple DataFrame with for example 3 columns and 3 rows.

I would like to have something like this:

```<code>+------+---+-----+
|nameID|age| Code|
+------+---+-----+
|2123  | 80| 4553|
|65435 | 10| 5454|
+------+---+-----+
</code>```

How can I create that Dataframe in Scala (is an example).
I have the next program:

```<code>import org.apache.spark.sql._
import org.apache.spark.sql.types._

object ejemploApp extends App{

  val schema = StructType(List(
      StructField("name", LongType, true),
      StructField("pandas", LongType, true),
      StructField("id", LongType, true)))
}
val outputDF = sqlContext.createDataFrame(sc.emptyRDD, schema)
</code>```

First problem:
It is throwing error in the outputDF that cannot resolve symbol schema.

Second problem:
How can I add the random numbers to the DataFrame?

Body:
I am trying to create a very simple DataFrame with for example 3 columns and 3 rows.

I would like to have something like this:

+------+---+-----+
|nameID|age| Code|
+------+---+-----+
|2123  | 80| 4553|
|65435 | 10| 5454|
+------+---+-----+

How can I create that Dataframe in Scala (is an example).
I have the next program:

import org.apache.spark.sql._
import org.apache.spark.sql.types._

object ejemploApp extends App{

  val schema = StructType(List(
      StructField("name", LongType, true),
      StructField("pandas", LongType, true),
      StructField("id", LongType, true)))
}
val outputDF = sqlContext.createDataFrame(sc.emptyRDD, schema)

First problem:
It is throwing error in the outputDF that cannot resolve symbol schema.

Second problem:
How can I add the random numbers to the DataFrame?

Body:
I would do something like this:

val nRows = 10

import scala.util.Random

val df = (1 to nRows)
  .map(_ => (Random.nextLong,Random.nextLong,Random.nextLong))
  .toDF("nameID","age","Code")

+--------------------+--------------------+--------------------+
|              nameID|                 age|                Code|
+--------------------+--------------------+--------------------+
| 5805854653225159387|-1935762756694500432| 1365584391661863428|
| 4308593891267308529|-1117998169834014611|  366909655761037357|
|-6520321841013405169| 7356990033384276746| 8550003986994046206|
| 6170542655098268888| 1233932617279686622| 7981198094124185898|
|-1561157245868690538| 1971758588103543208| 6200768383342183492|
|-8160793384374349276|-6034724682920319632| 6217989507468659178|
| 4650572689743320451| 4798386671229558363|-4267909744532591495|
| 1769492191639599804| 7162442036876679637|-4756245365203453621|
| 6677455911726550485| 8804868511911711123|-1154102864413343257|
|-2910665375162165247|-7992219570728643493|-3903787317589941578|
+--------------------+--------------------+--------------------+

Of course, the age isn't very realistic, but you can change your random numbers as you wish (i.e. using scalas modulo function and absolute value), you could e.g.

val df = (1 to nRows)
  .map(id => (id.toLong,Math.abs(Random.nextLong % 100L),Random.nextLong))
  .toDF("nameID","age","Code")

+------+---+--------------------+
|nameID|age|                Code|
+------+---+--------------------+
|     1| 17| 7143235115334699492|
|     2| 83|-3863778506510275412|
|     3| 31|-3839786144396379186|
|     4| 40| 8057989112338559775|
|     5| 67| 7601061291211506255|
|     6| 71| 7393782421106239325|
|     7| 43|   28349510524075085|
|     8| 50|  539042255545625624|
|     9| 41|-8654000375112432924|
|    10| 82|-1300111870445007499|
+------+---+--------------------+

EDIT: make sure you have the implicits imported:

Spark 1.6:

import sqlContext.implicits._

Spark 2:

import sparkSession.implicits._


问:
Using Postman to perform Azure AD auth for Azure Functions
Problem: I'm trying to use Postman to get an valid Azure AD access token that I can then use to pass on a request to an Azure Function protected by Azure Active Directory (Easy Auth).

I've read / viewed numerous explanations on how to do this. CGillum's entire blog for example. Some of the best ones (that don't quite work for me) are:

https://blogs.msdn.microsoft.com/devkeydet/2016/03/22/using-postman-with-azure-ad/

https://youtu.be/ujzrq8Fg9Gc

Even a similar question that I posted: Authentication for Azure Functions

I've verified that my ClientID, secret, and callback are all correct. I've ensured I have (what I think are) the correct permissions to the app I registered in my directory. I've got back a valid Bearer tokens in both of the first two examples above. No matter what though, when I pass this token back in the Authorization header I get a message that states "You do not have permission to view this directory or page."

My hope at this point is that someone reading this will point out the obvious thing that I missed.

Thanks in advance

答:
We could use the following way to get the easy auth token easily.

1.Vist the following url from browser and input your creditial.

```<code>https://{yourfunctionAppName}.azurewebsites.net/.auth/login/aad
</code>```

2.After that we could get the easy auth token after decode the url.

3.Test it with Postman

Body:
We could use the following way to get the easy auth token easily.

1.Vist the following url from browser and input your creditial.

https://{yourfunctionAppName}.azurewebsites.net/.auth/login/aad

2.After that we could get the easy auth token after decode the url.

3.Test it with Postman


问:
ClassCastException on calling a dialogfragment from RecyclerView
I have a RecyclerView from which I am trying to call a dialogfragment but I am getting a class cast exception. I tried a lot of solutions on stack but it didn't help. Please help me.

```<code>    java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
12-04 14:08:52.495 6146-    6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.opentok.example.efflorescence.myaudiotranscription.AllCallsRecyclerAdapter.showTranscriptionDialog(AllCallsRecyclerAdapter.java:249)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.opentok.example.efflorescence.myaudiotranscription.AllCallsRecyclerAdapter$1$1.run(AllCallsRecyclerAdapter.java:210)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Handler.handleCallback(Handler.java:815)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:104)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Looper.loop(Looper.java:207)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5765)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
12-04 14:08:52.496 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

my adapter code onClick

```<code>public void showTranscriptionDialog() {
  try {
    FragmentManager fr = ((Activity) context).getFragmentManager();
    TranscriptionDialogFragment msgDialog = new TranscriptionDialogFragment();
    msgDialog.show(fr, "Dialog");
  }
    catch (Exception e) {
    e.printStackTrace();
    Log.e("error displaying dialog",e.getLocalizedMessage());
  }
}
</code>```

my fragment

```<code>public class TranscriptionDialogFragment extends DialogFragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_transcription, container, false);
    getDialog().setTitle("Simple Dialog");
    return rootView;
  }
}
</code>```

My Contructor in adapter:

```<code>public AllCallsRecyclerAdapter(List<AllCallsData> list, Context context) {
  this.mInflater = LayoutInflater.from(context);
  this.list = list;
  this.context = context;
  mydb = new DBHelper(context);
}
</code>```

答:
This is because you're trying to cast the Application context to activity in the following code:

```<code>FragmentManager fr = ((Activity) context).getFragmentManager();
</code>```

which is an error.

You need to make sure the context is an activity not an application.

Body:
I have a RecyclerView from which I am trying to call a dialogfragment but I am getting a class cast exception. I tried a lot of solutions on stack but it didn't help. Please help me.

    java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
12-04 14:08:52.495 6146-    6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.opentok.example.efflorescence.myaudiotranscription.AllCallsRecyclerAdapter.showTranscriptionDialog(AllCallsRecyclerAdapter.java:249)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.opentok.example.efflorescence.myaudiotranscription.AllCallsRecyclerAdapter$1$1.run(AllCallsRecyclerAdapter.java:210)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Handler.handleCallback(Handler.java:815)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:104)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Looper.loop(Looper.java:207)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5765)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
12-04 14:08:52.496 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

my adapter code onClick

public void showTranscriptionDialog() {
  try {
    FragmentManager fr = ((Activity) context).getFragmentManager();
    TranscriptionDialogFragment msgDialog = new TranscriptionDialogFragment();
    msgDialog.show(fr, "Dialog");
  }
    catch (Exception e) {
    e.printStackTrace();
    Log.e("error displaying dialog",e.getLocalizedMessage());
  }
}

my fragment

public class TranscriptionDialogFragment extends DialogFragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_transcription, container, false);
    getDialog().setTitle("Simple Dialog");
    return rootView;
  }
}

My Contructor in adapter:

public AllCallsRecyclerAdapter(List<AllCallsData> list, Context context) {
  this.mInflater = LayoutInflater.from(context);
  this.list = list;
  this.context = context;
  mydb = new DBHelper(context);
}

Body:
This is because you're trying to cast the Application context to activity in the following code:

FragmentManager fr = ((Activity) context).getFragmentManager();

which is an error.

You need to make sure the context is an activity not an application.