text:
Q: Add new (shorter) column to tibble and expand tibble to remain tidy I have a dataframe and I need to add a column to include 3 species that correspond to each row of the existing dataframe. Hopefully the example below makes it clear:
Site    Year    Trt
A       2016    bowl
A       2016    vane
A       2017    target
A       2017    stick
B       2016    bowl
B       2016    vane
B       2017    target
B       2017    stick

species<-c("species1", "species2", "species3")

Then I want to get to
Site    Year    Trt     Species
A       2016    bowl    species1
A       2016    vane    species1
A       2017    target  species1
A       2017    stick   species1
A       2016    bowl    species2
A       2016    vane    species2
A       2017    target  species2
A       2017    stick   species2
A       2016    bowl    species3
A       2016    vane    species3
A       2017    target  species3
A       2017    stick   species3
B       2016    bowl    species1
B       2016    vane    species1
B       2017    target  species1
B       2017    stick   species1
B       2016    bowl    species2
B       2016    vane    species2
B       2017    target  species2
B       2017    stick   species2
B       2016    bowl    species3
B       2016    vane    species3
B       2017    target  species3
B       2017    stick   species3

I guess some rep methods would be okay, but the real dataset has two additional columns and 141 species. I get paranoid about everything matching up right.

A: What about using tidyr::expand to expand the data as:
library(tidyverse)
expand(data, nesting(Site, Year, Trt), species) %>% as.data.frame()

#     Site Year    Trt  species
# 1     A 2016   bowl species1
# 2     A 2016   bowl species2
# 3     A 2016   bowl species3
# 4     A 2016   vane species1
# 5     A 2016   vane species2
# 6     A 2016   vane species3
# 7     A 2017  stick species1
# 8     A 2017  stick species2
# 9     A 2017  stick species3
# 10    A 2017 target species1
# 11    A 2017 target species2
# 12    A 2017 target species3
# 13    B 2016   bowl species1
# 14    B 2016   bowl species2
# 15    B 2016   bowl species3
# 16    B 2016   vane species1
# 17    B 2016   vane species2
# 18    B 2016   vane species3
# 19    B 2017  stick species1
# 20    B 2017  stick species2
# 21    B 2017  stick species3
# 22    B 2017 target species1
# 23    B 2017 target species2
# 24    B 2017 target species3

Data
data <- read.table(text =
"Site    Year    Trt
A       2016    bowl
A       2016    vane
A       2017    target
A       2017    stick
B       2016    bowl
B       2016    vane
B       2017    target
B       2017    stick",
header = TRUE, stringsAsFactors = FALSE)

species<-c("species1", "species2", "species3")

A: A base R solution leveraging rep method:
transform(
    do.call('rbind', rep(list(df), length(species))),
    Species = rep(species, each=nrow(df))
)

#   Site Year    Trt  Species
#1     A 2016   bowl species1
#2     A 2016   vane species1
#3     A 2017 target species1
#4     A 2017  stick species1
#5     B 2016   bowl species1
#6     B 2016   vane species1
#7     B 2017 target species1
#8     B 2017  stick species1
#9     A 2016   bowl species2
#10    A 2016   vane species2
#11    A 2017 target species2
#12    A 2017  stick species2
#13    B 2016   bowl species2
#14    B 2016   vane species2
#15    B 2017 target species2
#16    B 2017  stick species2
#17    A 2016   bowl species3
#18    A 2016   vane species3
#19    A 2017 target species3
#20    A 2017  stick species3
#21    B 2016   bowl species3
#22    B 2016   vane species3
#23    B 2017 target species3
#24    B 2017  stick species3

A: Another base-R solution would be this (you can later sort based on Site column):
cbind(dat, Species = rep(species, each = nrow(dat)))

#    Site Year    Trt  Species
# 1     A 2016   bowl species1
# 2     A 2016   vane species1
# 3     A 2017 target species1
# 4     A 2017  stick species1
# 5     B 2016   bowl species1
# 6     B 2016   vane species1
# 7     B 2017 target species1
# 8     B 2017  stick species1
# 9     A 2016   bowl species2
# 10    A 2016   vane species2
# 11    A 2017 target species2
# 12    A 2017  stick species2
# 13    B 2016   bowl species2
# 14    B 2016   vane species2
# 15    B 2017 target species2
# 16    B 2017  stick species2
# 17    A 2016   bowl species3
# 18    A 2016   vane species3
# 19    A 2017 target species3
# 20    A 2017  stick species3
# 21    B 2016   bowl species3
# 22    B 2016   vane species3
# 23    B 2017 target species3
# 24    B 2017  stick species3


text:
Q: Prompt auto message when 'zero' as input in win32 code I have tried tooltip feature in win32 code, when 'OK' clicked the message displays only when we hover on particular box. But the feature Iam expecting is auto display of message at particular box when 'OK' is clicked. Is it possible to add such feature of auto popup? I need some balloon type of error popup.
My exact scenario is to error popup when Zero is given as input in a dialog, when 'OK' is clicked.
HWND gzui_controls::create_tool_tip_balloon(HWND hdlg, int tool_id, PTSTR text) const { if (!tool_id || !hdlg || !text) { return FALSE; }

HWND hwndTool = GetDlgItem(hdlg, tool_id);
if (WM_LBUTTONUP)
{
HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL,
        WS_POPUP | SWP_NOMOVE | TTS_NOPREFIX | TTS_BALLOON | BS_PUSHBUTTON,
        CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT,
        hdlg, NULL,
        getModuleInstance(), NULL);

    if (!hwndTool || !hwndTip)
    {
        return (HWND)NULL;
    }

    // Associate the tooltip with the tool.
    TOOLINFO toolInfo = { 0 };
    toolInfo.cbSize = sizeof(toolInfo);
    toolInfo.hwnd = hdlg;
    toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
    toolInfo.uId = (UINT_PTR)hwndTool;
    toolInfo.lpszText = text;
    SendMessage(hwndTip, TTM_ADDTOOL, 0, (LPARAM)&toolInfo);
    return hwndTip;
}

A: The following is an example of balloon tip for display information when input value is not valid.
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

// ...

   editHwnd = CreateWindow(L"EDIT",
       NULL,
       WS_VISIBLE | WS_CHILD | ES_MULTILINE | WS_BORDER,
       120,
       10,
       100,
       100,
       hWnd,
       NULL,
       hInst,
       NULL);

// ...

case WM_COMMAND:
    {
        if (HIWORD(wParam) == EN_CHANGE)
        {
            // TODO: Add logic of detecting input value here
            if (editHwnd == (HWND)lParam) // && inputVal == 0
            {
                balloonTip.cbStruct = sizeof(EDITBALLOONTIP);
                balloonTip.pszText = L"Zero is given as input";
                balloonTip.pszTitle = L"Tips";
                balloonTip.ttiIcon = TTI_INFO;
                Edit_ShowBalloonTip(editHwnd, &balloonTip);
            }
        }
    }
    break;

Refer to Edit Control, EDITBALLOONTIP structure, Edit_ShowBalloonTip macro

Note  To use Edit_ShowBalloonTip macro, you must provide a manifest specifying
  Comclt32.dll version 6.0.

It will like this:

redpajama_set_name: RedPajamaStackExchange


text:
Q: ClamAv + Microsoft Azure VM: Cannot connect to daemon from other VM I got two VMs on Azure that are in the same subnet. One VM (10.1.0.6) has clamav daemon running, the other runs a Java Wildfly Application (10.1.0.5).
I would like to send files from Java Application to the clam av daemon.
I checked that Clamav is running and listening on port 3310:
 netstat -ant|grep 3310
 tcp        0      0 127.0.0.1:3310          0.0.0.0:*               LISTEN

 netstat -lnp | grep clam
 (Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
 unix  2      [ ACC ]     STREAM     LISTENING     800631   -
 /var/run/clamav/clamd.ctl

For the Clam Av server there are all inbound ports open within the virtual private network. However, if I check on the java server if the port is available via telnet or nc I get:
telnet 10.1.0.6 3310
Trying 10.1.0.6...
telnet: Unable to connect to remote host: Connection refused

nc -vz 10.1.0.6 3310
nc: connect to 10.1.0.6 port 3310 (tcp) failed: Connection refused

If I send files via Java Application I get the same error.
Is my clamav setup correctly and is this issue related to my Subnet configuration?
Thanks for your help!

A: The problem was that the daemon was listening on the loopback IP address (127.0.0.1). I had to switch this is to listen on 10.1.0.6 (0.0.0.0 should also work).
added in /etc/clamav/clamd.conf:
TCPSocket 3310
TCPAddr 10.1.0.6

added in /etc/systemd/system/clamav-daemon.service.d/extend.conf
ListenStream=10.1.0.6:3310

Restarted the daemon and now it is working!


text:
Q: Framework for communicating between iOS and MacOS I'm looking to build a pair of apps that work in a similar way to iTunes and the Remote app for iOS... Is there a framework for connecting iOS and MacOS over wifi?
Bluetooth is something I'd like to avoid and there's no need for a web service, I'm just looking to control my Mac app remotely from the phone.
Thanks in advance.

A: Id say the most ideal way to accomplish this is via the Bonjour protocol.
Here is a great article on the subject, http://mobileorchard.com/tutorial-networking-and-bonjour-on-iphone/.
Good thing with using Bonjour in iOS is it also works via Bluetooth.
Hope this helps !
here is an example project  which exchange the data between iphone and iMAC with WiFi connectivity.
https://github.com/boobalaninfo/Bonjour-iOS-MAC-Apps
Use bonjour to search for devices. Then use CocoaAsyncSocket to send and receive data. It works like a charm.
Little info about AsyncSock:

GCDAsyncSocket and AsyncSocket are TCP/IP socket networking libraries.
  Here are the key features available in both:
Native objective-c, fully self-contained in one class. No need to muck
  around with sockets or streams. This class handles everything for you.
Full delegate support Errors, connections, read completions, write
  completions, progress, and disconnections all result in a call to your
  delegate method.
Queued non-blocking reads and writes, with optional timeouts. You tell
  it what to read or write, and it handles everything for you. Queueing,
  buffering, and searching for termination sequences within the stream -
  all handled for you automatically.
Automatic socket acceptance. Spin up a server socket, tell it to
  accept connections, and it will call you with new instances of itself
  for each connection.
Support for TCP streams over IPv4 and IPv6. Automatically connect to
  IPv4 or IPv6 hosts. Automatically accept incoming connections over
  both IPv4 and IPv6 with a single instance of this class. No more
  worrying about multiple sockets.
Support for TLS / SSL Secure your socket with ease using just a single
  method call. Available for both client and server sockets.


text:
Q: Zoomed UIImage inside ScrollView inside CollectionViewCell My goal is to create app like Apple Photos app - show photos, allow to zoom, scroll from horizontally, etc...
I am currently stuck at allowing to zoom photo in collectionViewCell.
What I've done: I have collectionView with scrollView inside collectionViewCell. This is how I create UIImageView inside In CollectionViewController in cellForItemAtIndexPath:
    let imageView: UIImageView!
    let someImage = UIImage(named: "someImage")
    imageView = UIImageView(image: someImage)
    imageView.frame = CGRect(origin: CGPointMake(0.0, 0.0), size:someImage.size)

    cell.scrollView.addSubview(imageView)
    cell.scrollView.contentSize = someImage.size

    let scrollViewFrame = cell.scrollView.frame
    let scaleWidth = scrollViewFrame.size.width / cell.scrollView.contentSize.width
    let scaleHeight = scrollViewFrame.size.height / cell.scrollView.contentSize.height
    let minScale = min(scaleWidth, scaleHeight);
    cell.scrollView.minimumZoomScale = minScale;

    cell.scrollView.maximumZoomScale = 1.0
    cell.scrollView.zoomScale = minScale;

    centerScrollViewContents(cell.scrollView, imageView: imageView)

(I found this code on Ray Wenderlich)
Next thing I need to add this code, so that zooming would work properly:
func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
    return imageView
}

func scrollViewDidZoom(scrollView: UIScrollView!) {
    let boundsSize = scrollView.bounds.size
    var contentsFrame = imageView.frame

    if contentsFrame.size.width < boundsSize.width {
        contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
    } else {
        contentsFrame.origin.x = 0.0
    }

    if contentsFrame.size.height < boundsSize.height {
        contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
    } else {
        contentsFrame.origin.y = 0.0
    }

    imageView.frame = contentsFrame
}

The thing is, my IBAOutlet for scrollView is inside CollectionViewCell, not CollectionViewController, so those two functions have to be called from CollectionViewCell, but I don't know how to access imageView for viewForZoomingInScrollView. Maybe my whole approach is wrong?

A: Create UICollectionViewCell subclass with xib
Subclassing UICollectionViewCell and initialising from xib
or without xib
http://randexdev.com/2014/08/uicollectionviewcell/
then set delegate for scrollView is collectionViewCell subclass
Add UIScrollViewDelegate code to cell
You can access imageView from cell property


text:
Q: Apache Camel stax2 NoSuchMethodError I'm getting very weird behavior from the Apache Camel application. I'm deploying the EAR on WebLogic 12.2.1.3 server on our test environment, and everything works fine. The EAR contains all the dependencies used by the application.
However, when I deploy the same EAR to production (it deploys fine), it gives the following runtime exception during message handling:
Exception occurred during execution on the exchange: Exchange[ID-napoli-34361-1518770862962-0-99], StackTrace: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[ID-napoli-34361-1518770862962-0-99]
    at org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1790)
    at org.apache.camel.impl.DefaultExchange.setException(DefaultExchange.java:350)
    at org.apache.camel.component.cxf.CxfProducer.process(CxfProducer.java:141)
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
    at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
    at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:541)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:198)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:198)
    at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:97)
    at org.apache.camel.component.cxf.CxfConsumer$CxfConsumerInvoker.syncInvoke(CxfConsumer.java:220)
    at org.apache.camel.component.cxf.CxfConsumer$CxfConsumerInvoker.invoke(CxfConsumer.java:147)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor$2.run(ServiceInvokerInterceptor.java:126)
    at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:131)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
    at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267)
    at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
    at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:191)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:301)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:220)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:276)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:286)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:260)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:137)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:350)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:247)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3697)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3667)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
    at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:197)
    at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
    at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
    at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2443)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2291)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2269)
    at weblogic.servlet.internal.ServletRequestImpl.runInternal(ServletRequestImpl.java:1703)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1663)
    at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:272)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:352)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:337)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:57)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:644)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:415)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:355)
Caused by: java.lang.NoSuchMethodError: org.codehaus.stax2.ri.EmptyIterator.getInstance()Lorg/codehaus/stax2/ri/EmptyIterator;
    at com.ctc.wstx.sw.OutputElementBase.getPrefixes(OutputElementBase.java:358)
    at org.apache.cxf.staxutils.StaxUtils.writeStartElement(StaxUtils.java:811)
    at org.apache.cxf.staxutils.StaxUtils.copy(StaxUtils.java:758)
    at org.apache.cxf.staxutils.StaxUtils.copy(StaxUtils.java:722)
    at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:214)
    at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:174)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
    at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:516)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:418)
    at org.apache.camel.component.cxf.CxfProducer.process(CxfProducer.java:133)
    ... 51 more
, Out: null: ]

The camel route success all the way to the cxf component, which tries to call external web service, failing for some reason and causing the exception.
It's the same package with same dependencies on both environments, and in the production environment weblogic I can not see any external libraries installed, which could conflict with the EAR package. So, how do I trace what is causing the problem?

A: This seems to be a compatibility issue between Stax and Woodstox.
See this issue and try to fix your dependencies:
https://github.com/FasterXML/woodstox/issues/10

A: The problem was weblogic providing the following library
oracle_common/modules/org.codehaus.woodstox.stax2-api.jar

The different version of same library was also packaged within the EAR. The problem was solved by setting prefer-application-packages in the deployment descriptor.
It is still unknown, why the application worked in our environment without the prefer-application-packages attribute. Shouldn't it have loaded the weblogic-one in our environment too? What causes the seemingly random behavior in this case?


text:
Q: The x command does not correctly when invoked under SASWorkspaceManager.WorkspaceManager? I have written some SAS code that calls R via the x command (I am using SAS 9.1.3 so there is no native SAS interface to R).
OPTIONS XWAIT XSYNC;
 X """&r_path."" --no-save --quiet < ""&out_code_folder.\code.r"" > ""&out_code_folder.\abba.log""";

This code works correctly when I run it in the SAS IDE but when I try to run the same code in VBA using (here strSAScode contains the above mentioned SAS code).
   Dim obWM As SASWorkspaceManager.WorkspaceManager
    Dim temp_dispaly_alert As Boolean
    Dim sm As SAS_Management
    Debug.Print strSASCode
    Set sm = New SAS_Management

    'Set obServerDef = New SASWorkspaceManagerServerDef
    Set obWM = New SASWorkspaceManager.WorkspaceManager
    Set obSAS = obWM.Workspaces.CreateWorkspaceByServer("MyServerName", VisibilityProcess, Nothing, "", "", "")
    Set sm.obLS = obSAS.LanguageService
    temp_dispaly_alert = Application.DisplayAlerts
    Application.DisplayAlerts = False
    sm.obLS.Submit strSASCode

Now every other code works, except the x command. Please Help.

A: By default, use of SYSTEM and X commands is disabled when accessed via techniques that use integration technologies due to potential security risks.
Have you followed the steps for 9.1.3 on Windows described in this usage note?
It describes how to enable this functionality on your SAS server; you may need to adapt what's described for the workspace, instead of the stored process, server.


text:
Q: LaTeX - Using commands inside inline code I want to be able to have inline code (printed in typewriter or something) where I can also use LaTeX commands like \myinlinecode{here comes a backslash: <\textbackslash>}. So it should be possible to use non-verbatim parts inside the code command.
I read that it should be possible with the listings package but I could't get it to work. What I tried was:
\documentclass{article}

\usepackage{listings}

\begin{document}

\lstset{escapebegin=x, escapeend=y}
\lstinline|x\textbraceleft y|

\lstset{escapebegin={x}, escapeend={y}}
\lstinline_x\textbraceleft y_

\lstset{escapebegin={\textbackslash}, escapeend={\textbackslash}}
\lstinline_\\textbraceleft \_

\end{document}

A: The following syntax makes it easier to use "escaped" (or LaTeX) content within \lstinline, and might be what you're after. There seems to be no particular need to use specially-assigned characters (like x and y) and the usual mathescape option works (escaping between $...$):

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\lstset{mathescape,basicstyle=\ttfamily}% Allow escaping to LaTeX inside $..$
\begin{document}

\lstinline|x$\lbrace$y|

\lstinline_x$\mbox{\textbraceleft}$y_

\lstinline!x{$\partial$}y!
\end{document}


text:
Q: Jquery UI Autocomplete not working after dom manipluation I have been trying to implement the autocomplete and have come across a problem that has stumped me.  The first time I call .autocomplete it all works fine and I have no problems. If, however, I call it after I have removed some (unrelated) elements from the DOM and added a new section to the DOM then autocomplete does nothing and reports no errors.
Code:-
$.ajax({
    type : 'get',
    dataType : 'json',
    url : '/finance/occupations',
    cache:true,
    success:function(data){
        occupationList = data;
        $('.js-occupation').autocomplete({
            source: occupationList,
            messages: {
                noResults: '',
                results: function(){}
            },
            minLength : 2,
            select:function(event, ui){
                $('.js-occupationId').val(ui.item.id);
            }
        });
    }
});

The background to this page is that it contains multiple sections that are manipulated as the user moves through them.  Hide and show works fine and does not impact on the autocomplete.  However, if I do the following:-
          var section = $('.js-addressForm:last').clone();
          clearForm(section);
          $('div.addressDetails').append(section);
          $('.js-addressForm:first').remove();

Which gives the user the bility to add multiple addresses on the previous section then the autocomplete stops working.
Any suggestions or pointers on something obvious I am missing?
I have tried to put the initialisation of the autocomplete on an event when the element gets focus and it still does not work.

A: You have to create the autocomplete after all other underlying objects.  If you F12, you will see that the list is "visible", however it is below and hidden by all instances created after it.
If you created a div with inputs (one input being the autocomplete), then you create the automplete then the dialog instances, the autocomplete will never show.  If you create the dialog then the autocomplete, no problem.  The problem is the z-order

A: I have faced the same issue. For now to fix this, i'm creating widget on the input once input is in focus. It will help you solve the issue.
You can look for the help on
making sure some event bing only when needed
Sample code will look like this
$( "#target" ).focus(function() {
  //I don't care if you manipulated the DOM or not. I'll be cautious. ;)

   (function() {
  $( "#combobox" ).combobox();
    $( "#toggle" ).click(function() {
      $( "#combobox" ).toggle();
    });
   })();

  // use a flag variable if you want
});

This solved my problem. Hope its the solution you were looking f


text:
Q: Trouble installing signed driver after installing unsigned driver I have many clients that use com0com which is a virtual port driver on 64 bit systems.  There are a few versions of this driver but only one older one that is signed.
Now if you use the versions I suggest then it installs with no problem.  Driver is signed as it should be.  However, if you first install an unsigned version of the driver (in other words you didn't read the manual!!), then of course it doesn't get installed.  However, from that point on, the good ones with signing can never be installed.  The installation then says that the drivers are not signed.
It seems nothing can be done to rectify this.
Any ideas?
Thanks

A: Ok, Solved...Windows kept picking the old driver.  Deleting it in the Device Manager fixed it.


text:
Q: Anaconda "> was unexpected at this time" I downloaded Anaconda3 not too long ago and today when I tried to run the Anaconda Prompt program (Windows 64 bit system) it gave me the following output:
>was unexpected at this time
>IF DEFINED PYTHONIOENCODING chcp > NUL

Then it's only on the regular command line terminal.
It has not done this before today and I don't really know what is going on. I am new with anaconda and command line prompts in general.
I've found a few articles referring to the first line, but none that tell me anything about the second. Any help would be great.

A: I solved it by uninstalling and reinstalling anaconda. Painful and time-consuming, but it worked.

A: I solved it by doing that as well but I have to do it every few days before it comes back again.

A: I tried reinstalling anaconda, but to no avail. The same error kept recurring. It basically comes from line 40 in the file conda.bat located in anaconda3\Library\bin\
@IF DEFINED PYTHONIOENCODING chcp %PYTHONIOENCODING% > NUL

I tried modifying this line line in numerous ways, but nothing worked.
However, there is a small hack that did. Open command prompt (or even the Anaconda Prompt) cd into the directory anaconda3\Scripts\. The command conda works here. Typing activate should run the batch file and activate the default 'base' environment.
Alternatively, just type anaconda3\Scripts\activate. Just do this each time you want to run the Anaconda Prompt, and you should be good to go.
Here is a screenshot


text:
Q: Determine 3-D coordinates based on TDOA of 4 microphones I am trying to determine the (x,y,z) coordinates of a sound source given TDOA information from 4 microphones in Python.
This pdf is very close but works with TOA, which is then converted into TDOA.
This answer shows how to get 4 non-linear equations, but I am not sure how to solve this.
This article shows a multilateration solution with 5 sensors. There is a python version in the comments. Someone also asks in the comments if there is a 4 sensor solution, apparently there is but its not very reliable. I am not sure if this is a limitation of multilateration or of 4 sensors in general.
I have also found other 2D solutions: here and here
I have the freedom of moving the microphones to wherever makes the calculations the simplest. Ideally I am looking for a function that takes as it's parameters the 4 microphones positions and the TDOA for each pair and returns a x,y,z source location/s (depending if there are ambiguities)

A: Hey just incase anyone else needs this the following is a linear equation solver based off the formulas from
https://www.ece.ucf.edu/seniordesign/sp2019su2019/g04/Docs/CONFERENCEPAPER.pdf
from scipy.optimize import minimize
import numpy

def tdoa_solve(delays_to_stations, stations_coordinates):
    # inspired by https://www.ece.ucf.edu/seniordesign/sp2019su2019/g04/Docs/CONFERENCEPAPER.pdf
    def error(x, c, d):
        value = sum([(numpy.linalg.norm(x - c[i]) - numpy.linalg.norm(x - c[0]) - 331.3 * (d[i] - d[0])) ** 2 for i in range(1, len(d))])
#         print((x, value))
        return value
    x0 = numpy.array([0.3,0.3,0.1])
    return minimize(error, x0, args=(stations_coordinates, delays_to_stations), method='Nelder-Mead').x

if __name__ == "__main__":
    stations = list(numpy.array([[1,1,0], [0,1,0], [1,0,0], [0,0,1]])) # the four sensors must be non-planar otherwise it won't be able to solve for the third dimension.

    delays_to_stations_list = [
        [0.00213434, 0.00213434, 0.00213434, 0.003696785],  # 0.5,0.5,0
        [0.002614022, 0.002614022, 0.002614022, 0.002614022],  # 0.5,0.5,0.5
        [0.00106717, 0.002386264, 0.002386264, 0.004400054], # 0.75,0.75,0
        [0.002502735, 0.003289239, 0.003289239, 0.003289239], # 0.75,0.75,0.75
    ]
    for delays_to_stations in delays_to_stations_list:
        print(tdoa_solve(delays_to_stations, stations))


text:
Q: doc has error? not sure http://docs.phalconphp.com/en/0.6.0/reference/odm.html
Setting multiple databases¶
In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when Phalcon\Mvc\Collection needs to connect to the database it requests the "mongo" service in the application's services container. You can overwrite this service setting it in the initialize method:
<?php

//This service returns a mongo database at 192.168.1.100
$di->set('mongo1', function() {
 $mongo = new Mongo("mongodb://scott:nekhen@192.168.1.100");
 return $mongo->selectDb("management");
});

//This service returns a mongo database at localhost
$di->set('mongo2', function() {
$mongo = new Mongo("mongodb://localhost");
return $mongo->selectDb("invoicing");
});

Then, in the Initialize method, we define the connection service for the model:
<?php

class Robots extends \Phalcon\Mvc\Collection
{

    public function initialize()
    {
        $this->setConnectionService('management'); // here?
    }

}

A: You are correct. The documentation was wrong. The correct usage is to set the appropriate service name (not the collection) using the setConnectionService.
http://docs.phalconphp.com/en/latest/reference/odm.html
<?php

// This service returns a mongo database at 192.168.1.100
$di->set(
    'mongo1',
    function()
    {
        $mongo = new Mongo("mongodb://scott:nekhen@192.168.1.100");
        return $mongo->selectDb("management");
    }
);

// This service returns a mongo database at localhost
$di->set(
    'mongo2',
    function()
    {
        $mongo = new Mongo("mongodb://localhost");
        return $mongo->selectDb("invoicing");
    }
);

Then, in the Initialize method, we define the connection service for the model:
.. code-block:: php
<?php

class Robots extends \Phalcon\Mvc\Collection
{
    public function initialize()
    {
        $this->setConnectionService('mongo1');
    }

}


text:
Q: Interrupt super.onCreate() in super class I have a base Activity in which I want to check authentication for all Activities that require to be logged in, both onCreate and onResume:
For example HomeActivity:
public class HomeActivity extends AccountRequiredActivity {

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

}

public class AccountRequiredActivity extends LifecycleActivity {
    private final int INTENT_REQUEST_CODE = 1;

    @Inject
    ViewModelProvider.Factory viewModelFactory;

    private AccountViewModel accountViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidInjection.inject(this);
        accountViewModel = ViewModelProviders.of(this, viewModelFactory).get(AccountViewModel.class);
        checkAuthentication();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkAuthentication();
    }

    private void checkAuthentication() {
        // Check if authenticated synchronously
        if(!accountViewModel.isAuthenticated()) {
            getLogin();
        };
    }

    private void getLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, INTENT_REQUEST_CODE);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == INTENT_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // The login is ok, continue
            } else {
                getLogin();
            }
        }

    }
}

LoginActivity is a separate activity that manages the login flow (connection to FB server and my own).
There are 2 problems with this code.
The first problem is that when isAuthenticated is false, I don't want the method to return to the calling child Activity (in this case, HomeActivity) because setContentView of Home should not be set.
The second problem is that onActivityResultis called asynchronously (as is the login flow in LoginActivity as a matter of fact.
How do I fix this code so that I'm able to make the auth check in the base class, while only continuing to call setContentView when the authentication succeeds?

A: In the base Activity do something like this:
@Override
protected final void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Do your authentication stuff here
    if (auth is successfull) {
        // Call derived Activity's "doOnCreate()" to set content view, etc.
        doOnCreate(savedInstanceState);
    } else {
        // Here you can do whatever you need to do in case the auth fails
    }
}

Declaring the method final prevents derived activities from overriding it.
Also create an abstract method doOnCreate() in the base Activity that each derived Activity needs to override.
Each derived Activity should NOT override onCreate(), but implement doOnCreate() and implement all of its initialization there.


text:
Q: How to trigger child process code from another file? I have code basically like this in one file, index.js:
module.exports = {
    const processHandler = require("myOtherFile.js");
    cp = require("child_process");
    cp.fork(pathOfCodeForFork);
    cp.send("message");
}

In another file (myOtherFile.js) I have:
process.on("message", function(msg) {
    console.log("here is the message " + msg);
}

The file loads but the code inside the process.on block never executes. Would really appreciate some guidance. New to child processes and probably not setting this up correctly.

A: So I asked this question, but I figured out the issue and wanted to post for anyone else struggling with this (and ask a follow-up). It turns out that pulling out the require for the myOtherFile.js from the module causes this to work (so, place  const processHandler = require("myOtherFile.js"); above the module code altogether). The follow up, is I am not sure why? Is the reference to process different inside and outside the module? Or is this a circular requires issue somehow? Is this about the order in which things get run? Something else?


text:
Q: SyntaxError: Unexpected identifier 'supabase'. Expected ';' after variable declaration I am trying to delete a row from the database and when I load the page, the file throws an error saying SyntaxError: Unexpected identifier 'supabase'. Expected ';' after variable declaration.
Following is my function code:
window.deleteChap = async function deleteChap(x) {

  let chapid = chapids[x];

  Swal.fire({
    title: `Are you sure you want to delete the chapter? This action is irreversible.`,
    showCancelButton: true,
    confirmButtonText: 'Yes, delete it!',
  }).then((result) => {
    if (result.isConfirmed) {

      const { data, error } = await supabase.from('chapters').eq('id', chapid).delete();

      if (error) {
        erroralert(error.message);
      } else {
        successalert(`Chapter deleted successfully.`);
      }
    }
  })

}

The supabase client has already been initialised this way:
let supabase;
$.ajax({
    url: "/keys",
    success: async function( result ) {

        result = JSON.parse(result);

        supabase = createClient(result.link, result.anon_key);

  }});

The javascript file is linked to the html with <script defer src="/js/dnovelinfo.js" type="module"></script>
I am not sure why the error is being thrown, even when I haven't interacted with the page (the page was only reloaded to see latest changes)

A: First of all,
const { data, error } = await supabase.from('chapters').eq('id', chapid).delete();

is not correct, you need to put .delete() just after from('chapters'), like this:
const { data, error } = await supabase.from('chapters').delete().eq('id', chapid);

A: I forgot to put the async keyword in the function after Swal.fire
It should have been like this: then( async (result) => {


text:
Q: Form events don't fire for select element (only JavaScript, no jQuery!) I have a form with a select element, radio buttons and checkboxes giving different options that, when selected/unselected, change the text inside the div underneath the form, automatically, using an onchange or oninput event.
It all works fine for the radio buttons and checkboxes but not with the select element, where I get the result from the option that was selected when the page loaded once I change it to another option, and not the option to which I changed, and it only changes the result the first time I apply a change to the select element.
Note: that I am trying to use only JavaScript without using JQuery.

var form = document.pcform;
var optionIndex = form.elements.dropdown.options.selectedIndex;

var thrPrice = 250;
var fftPrice = 300;
var svtPrice = 350;
var i3Price = 100;
var i5Price = 290;
var i7Price = 450;
var dvdPrice = 190;
var blurayPrice = 250;

function totalPrice() {
  var pcPrice = 0;

  if (optionIndex == 0) {
    pcPrice = pcPrice + thrPrice;
  }
  if (optionIndex == 1) {
    pcPrice = pcPrice + fftPrice;
  }
  if (optionIndex == 2) {
    pcPrice = pcPrice + svtPrice;
  }
  if (document.getElementById('i3').checked) {
    pcPrice = pcPrice + i3Price;
  }
  if (document.getElementById('i5').checked) {
    pcPrice = pcPrice + i5Price;
  }
  if (document.getElementById('i7').checked) {
    pcPrice = pcPrice + i7Price;
  }
  if (document.getElementById('dvd').checked) {
    pcPrice = pcPrice + dvdPrice;
  }
  if (document.getElementById('bluray').checked) {
    pcPrice = pcPrice + blurayPrice;
  }
  document.getElementById('priceDiv').innerHTML = "Your computer costs USD" + pcPrice;
}

pcform.addEventListener("change", totalPrice);
<form action="" name="pcform">

    Get the computer exactly how you want it!

   Screen size:
  <select id="dropdown" onchange="totalPrice()">
    <option id="thrteen" value="thirteen">13"</option>
    <option id="ffteen" value="fifteen">15"</option>
    <option id="svteen" value="seventeenthree">17,3"</option>
  </select>

Select the processor:

            <input type="radio" value="corei3" id="i3" name="processor">
            Core i3

            <input type="radio" value="corei5" id="i5" name="processor">
            Core i5

             <input type="radio" value="corei7" id="i7" name="processor">
            Core i7

Components:

    <input type="checkbox" value"dvdrom" id="dvd">
               DVD-ROM

    <input type="checkbox" value="bluray" id="bluray">
               Blu bluray

</form>.

A: The onchange event was firing off each time. You did not update option index each time it ran.
 var form = document.pcform;

    var thrPrice = 250;
    var fftPrice = 300;
    var svtPrice = 350;
    var i3Price = 100;
    var i5Price = 290;
    var i7Price = 450;
    var dvdPrice = 190;
    var blurayPrice = 250;

    function totalPrice() {
      var pcPrice = 0;
      var optionIndex = form.elements.dropdown.options.selectedIndex;

      if (optionIndex == 0) {
        pcPrice = pcPrice + thrPrice;
      }
      if (optionIndex == 1) {
        pcPrice = pcPrice + fftPrice;
      }
      if (optionIndex == 2) {
        pcPrice = pcPrice + svtPrice;
      }
      if (document.getElementById('i3').checked) {
        pcPrice = pcPrice + i3Price;
      }
      if (document.getElementById('i5').checked) {
        pcPrice = pcPrice + i5Price;
      }
      if (document.getElementById('i7').checked) {
        pcPrice = pcPrice + i7Price;
      }
      if (document.getElementById('dvd').checked) {
        pcPrice = pcPrice + dvdPrice;
      }
      if (document.getElementById('bluray').checked) {
        pcPrice = pcPrice + blurayPrice;
      }
      document.getElementById('priceDiv').innerHTML = "Your computer costs USD" + pcPrice;
    }

    pcform.addEventListener("change", totalPrice);

A: Your main error was not getting the index each time something changed.
I could not help trying to make an in my mind more elegant version which is unobtrusive. It will update whenever anything is changed in the form
I fixed several typos and mistakes in the label "for" and value"dvdrom" without = sign
The code below could be extended to not even look at the fields one by one, but take them by class and look them up in the object

var prices = {
  "thirteen": 250,
  "fifteen": 300,
  "seventeenthree": 350,
  "corei3": 100,
  "corei5": 290,
  "corei7": 450,
  "dvdrom": 190,
  "bluray": 250
};

var pcForm = document.getElementById("pcform");
pcForm.addEventListener("change", function(e) {
  var screen = prices[document.getElementById("screens").value]; // always set

  var rad = document.querySelector("[name=processor]:checked"); // not always set
  var processor = rad ? prices[rad.value] : 0;

  var dvdCheck = document.getElementById("dvd");
  var dvd = dvdCheck.checked ? prices[dvdCheck.value] : 0; // checked or not

  var blurayCheck = document.getElementById("bluray");
  var bluray = blurayCheck.checked ? prices[blurayCheck.value] : 0; // checked or not

  // console.log(screen, processor, dvd, bluray)
  var pcPrice = screen + processor + dvd + bluray;
  document.getElementById('priceDiv').innerHTML = "Your computer costs USD" + pcPrice;
});
// trigger it onload
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', true, true);
pcForm.dispatchEvent(evt);
<form action="" name="pcform" id="pcform">
  Get the computer exactly how you want it!

   Screen size:
  <select id="screens">
    <option id="thrteen" value="thirteen">13"</option>
    <option id="ffteen" value="fifteen">15"</option>
    <option id="svteen" value="seventeenthree">17,3"</option>
  </select>

Select the processor:

      <input type="radio" value="corei3" id="i3" name="processor">
      Core i3

      <input type="radio" value="corei5" id="i5" name="processor">
      Core i5

      <input type="radio" value="corei7" id="i7" name="processor">
      Core i7

Components:

    <input type="checkbox" value="dvdrom" id="dvd">
      DVD-ROM

    <input type="checkbox" value="bluray" id="bluray">
      Blu bluray

</form>

A: I did console.log(optionIndex) and found that it fires each time. The problem is in the logic, you are using optionIndex for Select item index, but you never updated that. You can simply use event to get value of selected option and check against them.
Please find updated code below:

var thrPrice = 250;
var fftPrice = 300;
var svtPrice = 350;
var i3Price = 100;
var i5Price = 290;
var i7Price = 450;
var dvdPrice = 190;
var blurayPrice = 250;

function totalPrice(event) {
  var pcPrice = 0;
  if (event.target.value === 'thirteen') {
    pcPrice = pcPrice + thrPrice;
  }
  if (event.target.value === 'fifteen') {
    pcPrice = pcPrice + fftPrice;
  }
  if (event.target.value === 'seventeenthree') {
    pcPrice = pcPrice + svtPrice;
  }
  if (document.getElementById('i3').checked) {
    pcPrice = pcPrice + i3Price;
  }
  if (document.getElementById('i5').checked) {
    pcPrice = pcPrice + i5Price;
  }
  if (document.getElementById('i7').checked) {
    pcPrice = pcPrice + i7Price;
  }
  if (document.getElementById('dvd').checked) {
    pcPrice = pcPrice + dvdPrice;
  }
  if (document.getElementById('bluray').checked) {
    pcPrice = pcPrice + blurayPrice;
  }
  document.getElementById('priceDiv').innerHTML = "Your computer costs USD" + pcPrice;
}

pcform.addEventListener("change", totalPrice);
<form action="" name="pcform" id="pcform">
  Get the computer exactly how you want it!

   Screen size:
  <select id="screens">
    <option id="thrteen" value="thirteen">13"</option>
    <option id="ffteen" value="fifteen">15"</option>
    <option id="svteen" value="seventeenthree">17,3"</option>
  </select>

Select the processor:

      <input type="radio" value="corei3" id="i3" name="processor">
      Core i3

      <input type="radio" value="corei5" id="i5" name="processor">
      Core i5

      <input type="radio" value="corei7" id="i7" name="processor">
      Core i7

Components:

    <input type="checkbox" value="dvdrom" id="dvd">
      DVD-ROM

    <input type="checkbox" value="bluray" id="bluray">
      Blu bluray

</form>


text:
Q: Why escape sequence "\a" doesn't produce sound in Windows Form application? I'm using visual studio and I've created a windows form application for C#. I tried the codes:
//1st
textBox1.Text = "\a";
Thread.Sleep(500);

and
//2nd
Messagebox.Show("\a");
Thread.Sleep(500);

and
//3rd
Console.WriteLine("\a");
Thread.Sleep(500);

but none of these codes produced any sounds from the \a escape sequence.
However, when I tried the 3rd set of codes on a Console application instead,
it worked. What codes should I use to allow the \a escape sequence to work and produce a sound on windows form application?

A: I think \a is only interpreted as beep by the console window. To play a beep sound in a windows forms application you can use:
SystemSounds.Beep.Play();

See this Microsoft article.


text:
Q: Error taking the difference within a function the function below is one that I have previously been able to use when fulldiam has been a vector.
dN <- sapply(df,function(dn,fulldiam) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam))),fulldiam)

In this function, df is a numeric data.frame (dim = 99 x 1399) and fulldiam is a numeric vector (length = 99).
I am trying to alter the data by altering the fulldiam vector to where it is slightly different for each. So now I am trying to use fulldiam_shifted which is a numeric data.frame (dim = 99 x 1399). When I try to run the function with the change I get an error.
dN_shift <- sapply(df,function(dn,fulldiam_shifted) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam_shifted))),fulldiam_shifted)

Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] :
  non-numeric argument to binary operator

I believe the issue is that the fulldiam_shifted needs to have each column called for each row of df. Is there any recommendations on what could be done to allow this function to work?

A: We may use Map here as both the datasets are of equal dimensions
Map(function(dn, fulldiam_new) 0.5*(head(dn,-1)+tail(dn,-1))*
                       abs(diff(log10(fulldiam_new))), df, fulldiam_shifted)


text:
Q: How to launch process from android app with ROOT permissions How to launch a process from android app with ROOT permissions?
I've found similar questions but they are not working for me: 1, 2
Error log (IOException when using Runtime.getRuntime().exec(commandArray);):
Caused by: java.io.IOException: Error running exec(). Command: [su -c, /data/data/%my_app_package%/%app% %params%] Working Directory: null Environment: null
08-22 11:02:17.515: WARN/System.err(19804): at java.lang.ProcessManager.exec(ProcessManager.java:211)
08-22 11:02:17.515: WARN/System.err(19804): at java.lang.Runtime.exec(Runtime.java:168)
08-22 11:02:17.515: WARN/System.err(19804): at java.lang.Runtime.exec(Runtime.java:123)
08-22 11:02:17.515: WARN/System.err(19804): ... 5 more
08-22 11:02:17.515: WARN/System.err(19804): Caused by: java.io.IOException: Permission denied
08-22 11:02:17.515: WARN/System.err(19804): at java.lang.ProcessManager.exec(Native Method)
08-22 11:02:17.515: WARN/System.err(19804): at java.lang.ProcessManager.exec(ProcessManager.java:209)
08-22 11:02:17.515: WARN/System.err(19804): ... 8 more

Similar error output when launching using ProcessBuilder:
08-22 11:19:34.052: WARN/System.err(22054): Caused by: java.io.IOException: Error running exec(). Command: [su -c, /data/data/%app_package%/%app% %parameters%] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/storage/sdcard0, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/framework_ext.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,65536]
08-22 11:19:34.052: WARN/System.err(22054): at java.lang.ProcessManager.exec(ProcessManager.java:211)
08-22 11:19:34.052: WARN/System.err(22054): at java.lang.ProcessBuilder.start(ProcessBuilder.java:195)
08-22 11:19:34.052: WARN/System.err(22054): ... 5 more
08-22 11:19:34.052: WARN/System.err(22054): Caused by: java.io.IOException: Permission denied

I'm absolutely sure the device is rooted and it works okay. Sometimes i'm asked for granting root permissions to the apps. In this case i'm not asked, just getting error.
How to ask root permission for the app in runtime? Does it grant root permissions for all started processes?

A: There is a difference on how to build command-line for process for ProcessBuilder:
NOT working code:

*

*commandLine.add("su -c"); commandLine.add("app"); commandLine.add("params")

*commandLine.add("sudo"); commandLine.add("app"); commandLine.add("params")
WORKING code:

*

*commandDownloader.add("su"); commandDownloader.add("-c"); commandLine.add("app");
For working code i'm asked for permission by Android OS (MIUI in my case to be more detailed)


text:
Q: How to do it can limit the number of open app? I have a program on which you want to limit the number of functions.
For example: send a message function can only be used 10 times, can not be used up in the open, and will pop up the number of your purchase information.
I have tried using the following method can be successful from 10 -> 0, but close the program to reload after the value has changed back to 10 up!!
There is no way 10 -> 0, close the program after re-loading or 0?
Thank you!!
- (void)viewDidLoad {
[super viewDidLoad];
   numberoftimes = 10;

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

[def setInteger:numberoftimes forKey:@"IntegerVal"];
[def synchronize];

numberoftimes-= 1;
 NSUserDefaults *def = [NSUserDefaults standardUserDefaults];

 [def setInteger:numberoftimes forKey:@"IntegerVal"];
 [def synchronize];

A: It looks to me like you are setting the value of @integerVal to 10 every time your viewDidLoad method is called. What you want to do is get the existing value before you decrement it...
int currentNumberOfTimes = 10;
if ([def valueForKey:@"integerVal"]) {
    currentNumberOfTimes = [[def valueForKey:@"integerVal"] intValue];
}
numberOfTimes = currentNumberOfTimes --;

[def setInteger:numberoftimes forKey:@"IntegerVal"];
[def synchronize];


text:
Q: Blur event doesn't fire when navigating away from input field When I move out of my input field the blur function doesn't fire.
Any idea's?
<input type="text" value="test" id="webshop_product_url_part" name="setting" class="is"/>

jQuery("input.is").live("blur", function(){
            console.log("2");
            conslole.log("asdf");

        });

A: Looking on jQuery live() documentation

Binds a handler
to an event (like click) for all
current - and future - matched
element. Can also bind custom events.
Possible event values: click,
dblclick, mousedown, mouseup,
mousemove, mouseover, mouseout,
keydown, keypress, keyup
Currently not supported: blur, focus,
mouseenter, mouseleave, change, submit

A: live uses event delegation to work. This means that only events that bubble can take advantage of it. Events that do no bubble, and therefore cannot utilize event delegation (jQuery's live), include blur and focus, among others.
The only way around this is to bind the event to every element. When you append and element, bind it then. You could also write a plugin of sorts that adds parameters to jQuery's append, allowing you to specify an event and it's associated handler for all elements that match your selector.


text:
Q: What is a word that captures the *desire* to empathize? [I've checked all the single-word-requests about empathy; they mostly deal with those who lack empathy or somehow empathize "wrongly."]
Empathy is (roughly) the ability to understand another's experience, to put oneself in another's shoes.
Is there a word that captures the desire to empathize? Or the enjoyment thereof or satisfaction derived therefrom?

A: Solicitude is the nearest I can think of.

Solicitude: the quality of caring about other people's comfort, safety, and how they feel.
Example: I'm touched by your solicitude.
 [Cambridge English Dictionary]

As a quality of another quality, it may fit your question.


text:
Q: Learning C from a background in C# I want to broaden my programming experience and so figured that learning C (not C++) would be a nice idea - I've got a starting project (some simple 2D games using SDL) and given it a go, but I have to admit I'm struggling.
Now I consider myself to be a very a competent C# developer, but C is just a completely different world!

*

*No namespaces.

*Without classes I don't know how to structure my code.

*I understand header files & includes, but my use of them doesn't seem quite right.

*The loss of (for example) the String class is a bit of a culture shock.

On top of that I'm finding it tricky to separate out the C++ information from the C information (for example is snprintf a C++ only thing?)
This may sound like an odd request, but are there any good guides for learning C if you have experience in other languages?

A: Don't try to learn C from C++ books/web sites.  Start with something aimed only at C.  A great place is The C Programming Language.  It's the original and still one of the best programming language books out there.
Learning C is going to be a struggle because it's a different kind of language.  It's a procedural language, not an object oriented language.  It will be good to stretch your brain in learning it.  You'll likely also learn a lot more about the way your OS works because it's down much closer to the metal.
Note also that it's a much less complex language and thus is missing a lot of the niceties of a modern language.  There is no BCL/.Net Framework.  As you noticed, there is no string class (although there are string functions).

A: I'd recommend you start with a book on C. It's not a good idea to learn a new language in constant comparison with a previous one, you end up learning what's different and not what's new and unique.
Take a look at Kernighan and Ritchie's book, or Deitel & Deitel's. They will both strike you as overly basic at first, but you'll end up with a much more solid knowledge of the language.
edit: a friend of mine right here suggests you also find something on data structures and algorithms after you've grasped the language, since you'll be working in an environment with no objects.
Hope it helps!

A: I'll answer you question, but first: Going from C# to C is like going from a plastic toothbrush to a wooden one... I see no advantage.
So:
Namespaces - No, there aren't any in C. This is a C++/C# feature. You should be able to compensate with prefixes. (namespace_myClass).
As for classes, I don't know how to help you. I am a C++ programmer (not C), but C does have struct, though I don't know if you can have member functions.
Header files and includes are syntactically the same. For example:
#include <Windows.h>

gives you windows functionality. Note that, you may need to link in libraries for many header files, like openGL.
And what will we do without string? You could make your own, or you can manually manage C strings (char*) with the C functions such memcpy, ect...
Farewell and goodluck!

A: C++ is a superset of C. So anything you can do in C, you can do in C++.
I think it is a good idea to learn C. It will make you have to deal with memory and resource management, structured programming vs object-oriented, a it has a much smaller standard library as well (compared to C#).

A: http://publications.gbdirect.co.uk/c_book/
http://www.coronadoenterprises.com/tutorials/c/c_topics.html
http://www.cyberdiem.com/vin/tutorials/
try the above links


text:
Q: Excel For loop and general vba guidance I can't seem to figure out why this button is giving a runtime error '424'. I do not understand if it is the for loop that is throwing it off. I have tried replacing the .activate with .select and nothing happened.
Private Sub updateX_Click()
Dim emptyRow As Long
Dim emptyRowX As Long
Dim counter

Sheets("Master Inventory").Activate
Sheets("X").Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Worksheets("Master Inventory").Range("A:A")) + 1
emptyRowX = WorksheetFunction.CountA(Worksheets("X").Range("A:A")) + 1

For counter = 1 To emptyRow
    If MI.Cells(counter, 1).Value = "X" Then
    X.Cells(emptyRowX, 1).Value = MI.Cells(counter, 2).Value
    X.Cells(emptyRowX, 2).Value = MI.Cells(counter, 3).Value
    X.Cells(emptyRowX, 3).Value = MI.Cells(counter, 4).Value
    X.Cells(emptyRowX, 4).Value = MI.Cells(counter, 5).Value
    X.Cells(emptyRowX, 5).Value = MI.Cells(counter, 6).Value
    End If
Next counter

End Sub

A: What about following corrections:
Dim counter As Long <-- this you already have (but you forgot the type definition)

Dim MI As Worksheet, X As Worksheet

Set MI = Worksheets("Master Inventory")
Set X = Worksheets("X")

Sheets("Master Inventory").Activate <-- this you already have


text:
Q: Separate table in case of surrogate key? I have been reading the heated debates on composite vs surrogate keys on Stack Overflow and other websites, and even though puzzled about some of the arguments given, I feel I am aware of the pros and cons of each.
I feel tempted to go for surrogate keys, but now I have another question. Let me explain my situation. I have a table consisting of 5 integers that make up a unique combination, and I have several tables referencing this entity. Right now all tables include the full 5 fields and all JOIN operations have to mention all 5 fields as a join criterium. Now I have added a surrogate key. But should I remove all 5 fields from all tables in favour of a surrogate foreign key that references the 'main' table?
I feel unsure about doing this, since each of the 5 fields separately is frequently used as a selection criterium in the other tables. I have indexes defined on them, in a certain natural order, so that the selection operations perform fast. If I migrate all 5 fields to a separate table, I'm afraid that when I want to select on let's say the first three of them, I'll have to define a JOIN and select from that, but no indexes will have been defined on that JOIN since it has just been generated, and I will suffer a performance loss.
Or should I somehow define a VIEW for each table, including the 5 keys, and index on that?
I feel confused, and after typing all this, inclined to stick with natural keys again.
Help?

A: I'd suggest to have one table with your 5 unique fields + surrogate PRIMARY KEY. In that table you can create indexes on each of the fields + unique constraint on 5 fields. Then, instead of having 5 fields in other tables you, will have just 1 column .

A: Unless you have a very specific goal for introducing a surrogate key, I'd probably leave it alone as long as it works for you.


text:
Q: почему response scrapy не показывает информацию с страницы Пытаюсь достать информацию с страницы (json), но скрапи как будто не видит страницу, подскажите пожалуйста, в чем проблема?
ссылка на саму страницу
https://quizium.ru/ajaxrating?search_team=&season=all&city=7&json=1&offset=0


text:
Q: Why am I getting "The driver could not establish a secure connection to SQL Server" when running the jar but not when running the project in maven? I have a Java project that connects to SQL Server using mssql-jdbc-7.0.0.jre8.jar.  When I run the project using "mvn exec:java" the code works just fine.  But when I build the project into a jar using "mvn clean compile package" and copy the jdbc jar into the target directory and then try running using "java -jar "  I get the error
ERROR connecting to SQL Server: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SQL Server did not return a response. The connection has been closed.

Why does it work when not jarred, but doesn't work when jarred?


text:
Q: how to move canvas along with a centered canvas So I have 2 canvases - one big and one small that is on the big one.
My question is how is the easiest and better way to center the big canvas and move the small one with him so that it can be again in the left upper corner as before i center the main canvas.
This is my code:
HTML:

    <canvas id="projectGame" width="800" height="800"></canvas>
    <canvas id="popUp" width="150" height="200"></canvas>

CSS:
#canvas-container {
      position: relative;
}
#projectGame {
      position: absolute;
      border: 1px solid #000000;
       margin-left: auto;
      margin-right: auto;
      left: 0;
      right: 0;
       z-index: 3;
}

#popUp {
      position: absolute;
       z-index: 4;
      border: 5px solid #000000;
}

Thanks in advance :)

A: First, put the width and height on the container:
#canvas-container {
      position: relative;
      width: 800px;
      height: 800px;
}

    <canvas id="projectGame"></canvas>
    <canvas id="popUp" width="150" height="200"></canvas>

then make the main canvas 100% of the container:
#projectGame {
      width: 100%;
      height: 100%;
      position: absolute;
      border: 1px solid #000000;
       margin-left: auto;
      margin-right: auto;
      left: 0;
      right: 0;
       z-index: 3;
}

Then set the popup's top-left where you want it relativly:
#popUp {
    position: relative;
    top: 150px;
    left: 150px;
    z-index: 4;
    border: 5px solid #000000;
}

Now move the whole container when you want to move/center/whatever the canvases instead of just moving/centering the one canvas.


text:
Q: Making Kafka consumers consume existing messages before subscription Having Publisher and N Consumers, if consumers use auto.offset.reset=latest then they miss all the messages that were published to a topic before they subscribed to it ... It is a known fact that Consumer with auto.offset.reset=latestdoesn't replay messages that existed in the topic before it subscribed...
So I would need either :

*

*Make publisher wait until all subscribers start consuming messages and then start publishing. Dunno how to do that without leveraging Zookeeper for instance. Does Kafka provide means to do that ?

*Another way would be having auto.offset.reset=latest Consumers and make them explicitly consume all existing messages before in case they are about to subscribe to a topic with existing messages...

What is the best practice for this case?
I guess that consumer must check topic for existing messages, consume them if there are any and then initiate auto.offset.reset=latest consumption. That sounds like the best way to me ...

A: If a high level consumer gets started, it does the following:

*

*look for committed offsets for its consumer group
a. if valid offsets are found, resume from there
b. if no valid offsets are found, set offsets according to auto.offset.reset
Thus, auto.offset.reset only triggers, if no valid offset was committed. This behavior is intended and necessary to provide at-least-once processing guarantees in case of failure.
Thus, is you want to read a topic from its beginning, you can either use a new consumer group.id and set auto.offset.reset = earliest or you explicitly modify the offsets on startup using seekToBeginning() before you start your poll() loop.

A: We do the option (1) using a service discovery feature provided by Eureka (any other service discovery app would do the job) + aliasing. Basically a publisher does not register itself (and start processing requests nor publish notifications) until at least one subscriber is available.


text:
Q: CSR to render Task Status destroys Task checkboxes I'm using some JavaScript to provide a more visual approach to a task lists column Percentage Complete.
The script works fine, but I noticed that the task column Completed is not being rendered as a unchecked/checked checkbox and instead displays the actual checkbox values No/Yes.
Using F12 Developer tool, there is no console error, and inspecting the HTML shows that when the script is applied that the HTML that renders the checkbox is never added.
The picture below demonstrates with and without the script. (Used as a JSLink).

The full script.
(function () {

    // Create object that have the context information about the field that we want to change it's output render
    var percentCompleteFiledContext = {};
    percentCompleteFiledContext.Templates = {};
    percentCompleteFiledContext.Templates.Fields = {
        // Apply the new rendering for PercentComplete field on List View, Display, New and Edit forms
        "PercentComplete": {
            "View": percentCompleteViewFiledTemplate,
            "DisplayForm": percentCompleteViewFiledTemplate,
            "NewForm": percentCompleteEditFiledTemplate,
            "EditForm": percentCompleteEditFiledTemplate
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(percentCompleteFiledContext);

})();

// This function provides the rendering logic for View and Display form
function percentCompleteViewFiledTemplate(ctx) {

    var percentComplete = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
    return "
 \

 \

 " + percentComplete;

}

// This function provides the rendering logic for New and Edit forms
function percentCompleteEditFiledTemplate(ctx) {

    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        return document.getElementById('inpPercentComplete').value;
    });

    return "<input type='range' id='inpPercentComplete' name='inpPercentComplete' min='0' max='100' \
            oninput='outPercentComplete.value=inpPercentComplete.value' value='" + formCtx.fieldValue + "' /> \
            <output name='outPercentComplete' for='inpPercentComplete' >" + formCtx.fieldValue + "</output>%";

}

CSR code samples #5 (Percent Complete)
Any pointers in the right direction?

A: It is not your CSR destroying the checkboxes,
It is because Microsoft didn't test JSLink properly and shipped a failing product
The Checkboxes are created by a JSLink on the View definition (each View definition)
If you check the sources it loads hierarchytaskslists.js, and that CSR code does the CheckBox
Now when you attach another JSLink on the WebPart it effectivly blocks loading of every other JSLInk on Views (and maybe even Field JSLinks)
Workaround is to load the Microsoft JS files yourself, add it as an extra JSLink on your WebPart

JSLinks on WebPart, View , Field
My (private) Link Manager App learned me there are 3 Microsoft JS files applied to various types of Lists
This is the Tasks list, where you see, by default every View gets the hierarchytaskslists file
But they do not work the moment you add a JSLink on the ListView webpart!!

No Field JSLinks here as you can only set those with back-end PowerShell code, not from the Browser side
Creating CSR / JSLink
Check out the awesome WYSIWYG editor Chrome Extension Andrey Markeev wrote:
https://github.com/andrei-markeev/cisar
It makes editing CSR a breeze
And https://github.com/tavikukko/Chrome-SP-Editor is a cool tool too


text:
Q: Updating a gtk_tree_view from pthreads I've been trying to figure out some method to cause a GtkTreeView to redraw after I update the bound GtkListStore from a background thread created with pthreads.
Generally, the widget does not update until something obscures an existing row (even a mouse cursor ).
Most of my searches for this problem has "your tree model doesn't/isn't generating the correct signals" ....
I'm running an old Red Hat 9 with gtk+ 2.0.0, for industrial embedded applications.  Most of the data comes from ipc/socket/pipes and gets displayed by a GTK app.  Unfortunately so does CRITICAL alarms, which has a habit of not showing when they should.  We will (one day) move to a current kernel, but I need to get something working with the existing software.
I've tried emiting the "row-changed" signals, tried calling the gtk_widget_queue_draw and also tried connecting to the "expose-event", where I've tried various things that don't work or seg fault.
server.c
bool Server::Start()
{
 // ....
 // pthread_t _id;
 //
 pthread_create( & _id, NULL, &StaticServerThread, this );
 // ....
}

viewer.c
bool Viewer::ReadFinished( SocketArgs * args )
{
 gdk_threads_enter();

 // Populate the buffer and message
 //
 // GtkListStore *_outputStore;
 // gchar        *buffer;
 // gchar        *message;

 GtkTreeIter iter;
 gtk_list_store_insert_with_values( _outputStore, &iter, 0,
                    0, buffer, 1, message, -1 );

 // ....
 gdk_threads_leave();
}

A: You can perform the updates to the list store in the main thread.  For example, you can use g_idle_add() in the worker thread.


text:
Q: quick selection of a random row from a large table in mysql What is a fast way to select a random row from a large mysql table?
I'm working in php, but I'm interested in any solution even if it's in another language.

A: Grab all the id's, pick a random one from it, and retrieve the full row.
If you know the id's are sequential without holes, you can just grab the max and calculate a random id.
If there are holes here and there but mostly sequential values, and you don't care about a slightly skewed randomness, grab the max value, calculate an id, and select the first row with an id equal to or above the one you calculated. The reason for the skewing is that id's following such holes will have a higher chance of being picked than ones that follow another id.
If you order by random, you're going to have a terrible table-scan on your hands, and the word quick doesn't apply to such a solution.
Don't do that, nor should you order by a GUID, it has the same problem.

A: I knew there had to be a way to do it in a single query in a fast way. And here it is:
A fast way without involvement of external code, kudos to
http://jan.kneschke.de/projects/mysql/order-by-rand/
SELECT name
  FROM random AS r1 JOIN
       (SELECT (RAND() *
                     (SELECT MAX(id)
                        FROM random)) AS id)
        AS r2
 WHERE r1.id >= r2.id
 ORDER BY r1.id ASC
 LIMIT 1;

A: Maybe you could do something like:
SELECT * FROM table
  WHERE id=
    (FLOOR(RAND() *
           (SELECT COUNT(*) FROM table)
          )
    );

This is assuming your ID numbers are all sequential with no gaps.

A: MediaWiki uses an interesting trick (for Wikipedia's Special:Random feature): the table with the articles has an extra column with a random number (generated when the article is created). To get a random article, generate a random number and get the article with the next larger or smaller (don't recall which) value in the random number column. With an index, this can be very fast. (And MediaWiki is written in PHP and developed for MySQL.)
This approach can cause a problem if the resulting numbers are badly distributed; IIRC, this has been fixed on MediaWiki, so if you decide to do it this way you should take a look at the code to see how it's currently done (probably they periodically regenerate the random number column).

A: Add a column containing a calculated random value to each row, and use that in the ordering clause, limiting to one result upon selection. This works out faster than having the table scan that ORDER BY RANDOM() causes.
Update: You still need to calculate some random value prior to issuing the SELECT statement upon retrieval, of course, e.g.
SELECT * FROM `foo` WHERE `foo_rand` >= {some random value} LIMIT 1

A: Here's a solution that runs fairly quickly, and it gets a better random distribution without depending on id values being contiguous or starting at 1.
SET @r := (SELECT ROUND(RAND() * (SELECT COUNT(*) FROM mytable)));
SET @sql := CONCAT('SELECT * FROM mytable LIMIT ', @r, ', 1');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

A: For selecting multiple random rows from a given table (say 'words'), our team came up with this beauty:
SELECT * FROM
`words` AS r1 JOIN
(SELECT  MAX(`WordID`) as wid_c FROM `words`) as tmp1
WHERE r1.WordID >= (SELECT (RAND() * tmp1.wid_c) AS id) LIMIT n

A: There is another way to produce random rows using only a query and without order by rand().
It involves User Defined Variables.
See how to produce random rows from a table

A: if you don't delete row in this table, the most efficient way is:
(if you know the mininum id just skip it)
SELECT MIN(id) AS minId, MAX(id) AS maxId FROM table WHERE 1

$randId=mt_rand((int)$row['minId'], (int)$row['maxId']);

SELECT id,name,... FROM table WHERE id=$randId LIMIT 1

A: In order to find random rows from a table, don't use ORDER BY RAND() because it forces MySQL to do a full file sort and only then to retrieve the limit rows number required. In order to avoid this full file sort, use the RAND() function only at the where clause. It will stop as soon as it reaches to the required number of rows.
See
http://www.rndblog.com/how-to-select-random-rows-in-mysql/

A: I see here a lot of solution. One or two  seems ok but other solutions have some constraints. But the following solution will work for all situation
select a.* from random_data a, (select max(id)*rand() randid  from random_data) b
     where a.id >= b.randid limit 1;

Here, id, don't need to be sequential. It could be any primary key/unique/auto increment  column. Please see the following Fastest way to select a random row from a big MySQL table
Thanks
Zillur
- www.techinfobest.com

A: The classic "SELECT id FROM table ORDER BY RAND() LIMIT 1" is actually OK.
See the follow excerpt from the MySQL manual:
If you use LIMIT row_count with ORDER BY, MySQL ends the sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result.

A: An easy but slow way would be (good for smallish tables)
SELECT * from TABLE order by RAND() LIMIT 1

A: With a order yo will do a full scan table.
Its best if you do a select count(*) and later get a random row=rownum between 0 and the last registry

A: In pseudo code:
sql "select id from table"
store result in list
n = random(size of list)
sql "select * from table where id=" + list[n]

This assumes that id is a unique (primary) key.

A: I'm a bit new to SQL but how about generating a random number in PHP and using
SELECT * FROM the_table WHERE primary_key >= $randNr

this doesn't solve the problem with holes in the table.
But here's a twist on lassevks suggestion:
SELECT primary_key FROM the_table

Use mysql_num_rows() in PHP create a random number based on the above result:
SELECT * FROM the_table WHERE primary_key = rand_number

On a side note just how slow is SELECT * FROM the_table:
Creating a random number based on mysql_num_rows() and then moving the data pointer to that point mysql_data_seek(). Just how slow will this be on large tables with say a million rows?

A: Take a look at this link by Jan Kneschke or this SO answer as they both discuss the same question. The SO answer goes over various options also and has some good suggestions depending on your needs. Jan goes over all the various options and the performance characteristics of each. He ends up with the following for the most optimized method by which to do this within a MySQL select:
SELECT name
  FROM random AS r1 JOIN
       (SELECT (RAND() *
                     (SELECT MAX(id)
                        FROM random)) AS id)
        AS r2
 WHERE r1.id >= r2.id
 ORDER BY r1.id ASC
 LIMIT 1;

HTH,
-Dipin

A: I ran into the problem where my IDs were not sequential.  What I came up with this.
SELECT * FROM products WHERE RAND()<=(5/(SELECT COUNT(*) FROM products)) LIMIT 1

The rows returned are approximately 5, but I limit it to 1.
If you want to add another WHERE clause it becomes a bit more interesting.  Say you want to search for products on discount.
SELECT * FROM products WHERE RAND()<=(100/(SELECT COUNT(*) FROM pt_products)) AND discount<.2 LIMIT 1

What you have to do is make sure you are returning enough result which is why I have it set to 100.  Having a WHERE discount<.2 clause in the subquery was 10x slower, so it's better to return more results and limit.

A: Use the below query to get the random row
SELECT user_firstname ,
COUNT(DISTINCT usr_fk_id) cnt
FROM userdetails
GROUP BY usr_fk_id
ORDER BY cnt ASC
LIMIT 1

A: In my case my table has an id as primary key, auto-increment with no gaps, so I can use COUNT(*) or MAX(id) to get the number of rows.
I made this script to test the fastest operation:
logTime();
query("SELECT COUNT(id) FROM tbl");
logTime();
query("SELECT MAX(id) FROM tbl");
logTime();
query("SELECT id FROM tbl ORDER BY id DESC LIMIT 1");
logTime();

The results are:

*

*Count: 36.8418693542479 ms

*Max: 0.241041183472 ms

*Order: 0.216960906982 ms
Answer with the order method:
SELECT FLOOR(RAND() * (
    SELECT id FROM tbl ORDER BY id DESC LIMIT 1
)) n FROM tbl LIMIT 1

...
SELECT * FROM tbl WHERE id = $result;

A: I have used this and the job was done
the reference from here
SELECT * FROM myTable WHERE RAND()<(SELECT ((30/COUNT(*))*10) FROM myTable) ORDER BY RAND() LIMIT 30;

A: Create a Function to do this most likely the best answer and most fastest answer here!
Pros - Works even with Gaps and extremely fast.
<?

$sqlConnect = mysqli_connect('localhost','username','password','database');

function rando($data,$find,$max = '0'){
   global $sqlConnect; // Set as mysqli connection variable, fetches variable outside of function set as GLOBAL
   if($data == 's1'){
     $query = mysqli_query($sqlConnect, "SELECT * FROM `yourtable` ORDER BY `id` DESC LIMIT {$find},1");

     $fetched_data = mysqli_fetch_assoc($query);
      if(mysqli_num_rows($fetched_data>0){
       return $fetch_$data;
      }else{
       rando('','',$max); // Start Over the results returned nothing
      }
   }else{
     if($max != '0'){
        $irand = rand(0,$max);
        rando('s1',$irand,$max); // Start rando with new random ID to fetch
     }else{

        $query = mysqli_query($sqlConnect, "SELECT `id` FROM `yourtable` ORDER BY `id` DESC LIMIT 0,1");
        $fetched_data = mysqli_fetch_assoc($query);
        $max = $fetched_data['id'];
        $irand = rand(1,$max);
        rando('s1',$irand,$max); // Runs rando against the random ID we have selected if data exist will return
     }
   }
 }

 $your_data = rando(); // Returns listing data for a random entry as a ASSOC ARRAY
?>

Please keep in mind this code as not been tested but is a working concept to return random entries even with gaps.. As long as the gaps are not huge enough to cause a load time issue.

A: SELECT DISTINCT * FROM yourTable WHERE 4 = 4 LIMIT 1;

A: Quick and dirty method:
SET @COUNTER=SELECT COUNT(*) FROM your_table;

SELECT PrimaryKey
FROM your_table
LIMIT 1 OFFSET (RAND() * @COUNTER);

The complexity of the first query is O(1) for MyISAM tables.
The second query accompanies a table full scan. Complexity = O(n)
Dirty and quick method:
Keep a separate table for this purpose only. You should also insert the same rows to this table whenever inserting to the original table. Assumption: No DELETEs.
CREATE TABLE Aux(
  MyPK INT AUTO_INCREMENT,
  PrimaryKey INT
);

SET @MaxPK = (SELECT MAX(MyPK) FROM Aux);
SET @RandPK = CAST(RANDOM() * @MaxPK, INT)
SET @PrimaryKey = (SELECT PrimaryKey FROM Aux WHERE MyPK = @RandPK);

If DELETEs are allowed,
SET @delta = CAST(@RandPK/10, INT);

SET @PrimaryKey = (SELECT PrimaryKey
                   FROM Aux
                   WHERE MyPK BETWEEN @RandPK - @delta AND @RandPK + @delta
                   LIMIT 1);

The overall complexity is  O(1).


text:
Q: Matplotlib: plot multiple graphs using same figure, without them overlapping I have a class which I use to plot things then save them to a file. Here's a simplified version of it:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

class Test():
    def __init__(self, x, y, filename):

        fig = plt.figure(1)
        ax = fig.add_subplot(111)

        ax.plot(x, y, 'D', color='red')

        ax.set_xbound(-5,5)
        ax.set_ybound(-5,5)

        plt.savefig('%s.png' % filename)

test1 = Test(1,2, 'test1')
test2 = Test(2,4, 'test2')

Here are the results:
test1

test2

The problem is that the test2 image also has the point from test1. The graphs are generated dynamically in a loop so I can't hardcode the figure number.
I could make a counter and pass it to the class constructor but I was wondering if there's a more elegant way to do this. I tried deleting the test1 object but that didn't do anything.

A: You could use the figure's clf method to clear the figure after you're done with one.  Also, pyplot.clf will clear the current figure.
Alternatively, if you just want a new figure then call pyplot.figure without an explicit num argument -- it will autoincrement, so you don't need to keep a counter.


text:
Q: How can we be certain our world has only three spatial dimensions? It's common knowledge that the universe has three spatial dimensions, and one temporal. But how can we be so sure? Physics tells us that vector forces act independently along different dimensions, so without a source of force along the fourth dimension, or with a component in the fourth dimension, nothing would ever pass out of our little slit of 3D space in a possibly 4D world. Moreover, some materials exhibit different levels of friction, or any other measure of directional "resistance," (using the term as an abstraction for every barrier to motion, physical, fluid and so on) differently along different directions. We could just be stuck on our little 3D slice of 4D universe.
How can we possibly know the world is indeed three-dimensional, especially considering models of two-dimensional motion work so well in our three-dimensional world when motion along the third dimension is heavily restricted?
Note: The question How can we be so sure the universe has 3 dimensions is somewhat similar in that it asks if spatial dimensions exist at all, but is not a duplicate. I did my research.

A: I'm not sure what kind of argument can convince you, since you seem to reject the everyday experience that the world has three dimensions. Nevertheless, I'll try to give an alternative argument of why this is the case (at least for a macroscopic scale). The argument is related to how things scale with distance.
Observe that the area of a $d$-dimensional sphere of radius $r$ is proportional to $r^d$. Imagine some kind of flow emanating from some point in $(d+1)$-dimensional space. The total flow that traverses any $d$-sphere centered at that point will stay constant with radius, so the flow per unit area (meaning $d$-dimensional volume) will scale as $1/r^d$.

In our world, many physical phenomena involve scalings like $1/r^2$. This kind of laws appear in the cases where some flow should propagate freely along every possible dimension. Thus, they are all explained nicely with the same underlying principle: a flow per unit area when the total number of dimensions is three.

Some examples of inverse square laws are:

*

*Newton's law of gravitation

*Coulomb's law

*Sound intensity fall-off from a point source

*Light illuminance fall-off from a point source

Now, it could be the case that there are more dimensions but everything is restricted to three spatial dimensions. But what does this mean? If it doesn't affect anything, if it can't be measured in any way, we can just forget about it. Just use Occam's razor: why would we imagine extra things in the universe that don't have any possible effect in anything?
Another possibility is that at least some things propagate through the extra dimensions but there's something preventing us from noticing this fact. The most common idea in this kind of models is that the extra dimensions are small, so we can't see them yet. This happens, for example, in string theory or in some models that have become very popular in the last decade, such as "large" ($1\,\mathrm{mm}$) extra dimensions or the Randall-Sundrum model.
In one of them, the weakness of gravity is explained by saying that it is the only force that propagates through the extra dimension, thus losing strength with respect to the others. In this model, we expect to be able to measure deviations of the inverse square law for gravity at small distances. In general, any model with small extra dimensions predicts new effects at small distances.
This possibility isn't ruled out, so we aren't sure that the world has only three spatial dimensions. It could be the case that there are more, but very tiny.

A: We can't know that for certain. There are many models in high energy physics and cosmology which assume the existence of extra dimensions, e.g. string theory (where the extra dimensions are usually compact, i.e. "very small" and not visible at low energy) or the Randall–Sundrum model (which explicity allows a non-compact 5th dimension).
Nevertheless, what all these models have in common is that these extra dimensions play no role at your typical everyday life energy scale (it would give corrections to Newtonian mechanics which are neglectable). Why is this so ? Newtonian mechanics agrees with every measurement we do at low energies and so every theory which aspires to describe a fundamental model of nature should of course reproduce the results of Newtonian mechanics at the energy scales for which this gives a good description of nature.
As Sanya mentioned it, an important principle for a physical theory is that we can measure its predicitions, i.e. are able to falsificate the theory. You could of course always predict extra dimensions which are not reachable for us but influence our physical reality in some sense, but then you need to give a model which allows us the falsification of said model via testable predictions (as for example string theory allows, but only at extreme energy scales).
In short, scientific principles "prohibit" extra dimensions, see for example Russell's teapot.


text:
Q: Updating fragment TextView from adapter class I am using a fragment to show a recyclerview with items.
And I have a Adapter class for the recyclerview.
Every time the user clicks on a recyclerview item, I need to change the text from a fragment TextView.
This is the onClick method in adapter class:
@Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            //showPopupMenu(v, position);

            String positi = marcaList.get(position).getnombre();
            Integer positid = marcaList.get(position).getId();

            Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + position);

            Toast.makeText(mCtx,"Seleccionados dispositivos de la marca "+positi, Toast.LENGTH_SHORT).show();

            SharedPreferences prefs3 =
                    mCtx.getSharedPreferences(MISDATOS, Context.MODE_PRIVATE);

            SharedPreferences.Editor editor3 = prefs3.edit();
            editor3.putString("nombreMarcaNuevoDisp",positi);
            editor3.putInt("idMarcaNuevoDisp",positid);
            editor3.apply();

        }

What I need is to update the text from a TextView in the fragment with the values from the selected list item.
EDIT
Adapter Class:
public class MarcasAdapterNuevoDisp extends RecyclerView.Adapter<MarcasAdapterNuevoDisp.ProductViewHolder>  {

    public static String MISDATOS= "MisDatos";
    private Context mCtx;
    private List<Marca> marcaList;
    private SharedPreferences mPref;

    public FragmentManager f_manager;

    public MarcasAdapterNuevoDisp(Context mCtx, List<Marca> marcaList) {
        this.mCtx = mCtx;
        this.marcaList = marcaList;

    }

    public interface OnDataChangeListener{
        public void onDataChanged(int size);
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.marcas_list, null);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProductViewHolder holder, int position) {

        Marca marca = marcaList.get(position);
String url = "https://jogua.es/administrar/application/admin/iconos/";
        //loading the image
        Glide.with(mCtx)
                .load(url+marca.geticono())
                .into(holder.imageView);

    }

    @Override
    public int getItemCount() {

        return marcaList.size();
    }

    class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        TextView textViewTitle;
        ImageView imageView;

        public ProductViewHolder(View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            //showPopupMenu(v, position);

            String positi = marcaList.get(position).getnombre();
            Integer positid = marcaList.get(position).getId();

            Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + position);

            Toast.makeText(mCtx,"Seleccionados dispositivos de la marca "+positi, Toast.LENGTH_SHORT).show();

            SharedPreferences prefs3 =
                    mCtx.getSharedPreferences(MISDATOS, Context.MODE_PRIVATE);

            SharedPreferences.Editor editor3 = prefs3.edit();
            editor3.putString("nombreMarcaNuevoDisp",positi);
            editor3.putInt("idMarcaNuevoDisp",positid);
            editor3.apply();

        }

    }
}

A: You can use following way,
Add field for fragment and change your adapter constructor like this,
private MarcasFragment fragment;
public MarcasAdapterNuevoDisp(MarcasFragment fragment, List<Marca> marcaList) {
    this.mCtx = fragment.getActivity();
    this.fragment = fragment;
    this.marcaList = marcaList;

}

Then in your onclick method,
@Override
public void onClick(View v) {
    fragment.textView.setText(yourString); //As your textview is public, you can access it from here.
}

A: you can create an Interface and use the interface to setText in your textview like this:-
Interface :-
 public interface IOnItemClickListener {
        void onItemClick(String text);
    }

use Interface in fragment and pass this iOnItemClickListener in your adapter constructor:-
private IOnItemClickListener iOnItemClickListener = new IOnItemClickListener() {
        @Override
        public void onItemClick(String text) {

          yourTextView.setText(text);

        }
    };

and in your adapter create an object in your adapter :-
private IOnItemClickListener iClickListener;

public SearchAdapter(Context ctx, IOnItemClickListener iClickListener, ArrayList<SearchResponse> arrayList) {
        this.ctx = ctx;
        **this.iClickListener = iClickListener;**
        this.arrayList = arrayList;
    }

and when your click on item;-
holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iClickListener.onItemClick("pass your text");
            }
        });