text:
Q: Cómo seleccionar aleatoriamente más de dos valores en un array en JS Soy nuevo en Javascript y queria saber como puedo obtener más de 2 valores que sean totalmente aleatorios de este array

let frutas = ['manzana','banana','uva','sandía','melón']

A: Puedes hacer uso de la Función Math.random() que te devolverá un número aleatorio entre 0 y 1, haciendo uso de esta función, puedes multiplicarlo por el máximo número aleatorio que quieres tener y redondearlo con la ayuda de Math.floor(), el código se vería de la siguiente manera:
Math.floor((Math.random() * 5)); // arroja un número random
Ahora, si lo que quieres es 2 números random de tu array, solo deber generar dos números random y usarlos como índice de tu array. De la siguiente manera:

let frutas = ['manzana','banana','uva','sandía','melón'];
let random1 = Math.floor((Math.random() * 5) );
let random2 = Math.floor((Math.random() * 5) );

console.log(frutas[random1]);
console.log(frutas[random2]);

A: Si lo que quieres es obtener 2 o más elementos distintos del array, recomiendo mejor es desordenar el array, y luego coger la cantidad de elementos que necesites:

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function randomElements(array, quantity) {
  return shuffleArray([...array]).slice(0, quantity);
}
let frutas = ['manzana','banana','uva','sandía','melón', 'pera', 'naranja', 'piña'];

console.log(randomElements(frutas,2));
console.log(randomElements(frutas,4));
console.log(randomElements(frutas,6));

A: Te recomiendo indagar el metodo Math.random(), este mismo genera un valor aleatorio, el cual si lo combinas con el metodo Math.floor() o Math.ceil() vas a poder redondearlo hacia arriba o abajo, dependiendo de lo que quieras. Luego podes multiplicar ese valor para que el numero este dentro del largo de los elemtos del Array.
Dominando eso el paso siguiente es que generes ese numero aleatorio entre 0 y el total de elementos.
Te dejo esto como ejemplo para que puedas darte una idea y no sea tan abstracto.

for(let i=0;i<5;i++){
    //Math.ceil()redondea el numero que generas con Math.random(), y lo colocas dentro de los parentesis ()
    let numeroAleatorio= Math.ceil(Math.random()*5)
    //Lo multiplicas por el numero hasta el cual queres llegar, en este ej, puse 5
    console.log(numeroAleatorio);
}


text: Q: Customer can't register an account during order process,redirect to the shopping cart page Everyone thought it was an old one.Actually, it is.magento 1.9.1.0,When I checked out, clicking on my account was redirected back to the shopping cart page.It's not just this version, I've installed 1.9.x and most of them will.But I looked for a lot and still couldn't find a solution.Any friends know, please help me, thank you very much!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to reference a primary key in Ms Access VBA behind a report I would like to reference the Primary key on the continuous long summary report on my VBA code see below so that I get the correct results per total. The report was combined using domain functions, there is no ISSUE here in terms of performance all is perfect even if there are huge queries to do the actual calculations.
The report has grouped sales data for each salesman coming from unrelated tables & queries, thanks the domain functions has helped to construct this report accurately and with quality performance.
Problems:
I want now to have the final total for all salesmen, but if I reference the subtotal per each salesman, it only picks the value for the first salesman throughout, that is why I want to reference the primary which is based from the salesmen table and visible on the report. On the report I'm using this code below on-load event:
VBA Code
Me.txtsalestotal = Me.finalTotal

I'm putting the code above behind the report, but it keeps on picking the same value for one salesman to all salesmen, that's I why a primary key referencing is required here.
I think if I can be helped to know how to reference the primary key (which is Visible on the report) on the above code, then it will sort out this problem for good.

A: Here is my well researched answer to this problem:
Because of the domain functions that were used to summarize the report, then the sum function is now rendered irrelevant, meaning it can never be used on a non-bound control unless a control is bound directly to the record source in this case a query.
Solution
(1) Create a new control from any of participating tables with the correct data type in this numbers
(2) Include this control as part of the main record source query, the one which supplies the main data to the report in question.
(3) In the main report assign this control with the un-bound calculate value as its record source, Ms Access will treat it as a normal native control like any other queries controls.
(4) Then to have the cumulative figures just apply the in-belt report running total and hide it
(5) Finally add another control in the page footer and then reference the hidden control, problem solved!


text:
Q: King on reduced chessboard $2\times 2$ moving randomly, what is the probability that it ends up in one of the corners after $1000$ moves? As mentioned in the title, we have a chessboard $2\times2$, the king moves with equal probability to each square on the chessboard. King begins from the left upper corner. What is the approximate probability that the king will be standing in the bottom right corner after a thousand moves? I know how to solve it when the number of steps goes to infinity, which would make the probability $1/4$. But is there any trick to do it for a $1000$ moves or is it just "relatively" large number so that I would use my method to solve it as $n$ goes to infinity?

A: The following is a Markov chain approach, since OP tagged it:
There are two states: 1) Not being in the bottom right corner, and 2) being in brc. The transition matrix is $$A=\begin{pmatrix}2/3&1\\1/3&0\end{pmatrix}$$ What is being asked is the value of $$p=\begin{pmatrix}0&1\end{pmatrix}\cdot A^{1000}\begin{pmatrix}1\\0\end{pmatrix}=\frac{1}{4}\begin{pmatrix}0&1\end{pmatrix}\begin{pmatrix}1&-1\\1&3\end{pmatrix}\begin{pmatrix}1&0\\0&(-\frac{1}{3})^{1000}\end{pmatrix}\begin{pmatrix}3&1\\-1&1\end{pmatrix}\begin{pmatrix}1\\0\end{pmatrix}=\frac{1}{4}\left(1-\frac{1}{3^{1000}}\right)$$ The column $(1,0)$ refers to the starting state of 1) and the left-most $(0,1)$ refers to the end-state 2), with a thousand transitions in between.

A: After $n$ moves, the probabilities of the three squares other than the starting square are equal by symmetry. Let $p_n$ be the probability of being in the lower right square after $n$ moves. Then the probability of being in the upper left after $n$ moves is $1-3p_n$.
We can find a simple recursion here. To reach the lower right square on the $(n+1)$th move, we must be in one of the other three squares (probability $1-p_n$) after the $n$th move, and then make the correct move from there (probability $\frac13$). Thus $p_{n+1}=\frac13(1-p_n)$.
If $e_n=p_n-\frac14$, we then get $e_{n+1}+\frac14=\frac13(\frac34-e_n)=\frac14-\frac13e_n$, so $e_{n+1}=-\frac13 e_n$. Since $p_0=0$ and $e_0=-\frac14$, we get $e_{1000}=-\frac14\cdot \left(-\frac13\right)^{1000}=\frac{-1}{4\cdot 3^{1000}}$ and $p_{1000}=\frac14-\frac{1}{4\cdot 3^{1000}}=\frac{3^{1000}-1}{3^{1000}\cdot 4}$.
There it is. Exact, even.


text:
Q: Unable to Get Correct User Online Presence I have an app in which I want to check my users' online presence. Right now, when I check, it tells me everyone is offline.
The users grant user_online_presence and offline_access (plus a few other) permissions to the app. Then I store the access token. I am able to access any information I need at any time except for the online presence.
To get the online presence, I first set the access token:

$facebook->setAccessToken($user['AccessToken']);

Then I query Facebook:

$fql = "SELECT uid, name, online_presence, status FROM user WHERE uid = ".$user['FacebookID'];
  $param = array('method' => 'fql.query', 'query' => $fql, 'callback' => '');
  $fqlResult = $facebook->api($param);

When I check the results, I get the id, name, and status, but everyone is listed as offline, even me when I know I'm online and active:

[online_presence] => offline

Any help getting this working would be greatly appreciated. Thank you all for your time.

A: I used this FQL query sucessfully :-
SELECT name,online_presence FROM user WHERE uid
IN (SELECT uid2 FROM friend WHERE uid1 = me())

to get all the online friends. Got output as "idle","active" and "offline". All values of which were absolutely correct.

A: There are 2 permits

*

*user_online_presence, for the user

*friends_online_presence, for friends

http://developers.facebook.com/docs/reference/api/permissions/

A: online_presence is for chat online, not facebook online

The user's Facebook Chat status. Returns a string, one of active,
  idle, offline, or error (when Facebook can't determine presence
  information on the server side). The query does not return the user's
  Facebook Chat status when that information is restricted for privacy
  reasons.

Also, I ran fql?q=SELECT name, online_presence FROM user where uid IN (Select uid1 from friend WHERE uid2=me()) and it listed my friend's online status fairly accurately. Only a very few were incorrect.  Maybe that's due to a lag in the facebook update system, or maybe they're caching the information for too long, etc.


text:
Q: Distance between two lines
Find the distance between the lines $l_1:$ $x=1+4t,y=5-4t,z=-1+5t$ and $l_2:x=2+8t,y=4-3t,z=5+t$

So the approach in general is to find a vector that is orthogonal to 2 planes that the lines are in them.
I saw that the cross product is used to find this vector as in the following:
$$\begin{vmatrix}
\hat{i} & \hat{j} & \hat{k}  \\
4 & -4 & 5 \\
8 & -3 & 1  \\
\end{vmatrix}=11\hat{i}+36\hat{j}+20\hat{k}$$
How can the cross product be used here? why does it give a vector that is  orthogonal to 2 planes?

A: Because a line joining a point from one of the lines to a second point from the other line will be the shortest when it is perpendicular to both lines. Perpendicular to a line, means perpendicular to its generating vector, i.e. coefficients of its equation. And in three dimension all vectors that are simultaneously perpendicular to two vectors are multiples of their cross-product (when those vectors are not parallel.)


text:
Q: Layout handle for onepage checkout I want to have a specific CSS file at the onepage checkout and I was simply wondering if there is a layout handle for that (so I don't have to make one).
Probably answered my own question, but I found this in my search: http://itpscan.info/blog/magento/layout_handles.php
Might come in handy for other people searching for default XML handles

A: Here is the one page check out index  handler
<checkout_onepage_index>
By default you this is the handler you can find this handler in layout folders checkout.xml file
I think you know the xml code for adding the css if you not then tell me I will update the code

A: Rather than changing directly in checkout.xml it is good if you create local.xml in your layout folder and add your xml code there as it is the best practice to make your custom changes separately.
Below will be the code in your local.xml
<layout version="0.1.0">
    <checkout_onepage_index translate="label">
        <reference name="head">
            <action method="addCss"><stylesheet>css/yourstyle.css</stylesheet></action>
        </reference>
    </checkout_onepage_index>
</layout>


text:
Q: Intel x86 emulator starts but android doesn't boot I want to run my app on a emulator api level 10 using Intel HAX technology. I've downloaded the HAXM package from sdk manager and installed it. I've also enabled the "Virtualization technology" in BIOS setting (Reading this thread) but when start the emulator screen keeps black and android doesn't boot/start. Here's the Avd message on starting emulator:

Please help me, I've no idea what's wrong!
(My pc config: Windows 7 - 64bit, 4gig RAM, intel M 520 2.4 GHz, working on eclipse)
Edit:
Here is the console messages after running emulator:
[2014-01-11 12:14:24 - BabbageTuring] ------------------------------
[2014-01-11 12:14:24 - BabbageTuring] Android Launch!
[2014-01-11 12:14:24 - BabbageTuring] adb is running normally.
[2014-01-11 12:14:24 - BabbageTuring] Performing com.illinois.babbageturing.MainActivity activity launch
[2014-01-11 12:14:28 - BabbageTuring] Launch canceled!
[2014-01-11 12:14:47 - SDK Manager] Updated AVD '480x800' based on Android 2.3.3, Intel Atom (x86) processor,
[2014-01-11 12:14:47 - SDK Manager] with the following hardware config:
[2014-01-11 12:14:47 - SDK Manager] hw.sdCard=no
[2014-01-11 12:14:47 - SDK Manager] hw.device.manufacturer=Generic
[2014-01-11 12:14:47 - SDK Manager] hw.mainKeys=yes
[2014-01-11 12:14:47 - SDK Manager] hw.lcd.density=240
[2014-01-11 12:14:47 - SDK Manager] hw.accelerometer=yes
[2014-01-11 12:14:47 - SDK Manager] hw.dPad=no
[2014-01-11 12:14:47 - SDK Manager] hw.device.hash=1318766497
[2014-01-11 12:14:47 - SDK Manager] hw.trackBall=yes
[2014-01-11 12:14:47 - SDK Manager] hw.device.name=3.7in WVGA (Nexus One)
[2014-01-11 12:14:47 - SDK Manager] hw.camera.back=none
[2014-01-11 12:14:47 - SDK Manager] hw.sensors.proximity=yes
[2014-01-11 12:14:47 - SDK Manager] hw.battery=yes
[2014-01-11 12:14:47 - SDK Manager] disk.dataPartition.size=200M
[2014-01-11 12:14:47 - SDK Manager] hw.gpu.enabled=yes
[2014-01-11 12:14:47 - SDK Manager] hw.audioInput=yes
[2014-01-11 12:14:47 - SDK Manager] hw.sensors.orientation=yes
[2014-01-11 12:14:47 - SDK Manager] hw.gps=yes
[2014-01-11 12:14:47 - SDK Manager] skin.dynamic=yes
[2014-01-11 12:14:47 - SDK Manager] hw.keyboard=no
[2014-01-11 12:14:47 - SDK Manager] vm.heapSize=32
[2014-01-11 12:14:47 - SDK Manager] hw.ramSize=512

A: I am on Windows 7 too and can't get API 10 to work with the Intel x86 image, unless I set the RAM to 768 (max for Windows and far more than devices had then) and turn off "Use Host GPU".

A: Please make sure you have the right x86 image installed corresponding to the API level. You can find x86 image distribution here
I have seen that decreasing the RAM size works, when the system is running low on RAM. 512MB would be ideal in most scenarios. Please enable "Use Host GPU" and make sure you are selecting x86 from the drop down box on AVD.
Refer to this article for more information

A: You are trying to use API Level 10?  The minimal requirements for HAXM is API level 17.  Here are some links that might be helpful to look at:
https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows
https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm

A: To use the graphics acceleration feature make sure you have
Android SDK Tools - Revision 17 +
Android SDK Platform API 15 - Revision 3+
Download the intel x86 images from http://www.intel.com/software/android
Click on tools and navigate to bottom of the page for the details
I hope you have already installed intel HAXM and its running else please refer https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows
Moreover, it worked for me only when I checked Use Host GPU option.
I know I am late but I hope it will help the new users like me.

A: Have you downloaded Intel x86 Atom System Image? That's the image required for running on HAX


text:
Q: SoapAction header missing when using CXF I have a WSDL file from outside WS that i'm connecting to. And I'm trying to get it working with CXF (works fine with JAX-WS). But I'm getting error from other system. So I decided to take a look at data we're sending to that system and only diffrence is that CXF sets empty SOAPAction http header.
I took some reading and looks like only known solutions is pointing to WSDL directly. But I already did that.
Anyone has a clue about this?
<bean id="object" class="xxx.XxxObject" factory-bean="objectFActory"
      factory-method="create"/>

<bean id="objectFActory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
    <property name="serviceClass" value="xxx.XxxObject"/>
    <property name="wsdlLocation" value="http://blebleble"/>
    <property name="address" value="http://blebleble"/>
    <property name="username" value="user"/>
    <property name="password" value="password"/>
    <property name="properties">
        <map>
            <entry key="javax.xml.ws.session.maintain" value-type="java.lang.Boolean" value="true"/>
        </map>
    </property>
</bean>

Headers:
POST /somepath HTTP/1.1
Content-Type: text/xml; charset=UTF-8
Accept: */*
Authorization: Basic <randomhex>
SOAPAction: ""
User-Agent: Apache CXF 2.7.6
Cache-Control: no-cache
Pragma: no-cache
Host: somehost:8080
Connection: keep-alive
Content-Length: 2791

A: None of this is CXF specific.  It is all standard JAX-WS.
You can use the action property of the @WebMethod annotation to set a SOAP action.  For example
@WebMethod(operationName = "TestOperation", action="http://example.org/TestOperation")

If you are using wsimport to generate artifacts from the WSDL, you should already have this set in your @WebService annotated interface.

A: I was able to replicate the behavior you described (SOAPAction header is "") using an invocation like this:
MyPortService service = new MyPortService();
MyPort port = service.getMyPortSoap11();
MyRequest request = new MyRequest();
MyResponse response = port.subscription( request );

Here are the HTTP Headers from TCP Dump using this invocation:
POST /MyService/services HTTP/1.1
Content-Type: text/xml; charset=UTF-8
Accept: */*
SOAPAction: ""
User-Agent: Apache CXF 2.7.6
Cache-Control: no-cache
Pragma: no-cache
Host: redacted
Connection: keep-alive
Content-Length: 377

I tried adding an out interceptor and ensuring that the SOAPAction was set as a header, but no matter what I tried that did not cause the SOAPAction to be sent as part of the HTTP request.
I then found a lead in this thread and reformatted my invocation:
ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
factory.setServiceClass( MyPort.class );
factory.setAddress( "http://www.host.com/service" );
factory.setServiceName( new QName( targetNamespace, wsdlBindingName ) );
Object myService = factory.create();
org.apache.cxf.endpoint.Client client = ClientProxy.getClient( myService );
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("SOAPAction", Arrays.asList("mySoapAction"));
client.getRequestContext().put(Message.PROTOCOL_HEADERS, headers);
client.invoke( operationName, request );

Here are the HTTP Headers from TCP Dump of an invocation in this style:
POST /MyService/services HTTP/1.1
Content-Type: text/xml; charset=UTF-8
Accept: */*
SOAPAction: mySoapAction
User-Agent: Apache CXF 2.7.6
Cache-Control: no-cache
Pragma: no-cache
Host: redacted
Connection: keep-alive
Content-Length: 377

Hope this helps.

A: If it's still actual. Faced same problem and wrote interceptor. It's quite universal:
public class SoapActionInterceptor extends AbstractSoapInterceptor {
    private static final String SLASH = "/";

    public SoapActionInterceptor() {
        super(Phase.POST_LOGICAL);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {

        BindingOperationInfo bindingOperationInfo = message.getExchange().getBindingOperationInfo();
        OperationInfo operationInfo = bindingOperationInfo.getOperationInfo();
        InterfaceInfo interfaceInfo = operationInfo.getInterface();
        QName interfaceInfoNameQName = interfaceInfo.getName();
        QName operationQName = operationInfo.getName();

        Map<String, List<String>> reqHeaders = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));

        if (reqHeaders == null) {
            reqHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        }

        if (reqHeaders.size() == 0) {
            message.put(Message.PROTOCOL_HEADERS, reqHeaders);
        }

        reqHeaders.put(SoapBindingConstants.SOAP_ACTION, Arrays.asList(interfaceInfoNameQName.getNamespaceURI() + SLASH + interfaceInfoNameQName.getLocalPart() + SLASH + operationQName.getLocalPart()));
    }
}

To use it in Spring + Apache CXF:
<jaxws:client id="client" serviceClass="some.generated.webservice.Interface"
              wsdlLocation="/META-INF/wsdl/webservice.wsdl"
              address="http://example.address/service">
    <jaxws:outInterceptors>
        <bean class="some.package.interceptor.SoapActionInterceptor"/>
    </jaxws:outInterceptors>
</jaxws:client>

A: I found another cause of this issue, so I thought I would go ahead and post this answer in case it helps someone.
After creating a SOAP Service, WSDL-first, and generating the service interface and related classes from the XSD, I found that the soap action I was setting in my wsdl was not showing up in the CXF-generated WSDL (which you can get to by adding '?wsdl' to your service endpoint and putting that in your browser).
ex: http://localhost:8080/mywar/services/myservice?wsdl
The cause of this issue for me was that I did not properly annotate the service implementation class. Although the generated interface had the appropriate annotations on it, the implementation class was the cause of my issue.
I had to add the following to my service implementation class to resolve the issue:
@WebService(
    targetNamespace="...",
    portName="...",
    endpointInterface="...",
    serviceName="...")
Hope this helps someone...


text:
Q: VB.NET - Get second hyperlink from string and set as LinkLabel text property I have a tool that takes in an email and sorts the data into the appropriate fields. In the email, there are normally two hyperlinks that launch the ticket editor in IBM notes. One is a local link and one is a server link. The following code is able to get the local link as it is the first hyperlink that contains 'notes://' but I need to get the one for the server as well, which also starts with 'notes://".
   For i = 0 To lines.Count + 1
            If lines(i).StartsWith("notes://") Then
                StartLine = i
                Exit For
            End If
        Next
        link_OpenRequestUsingNotes.Text = lines(StartLine)

I thought of writing some code to check the line about it to see if it matches a specific string, maybe with Regex?
For the local link it needs to look for:
"using a Notes client (local replica)"
For the server link it needs to look for:
"using a Notes client (Server):"
The hyperlink is below this text so it would need to look for those and then get the text on the next line.
These links are then set as the text for two link labels that the users can press and go to that link.
If someone could please help me find a way to get the server link, it would be greatly appreciated.

A: You can use this code:
link_OpenRequestUsingNotes_Local.Text = "" 'fields for local link
link_OpenRequestUsingNotes_Server.Text = "" 'field for server link

For i = 0 To lines.Count - 1

    If lines(i).StartsWith("using a Notes client (local replica)") Then
        link_OpenRequestUsingNotes_Local.Text = lines(i + 1)
    ElseIf lines(i).StartsWith("using a Notes client (Server)")
        link_OpenRequestUsingNotes_Server.Text = lines(i + 1)
    End If

    If link_OpenRequestUsingNotes_Local.Text <> "" AndAlso link_OpenRequestUsingNotes_Server.Text <> "" Then
        Exit For
    End If

Next i

A: You could use code like this to find the first two links:
Dim notes = Function(x) x.StartsWith("notes://")
Dim index As Integer = lines.FindIndex(notes)
If index <> -1 AndAlso index < (lines.Count - 1) Then
    Dim firstLink As String = lines(index + 1)
    ' ... do something with "firstLink"...
    Debug.Print(firstLink)

    index = lines.FindIndex(index + 2, notes)
    If index <> -1 AndAlso index < (lines.Count - 1) Then
        Dim secondLink As String = lines(index + 1)
        ' ... do something with "secondLink"...
        Debug.Print(secondLink)
    End If
End If

A: I managed to fix it myself
Just add 1 to i (StartLine = i + 1) to go to the line below!
  'Notes Server Link
    For i = 0 To lines.Count - 1
        If lines(i).StartsWith("Click here to open the request using a Notes client (Server):") Then
            StartLine = i + 1
            Exit For
        End If
    Next
    link_OpenServerLink.Text = lines(StartLine)


text:
Q: How to edit this table data to become a link i am using a table on my website for products.
At the moment only the image is clickable but i want the whole line or at least all the information in the table to be linking to the productpage.
The image has this and works as a link to the productpage:

        <a href="<?php the_permalink() ?>" target="_blank" class="thumbnail alignleft"><img src="<?php
            if (has_post_thumbnail($post->ID))
            {
                $img_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail');
                echo woof_aq_resize($img_src[0], get_tpl_option('tpl_3_img_width', $options), get_tpl_option('tpl_3_img_height', $options), true);
            } else
            {
                echo WOOF_LINK . 'img/not-found.jpg';
            }
            ?>" alt="<?php the_title() ?>" />

Now i am trying to do the same thing for all the other info in the table wich have code like this:
<?php
    $product = new WC_Product(get_the_ID());
    echo $product->get_attribute('pa_voedings-spanning-dcac');
    ?>

Or even better make the whole line of the table a link. Thank you for your time,
Sjoerd

A: You can simply wrapp each cell content with a "a" balise like this:

    <?php $product = new WC_Product(get_the_ID()); ?>
    <a href="<?php the_permalink() ?>" target="_blank">
      <?php echo $product->get_attribute('pa_voedings-spanning-dcac'); ?>


text:
Q: Why does `basic_ios::swap` only do a partial swap?
C++11 §27.5.4.2/21:
void swap(basic_ios& rhs);
Effects: The states of *this and rhs shall be exchanged, except that rdbuf() shall return the same value as it returned before the function call, and rhs.rdbuf() shall return the same value as it returned before the function call.

What is this partial swapping useful for?
Can it cause trouble?

A: You can blame me for this one.  The committee has tried to change (twice I think), but each time the solution ended up breaking things.
Swap and move semantics was retrofitted onto our I/O system a decade after it was designed.  And it wasn't a perfectly clean fit.
Note that basic_ios::swap is a protected member function and there is no namespace-scope variant.  Thus this can only be called from a derived class (typically istream/ostream).  Note that i/o_stream::swap is also protected and with no namespace-scope variant.  And their spec is to call the base class swap and then swap any local data (such as the gcount in istream).
Finally up at the string/filestream level you get what you would consider a "normal" swap: public member and namespace-scope variants.  At this level you've got a data member string/file buffer (the rdbuf) and the base class.  The swap at this level simply swaps the base and data members.
The complicating characteristic of all this is that the rdbuf() down in the base class is actually a self-referencing pointer to the derived class's streambuf (basic_filebuf or basic_stringbuf) and that is why you don't want the base class to swap these self-referencing pointers.
This makes the base swap weird, but everyone is protected from it except the derived clients.  And the code for the derived client's swap is subsequently deceptively simple looking.  And at the derived level, swap is made public and behaves in the manner that public clients expect it to.
A similar dance is made for move construction and move assignment.  Move construction is further complicated by the fact that the base class is a virtual base, and thus its constructor is not called by the most directly derived class.
It was fun.  It looks weird.  But it ultimately works. ;-)
Slight Correction:
Alberto Ganesh Barbati is responsible for protecting swap at the i/ostream level.  It was a very good call on his part that I had completely missed with my first design.

A: I only have one speculative answer...
If the author assumed that a stream may use an internal buffer (for example a char buffer[50] data member), then this provision is necessary as obviously the content of the buffers may be swapped, but their address will remain unchanged.
I do not know whether it is actually allowed or not.


text:
Q: Unable to load dll dependency config file We have service which is running on IIS app pool, for our scenario we started consuming a library (not owned by us), library has few dlls and some config and binary files which needs to be loaded during runtime. We are bin placing all dlls and dependent model files to web app bin folder. Found that during runtime due to shadow copy enabled, dlls are getting copied to C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files but not copying any of dependent config and model files which is causing issue at run time.
Anyone know how we can force dependency to also get copied or any other way to resolve this issue?
Checked other thread as well and suggestion was disable shadow copy using below settings but I want to avoid this.
<hostingEnvironment shadowCopyBinAssemblies="false" />


text:
Q: Microsoft Fabric WebAPI communication A question perhaps silly, but I'm not sure where to start digging.
I have an app based on Microsoft Fabric SDK, there two stateless WebAPI services and one ASP.NET Core for Web UI  - just front end. Apparently, UI calls WebAPI's for it needs.
However sometimes one of stateless WebAPI need to communicate with another stateless WebAPI service without UI liaising. Should it make a call over http (what would be an address then), is there simpler way? Is my architecture crap?
Thanks


text:
Q: Is it possible for a Chrome extension to access an IndexedDB database created by a specific domain? If http://example.com/ creates an IndexedDB database, is it possible for a Chrome extension (used on domains other than example.com) to open and query this database?

A: No, you can not do it. The data storage is sandboxed http://www.html5rocks.com/en/tutorials/offline/storage/

A: Yes, IndexedDB can be accessed through chrome extension with the help of content scripts. Content Scripts can access the indexedDB storage of the domain you have specified in manifest.json file.
For more info check here:
https://stackoverflow.com/a/60002682/9131807


text:
Q: How to test the laravel Mailer using Phpunit I need to test the Laravel Mailer using PHPunit, I am using CRUD Operations, where if any one the method fails, It should trigger the mail. I need to test the mail part, below is the code.
 public function index()
    {

        $response = Http::withBasicAuth(userName,passWord)
            ->get(connection());
        $this->html_mail($response);
        return $response->json();
    }

 public function show($id)
    {
      $response = Http::withBasicAuth(userName, passWord)
            ->get(connection());
        // check response & send mail if error
        $this->html_mail($response);
        $record = collect($response->json() ['output'])
            ->where($this->primaryKeyname, $id)->first();
        return $record;
    }

Mailer method:
 public function html_mail($response)
    {
        if ($response->failed() || $response->serverError() || $response->clientError()) {
            Mail::send([], [], function ($message) use ($response) {
                $message->to('foo@example.com');
                $message->subject('Sample test');
                $message->setBody($response, 'text/html');
            });
        }

        return 'Mail Sent Successfully';
    }
}

Could someone please help to test the Mailer method  using PHPunit.
Thanks.

A: It looks like there might be some code missing in your examples, but generally you're looking for Laravel's Mail::fake() method:
# tests/Feature/YourControllerTest.php

use Illuminate\Support\Facades\Mail;

/**
 * @test
 */
public function index_should_send_an_email_if_authentication_fails(): void
{
    Mail::fake();

    $this->withToken('invalidToken', 'Basic')
        ->get('your.route.name');

    Mail::assertSent(function ($mail) {
        // Make any assertions you need to in here.
        return $mail->hasTo('foo@example.com');
    });
}

There's also an opportunity to clean up your controller methods here by leveraging middleware for authentication rather than repeating it in every method.
Digging into Illuminate\Auth\SessionGuard, Laravel automaticallys fire an Illuminate\Auth\Events\Failed event if authentication fails. Instead of sending directly from your controller, you might consider registering an event listener and attaching it to that event, then letting the listener dispatch a mailable notification.
# app/Providers/EventServiceProvider

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Auth\Events\Failed' => [
        'App\\Listeners\\FailedAuthAttempt',
    ],
];

With those changes, your testing also becomes easier:
# tests/Feature/Notifications/FailedAuthAttemptTest.php

use App\Notifications\FailedAuthAttempt;
use Illuminate\Notifications\AnonymousNotifiable;
use Illuminate\Support\Facades\Notification;

/**
 * @test
 */
public function it_should_send_an_email_upon_authentication_failure(): void
{
    Notification::fake();

    $this->withToken('invalidToken', 'Basic')
        ->get('your.route.name');

    Notification::assertSentTo(new AnonymousNotifiable(), FailedAuthAttempt::class);
}

Now, any route in your application that uses Laravel's auth.basic middleware will automatically send the FailedAuthAttempt notification upon failure. This also makes it easier to, for example, send these notices to a Slack channel rather than sending emails.


text:
Q: Не работает форма для регистрации Есть форма для регистрации, но про нажатии на кнопку ничего не происходит.
Код формы:
<!DOCTYPE html>

    <title>index</title>

<form action="javascript:login()" method="post">
<input name="emailLogin" type="text" id="emailLogin" value=""/>
<input name="pswLogin" type="password" id="pswLogin" value=""/>
<input type="submit" name="Submit" value="Login"/>
</form>

ajax_framework.php:
    function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();

/* ----------------------- */
/*      LOGIN              */
/* ----------------------- */
/* Переменная nocache содержит случайное число, добавляемое в запрос
   для предотвращения кеширования браузером запроса */
var nocache = 0;
function login() {
 // Отображаем соощение в области ID ajax_response
 document.getElementById('login_response').innerHTML = "Loading..."
    // Проверяем, что все поля не пустые. Используем encodeURI() для кодирования недопустимых символов в запросе.
var email = encodeURI(document.getElementById('emailLogin').value);
var psw = encodeURI(document.getElementById('pswLogin').value);
 // Получаем случайное число
nocache = Math.random();
 // Pass the login variables like URL variable
http.open('get', 'login.php?email='+email+'&psw='+psw+'&nocache = '+nocache);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply() {
if(http.readyState == 4){
var response = http.responseText;
 if(response == '0'){
// if login fails
  document.getElementById('login_response').innerHTML = 'Login failed! Verify user and password';
// else if login is ok show a message: "Welcome + the user name".
  } else {
document.getElementById('login_response').innerHTML = 'Welcome'+response;
  }
}

login.php :
    <?php include('config.php');

// Verify if user exists for login
if(isset($_GET['email']) && isset($_GET['psw'])){

$email = $_GET['email'];
$psw = $_GET['psw'];

/*$getUser_sql = 'SELECT * FROM USER WHERE email="'. $email . '" AND psw = "' . $psw . '"';
$getUser  = mysql_query($getUser_sql);
$getUser_result =  mysql_fetch_assoc($getUser);
$getUser_RecordCount = mysql_num_rows($getUser);*/
$proof_email = mysqli_query($link, "SELECT * FROM users WHERE email = '$email' ");
$getUser_result =  mysql_fetch_assoc($proof_email);
if($getUser_RecordCount = 1){ echo '0';} else { echo "Good";}
}
?>

config.php :
    <?php
 $link = mysqli_connect(
            'localhost',  /* Хост, к которому мы подключаемся */
            'root',       /* Имя пользователя */
            '',   /* Используемый пароль */
            'hentai');

?>

A: Код в файле ajax_framework.js синтаксически неверный - в нем отсутствует завершающий }. Проверьте сообщения в консоли разработчика Вашего браузера - в нем вы увидете Uncaught SyntaxError: Unexpected end of input.
Проверить js-код, на корректность, можно линтером, например тут


text:
Q: Add photo Bucket to my phpfox site I need to add photo bucket in to my site. i already added flicker photo import module in my site. But need to add photo bucket as well.
How can i do this?
need some help.
Thanks
Akila

A: Sounds like you mean a photobucket slideshow.  You can create your slideshow here:
http://photobucket.com/slideshows

A: I think you are looking for slider on HTML pages.
Have a look at the following tutorials to apply photo slider on your images.
http://www.buildinternet.com/project/supersized/
http://www.dreamcss.com/2009/04/create-beautiful-jquery-sliders.html
Hope this will Help..
Thanks!
Hussain


text:
Q: How to get the right http file length with qt? I want to get the url "https://iso.mirrors.ustc.edu.cn/qtproject/archive/qt/5.11/5.11.1/qt-opensource-windows-x86-5.11.1.exe" file's length with Qt,
but QNetworkAccessManager request cannot get the Content-Length。 the content is
This page requires JavaScript. Please wait 2 seconds.

if I add the cookie="addr=113.57.128.130" to request manually, I can get the right things。 what should I do to get the file length?

A: Try this example :
widget.h
public:
    void requestFileSize(const QString &url);
    QNetworkAccessManager *m_netmanager;
    QNetworkReply *m_reply;

public slots:
    void fileSize();

widget.cpp
void Widget::requestFileSize(const QString &url)
{
    QNetworkRequest req;
    m_netmanager = new QNetworkAccessManager(this);
    req.setUrl(QUrl(url));
    m_reply = m_netmanager->get(req);
    connect(m_reply, SIGNAL(metaDataChanged()), this, SLOT(fileSize()));
}

void Widget::fileSize()
{
    qDebug() << "Content Length: " << m_reply->header(QNetworkRequest::ContentLengthHeader).toString();
    m_reply->deleteLater();
    m_netmanager->deleteLater();
}

Now call :
requestFileSize("https://as5.cdn.asset.aparat.com/aparat-video/c6f1e63e310060e70574f1692c2322395584619-360p__37462.mp4");

Output in byte :
Content Length:  "12186677"

And its approximately 11.6 MB
I test it with some urls but i dont know why with this url https://iso.mirrors.ustc.edu.cn/qtproject/archive/qt/5.11/5.11.1/qt-opensource-windows-x86-5.11.1.exe always return 0.


text:
Q: Improve my $(\epsilon, \delta)$ proof of absolute value function continuity In Charles C. Pugh's Real Mathematical Analysis [2nd Ed] on page 76, continuity of $f : x \mapsto \lvert x \rvert$ on $\mathbb{R}$ is a corollary of another theorem. However, I wanted to see if I could use the $(\epsilon, \delta)$-condition to prove its continuity. My proof below seems overly complicated; if you can find any ways to improof it, please let me know!

Conclusion. We want to show that for any $\epsilon > 0$ and any $x \in \mathbb{R}$, there exists a $\delta >0$ such that if $y \in \mathbb{R}$ then the following holds:
$$ \lvert y - x \vert < \delta \implies \bigl\lvert |y| - |x| \bigr\rvert < \epsilon , $$
i.e., $\lvert * \rvert$ is continuous.
Proof. Choose $\delta := \epsilon$. We want to show that $\bigl\lvert |y| - |x| \bigr\rvert \leq \lvert y - x \vert < \delta = \epsilon$. There are 8 cases to consider:

*

*$|y| > |x|$
a) $y > 0, x > 0$
b) $y > 0, x < 0$
c) $y < 0, x > 0$
d) $y < 0, x < 0$

*The same four cases but with $|x| < |y|$.

Without loss of generality, we prove case 1. For each sub-case, $|y| > |x|$ implies $|y| - |x| > 0$, so $\bigl\lvert |y| - |x| \bigr\rvert = |y| - |x|$.
1.a) Note that $y - x > 0$. Hence
$$ \bigl\lvert |y| - |x| \bigr\rvert = y - x = | y - x | . $$
1.b) Note that since $x < 0$, we have $y + x < y - x$. Note also that $y - x > 0$. Hence
$$ \bigl\lvert |y| - |x| \bigr\rvert = y - (-x) = y + x < y - x = | y - x | . $$
1.c) Note that since $x > 0$, we have $-y + x > -y - x$. Note also that $x - y > 0$. Hence
$$ \bigl\lvert |y| - |x| \bigr\rvert = -y - x < x - y = | x - y | = | y - x |. $$
1.d) Note that since $-y < -x$ we have $x - y < 0$. Hence
$$ \bigl\lvert |y| - |x| \bigr\rvert = -y - (-x) = x - y < |x - y| = | y - x | . $$
Therefore all cases satisfy $\bigl\lvert |y| - |x| \bigr\rvert \leq \lvert y - x \vert < \epsilon$, as required.

I think it is possible to structure the proof so that, using symmetry, only two cases need to be proved.

A: Let's show that
$$
||x|-|y|| \leq |x-y|
$$
for any $x,y \in \mathbb{R}$. Indeed, by the triangle inequality, we have
\begin{align}
|x| &= |x - y + y| \\
&\leq |x-y| + |y|,
\end{align}
which implies $|x| - |y| \leq |x-y|$. Exchanging $x$ and $y$ leads to $|y| - |x| \leq |x-y|$. Hence, the inequality is established. Can you simplify your proof from here?


text:
Q: JQuery button click only works 1st time I have the below JQuery code on a Rails 5 app.  Works fine if I check the box the first time.  Also works fine if I uncheck the same checkbox.  But when I reclick the same box I initially clicked, it no longer checks off the box.   Anything I'm missing in my code below?
$(".filter-wrapper-f").click(function(){
    var $checkbox = $(this).children(".checkpic");
    if ($checkbox.attr('checked')){
        $checkbox.removeAttr('checked');
    } else {
        $checkbox.attr('checked', true);
    }
});

I've also tried this and it won't work to start with.
$(".filter-wrapper-f").click(function(){
var $checkbox = $(this).children(".checkpic");
    if ($checkbox.prop('checked', true)){
        $checkbox.removeProp('checked');
    } else {
        $checkbox.prop('checked', true);
    }
});

A: As per the jQuery docs, prop should be used to set the checked attribute.
$checkbox.prop('checked', true)
Explanation here: https://stackoverflow.com/a/5876747/5551783


text:
Q: When and why to use mysqli_fetch_row, mysqli_fetch_object, mysqli_fetch_assoc, mysqli_fetch_array I understand in some way the differences between mysqli_fetch_row, mysqli_fetch_object, mysqli_fetch_assoc and mysqli_fetch_array.
My question is if they are so similar (if they are really almost the same as many topics say) which should we use?
Why should we use the preferred one and is there some performance difference?
I have read some people say never to use mysqli_fetch_array. I am confused. I am reading now some PHP books and all the examples include it. If this is incorrect is it better for me to stop using it while exercising and use something else that you could explain and recommend?
I have also read that these are equal:
mysqli_fetch_array( $result, MYSQLI_ASSOC ) = mysqli_fetch_assoc( $result )
mysqli_fetch_array( $result, MYSQLI_NUM ) = mysqli_fetch_row( $result )
mysqli_fetch_array ( $result ) = mysqli_fetch_assoc( $result ) + mysqli_fetch_row( $result )

If they are equal as a concept, are there performance differences? Which should we use? Are the differences because of performance reasons or for the developer's convenience?
I strongly believe that these differences have a big reason and they have different usage and cases, but I cannot find where to use different functions and syntax.

A: These lines from the documentation on php.net are key:

mysqli_fetch_array() is an extended version of the mysqli_fetch_row()
  function. In addition to storing the data in the numeric indices of
  the result array, the mysqli_fetch_array() function can also store the
  data in associative indices, using the field names of the result set
  as keys.

http://www.php.net/manual/en/mysqli-result.fetch-array.php
In cases where two or more columns have the same name the only way to reference the first occurence(s) of that column is by numerical index. In these cases you need mysqli_fetch_row or mysqli_fetch_array with either MYSQLI_BOTH or MYSQLI_NUM as its second argument (in procedural usage).
mysqli_fetch_assoc($result) is just shorthand for mysqli_fetch_array($result, MYSQLI_ASSOC).
mysqli_fetch_object does what you expect: It returns a row of results as an object. Use of this over mysqli_fetch_assoc is a matter of whether an object or an array better represents the record being handled. The object can be of whatever class you want - stdClass is the default.

A: I dont think there is a huge differents, its only that you need only one function to do the same ;)


text:
Q: VMware Fusion 11 macOS monterey : No internet access on guest OS Not able to access internet on guest OS VMware Fusion 11 with mac OS 12 Monterey. The network adapter used is "share with my mac" same works for mac OS 11 but not working on 12. Is shows self-assigned IP.
Any work around?

A: In this release, if we don't use the NIC type 'vmxnet3', we will have issues getting an IP Address in the VM. Locate the below (search "virtualDev" or "e1000e") in your VM's VMX file (option+right click on your VM, select "Open config file in editor".
ethernet0.virtualDev = "e1000e"

Replace "e1000e" with "vmxnet3".
ethernet0.virtualDev = "vmxnet3"

Once that's done, restart the VM. If this doesn't work, rebuild your VM with this option set from the start.
I have a blog on this topic which should get you going. https://blog.eucse.com/how-to-run-macos-monterey-12-beta-in-vmware-fusion/


text:
Q: how to set boolean value to a variable inside an array and check for that value using node js? I want to set a boolean value "true" to a variable inside the flags[ ]. Then when all the variables inside the flags[ ] are true, I need to do an operation.
Please find my code below.
var flags = [terminationFlag,transferFlag,jrCancelledFlag,jrFilledFlag,jrOpenFlag,miegFlags,headcountFlag,replacementReqFlag,costcentreFlag,gradeMapFlag]

var arguments = ["terminationReport - 2019-1", "transferReport - 2019-1", "jrCancelledReport - 2019-1", "jrFilledReport - 2019-1", "jrOpenReport - 2019-1","MIEGReport - 2019-1", "HeadCountReport - 2019-1","ReplacementReport - 2019-1","CostcentreReport - 2019-1","GradeMapReport - 2019-1"]

for (i=0; i < arguments.length ;i++){
    console.log("arguments : "+ arguments[i]);
    request('http://localhost:3000/query/CheckKey/'+arguments[i], function (error, response, body) {
        var result = JSON.stringify(response.body).replace(/[^a-zA-Z ]/g, "");
        if (result == "yes"){
            console.log("record found ****************");
            flags[i]=true;
            console.log("flags : "+ flags);
        }
       if flags = true {
           //do operation
        }
    });

}

But it is not working. Please help me in solving this issue.

A: If you want to check whether every element in flags is true, use Array.every():
if (flags.every(flag => flag)) {...}

Or if your browser doesn't support ES6:
if (flags.every(function(flag) {
    return flag;
})) {...}

A: This is probably because you're running an asynchronous operation inside for loop. Since you haven't declared i, it's created as a global variable. The for loop just fires the requests and won't wait for the callbacks to run. By the time request is done, the value of i is changed to something else and you end up assigning true to wrong flag items. So, change it to:
arguments.forEach((arg, i) => {
  console.log("arguments : " + arg);
  request('http://localhost:3000/query/CheckKey/' + arg, function(error, response, body) {
    var result = JSON.stringify(response.body).replace(/[^a-zA-Z ]/g, "");
    if (result == "yes") {
      console.log("record found ****************");
      flags[i] = true;
      console.log("flags : " + flags);
    }
    if flags = true {
      //do operation
    }
  });
})

Or use let:
for (let i=0; i < arguments.length ;i++){

}

A: There are 2 issues here.
First, this for-loop should use let to iterate especially when you use asynchronous function(s) inside the loop because each iteration will hold the i value for each loop.
for (let i=0; i < arguments.length ;i++){

Second,
if flags = true {
    //do operation
}

You have to use any form of loop to check if all of the flags in the flags array are true. You could use Array.every like in Jack Bashford's answer.
I recommend an ordinary for-loop since it is better performance-wise.
let allFlagsTrue = true
for (let j = 0; j < flags.length; j++){
    if (flags[i] === false){
        allFlagsTrue = false
    }
}
if (allFlagsTrue){
    // Do your operations
}


text:
Q: Converting tuple into records in blank feature class using ArcPy? Here is the code block that I am using with ArcGIS 10.2 for Desktop, it all works great except for the bottom part. I am not sure how to turn the tuple into records on a blank feature class. The tuple looks like this: ('BRONTE DR', 'BRONTE DR', 'RICHARDSON DR', 'RICHARDSON DR'). I want each part of the tuple to be a new record in the blank feature class.
import re
import arcpy
from arcpy import env
arcpy.env.overwriteOutput = True
if arcpy.Exists(r"J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb\street_assets2"):
    arcpy.Delete_management(r"J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb\street_assets2")
arcpy.env.workspace = r'J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb'
table1 = r"street_assets"
field1 = r"STREET_OR_INTERSECTION"
def unique_values(table, field):
    with arcpy.da.SearchCursor(table, [field]) as cursor:
        return sorted({row[0] for row in cursor})
newtuple = unique_values(table1,field1)
newtuple = str(newtuple)
newtuple = newtuple.split("}{")
newtuple = ([s.replace('\'', '') for s in newtuple])
newtuple = ([s.replace('"', '') for s in newtuple])
newtuple = ([s.replace('u', '') for s in newtuple])
newtuple = ([s.replace('[', '') for s in newtuple])
newtuple = ([s.replace(']', '') for s in newtuple])
newtuple = ([s.replace('{', '') for s in newtuple])
newtuple = ([s.replace('}', '') for s in newtuple])
out_path = r"J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb"
out_name = "street_assets2"
geometry_type = "POINT"
template = r"J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb\street_assets"
has_m = "DISABLED"
has_z = "DISABLED"
spatial_reference = arcpy.Describe(r"J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb\street_assets").spatialReference
arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type, template, has_m, has_z, spatial_reference)
newtuple = tuple(newtuple)
print newtuple

## Problem Here

cursor = arcpy.da.InsertCursor(r"J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb\street_assets2", ['STREET_OR_INTERSECTION'])
i = 0
for i in newtuple:
    cursor.insertRow([i])
    i = i + 1

A: When working with cursors, each row is a tuple. In your case, you need to create a tuple with one value.
cursor = arcpy.da.InsertCursor(r"J:\STW\Divisions_&_Branches\MSMD\Branches_&_Sections\GIS\users\Anault\intersections_software_development\OUTPUT.gdb\street_assets2", ['STREET_OR_INTERSECTION'])
for i in newtuple:
    #create tuple with one value
    row = (i,)
    cursor.insertRow(row)
del cursor


text:
Q: How is best to cache a Panda dataframe in Redis Cluster I am retrieving a big set of data from BigQuery and performing some sort of data transformation on it and storing my data in a Panda dataframe.
Since this data doesn't need to be retrieved again from the database every time, I want to cache it to avoid recalling the database and performing the same sort of transformation again.
Let's assume that the data is bigger than 512 MB which is the string value limitation in Redis.
I am considering using Redis Cluster to distribute this caching process, but I don't know how I should store the data.
There are two ways that I can think of for this purpose:

*

*Based on this thread and this one, we can compress the dataframe using zlib and store it in a key. In this case, I am not sure when the data is greater than 512MB, Redis is automatically splitting it in the cluster nodes?

*Storing each row of the dataframe as a key in the Redis. In this case, I am not sure how to read the data back as a Panda dataframe again.


text:
Q: Java.lang.reflect.InvocationTargetException when Mock AccountManager through Dagger Provide. How to fix? In my dagger, I want to provide a mock Account Manager
@Provides
@Singleton
AccountManager provideAccountManager(Context context) {
    return Mockito.mock(AccountManager.class);
}

I go the below crash when it runs Mockito.mock(AccountManager.class), as below
    java.lang.ExceptionInInitializerError
    at org.mockito.internal.creation.jmock.ClassImposterizer.createProxyClass(ClassImposterizer.java:85)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:62)
    at org.mockito.internal.creation.jmock.ClassImposterizer.imposterise(ClassImposterizer.java:56)
    at org.mockito.internal.creation.CglibMockMaker.createMock(CglibMockMaker.java:23)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:26)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:51)
    at org.mockito.Mockito.mock(Mockito.java:1243)
    at org.mockito.Mockito.mock(Mockito.java:1120)
    at com.mypackage.app.test.TestAndroidServicesModule.provideAccountManager(TestAndroidServicesModule.java:118)
    at com.mypackage.app.test.TestAndroidServicesModule_ProvideAccountManagerFactory.get(TestAndroidServicesModule_ProvideAccountManagerFactory.java:31)
    at com.mypackage.app.test.TestAndroidServicesModule_ProvideAccountManagerFactory.get(TestAndroidServicesModule_ProvideAccountManagerFactory.java:10)
    at dagger.internal.DoubleCheck.get(DoubleCheck.java:47)
    at au.com.mypackage.utils.AccountUtil_Factory.get(AccountUtil_Factory.java:71)
    at au.com.mypackage.utils.AccountUtil_Factory.get(AccountUtil_Factory.java:13)
    at dagger.internal.DoubleCheck.get(DoubleCheck.java:47)
    at au.com.mypackage.utils.ShortcutUtil_Factory.get(ShortcutUtil_Factory.java:41)
    at au.com.mypackage.utils.ShortcutUtil_Factory.get(ShortcutUtil_Factory.java:9)
    at dagger.internal.DoubleCheck.get(DoubleCheck.java:47)
    at au.com.mypackage.app.ui.main.MainActivity_MembersInjector.injectMembers(MainActivity_MembersInjector.java:76)
    at au.com.mypackage.app.ui.main.MainActivity_MembersInjector.injectMembers(MainActivity_MembersInjector.java:13)
    at com.mypackage.app.test.DaggerResiTestComponent.inject(DaggerResiTestComponent.java:1814)
    at au.com.mypackage.app.ui.main.MainActivity.onCreate(MainActivity.java:113)
    at android.app.Activity.performCreate(Activity.java:6679)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.support.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:532)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
    Caused by: org.mockito.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:238)
    at org.mockito.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145)
    at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:117)
    at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:109)
    at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:105)
    at org.mockito.cglib.proxy.Enhancer.<clinit>(Enhancer.java:70)
    ... 35 more
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at org.mockito.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:385)
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:220)
    ... 40 more
    Caused by: java.lang.UnsupportedOperationException: can't load this type of class file
    at java.lang.ClassLoader.defineClass(ClassLoader.java:594)
    ... 43 more

    Test running failed: Instrumentation run failed due to 'Process crashed.'

Did I miss something?

A: Based on David Rawson's comment, I change my dependency from
androidTestCompile 'org.mockito:mockito-all:1.9.5'

To
androidTestCompile 'org.mockito:mockito-android:2.7.22'

That fix the problem!


text:
Q: CopyFileEx wrapper parameters I have recently had to change from using File.Copy() to CopyFileEx and I am struggling to find how to use it.
After a lot of googling I found this nice wrapper to use it, but what I need is to get the progress of the copied bytes of the current file, and if possible calculate the progress of copying all files I pass to it.
(I know there are projects that have progress bars linked to CopyFileEx but I'm not experienced enough to pull out the relevant code, and I would like to use this wrapper).
Presumably just by comparing it to the total bytes of the files to be copied, which I would find beforehand, and working out the percentage from that.
My current method of copying is
FileRoutines.CopyFile(new FileInfo("source.txt"), new FileInfo("dest.txt"));

What I am stuck on is how to overload it with the parameter's needed to get the progress info.
public sealed class FileRoutines
{
    public static void CopyFile(FileInfo source, FileInfo destination)
    {
        CopyFile(source, destination, CopyFileOptions.None);
    }

    public static void CopyFile(FileInfo source, FileInfo destination,
        CopyFileOptions options)
    {
        CopyFile(source, destination, options, null);
    }

    public static void CopyFile(FileInfo source, FileInfo destination,
        CopyFileOptions options, CopyFileCallback callback)
    {
        CopyFile(source, destination, options, callback, null);
    }

    public static void CopyFile(FileInfo source, FileInfo destination,
        CopyFileOptions options, CopyFileCallback callback, object state)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (destination == null)
            throw new ArgumentNullException("destination");
        if ((options & ~CopyFileOptions.All) != 0)
            throw new ArgumentOutOfRangeException("options");

        new FileIOPermission(
            FileIOPermissionAccess.Read, source.FullName).Demand();
        new FileIOPermission(
            FileIOPermissionAccess.Write, destination.FullName).Demand();

        CopyProgressRoutine cpr = callback == null ?
            null : new CopyProgressRoutine(new CopyProgressData(
                source, destination, callback, state).CallbackHandler);

        bool cancel = false;
        if (!CopyFileEx(source.FullName, destination.FullName, cpr,
            IntPtr.Zero, ref cancel, (int)options))
        {
            throw new IOException(new Win32Exception().Message);
        }
    }

    private class CopyProgressData
    {
        private FileInfo _source = null;
        private FileInfo _destination = null;
        private CopyFileCallback _callback = null;
        private object _state = null;

        public CopyProgressData(FileInfo source, FileInfo destination,
            CopyFileCallback callback, object state)
        {
            _source = source;
            _destination = destination;
            _callback = callback;
            _state = state;
        }

        public int CallbackHandler(
            long totalFileSize, long totalBytesTransferred,
            long streamSize, long streamBytesTransferred,
            int streamNumber, int callbackReason,
            IntPtr sourceFile, IntPtr destinationFile, IntPtr data)
        {
            return (int)_callback(_source, _destination, _state,
                totalFileSize, totalBytesTransferred);
        }
    }

    private delegate int CopyProgressRoutine(
        long totalFileSize, long TotalBytesTransferred, long streamSize,
        long streamBytesTransferred, int streamNumber, int callbackReason,
        IntPtr sourceFile, IntPtr destinationFile, IntPtr data);

    [SuppressUnmanagedCodeSecurity]
    [DllImport("Kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    private static extern bool CopyFileEx(
        string lpExistingFileName, string lpNewFileName,
        CopyProgressRoutine lpProgressRoutine,
        IntPtr lpData, ref bool pbCancel, int dwCopyFlags);
}

public delegate CopyFileCallbackAction CopyFileCallback(
    FileInfo source, FileInfo destination, object state,
    long totalFileSize, long totalBytesTransferred);

public enum CopyFileCallbackAction
{
    Continue = 0,
    Cancel = 1,
    Stop = 2,
    Quiet = 3
}

[Flags]
public enum CopyFileOptions
{
    None = 0x0,
    FailIfDestinationExists = 0x1,
    Restartable = 0x2,
    AllowDecryptedDestination = 0x8,
    All = FailIfDestinationExists | Restartable | AllowDecryptedDestination
}

Any pointers really appreciated.

A: The wrapper already has the plumbing needed to handle the progress.  Just implement the code to update your progress bar in CallbackHandler before the return.  The progressBar1.Maximum defaults to 100, so the code below will calculate the percentage.
Replace your current CopyFile call with this:
CopyFileCallbackAction myCallback(FileInfo source, FileInfo destination, object state, long totalFileSize, long totalBytesTransferred)
{
    double dProgress = (totalBytesTransferred / (double)totalFileSize) * 100.0;
    progressBar1.Value = (int)dProgress;
    return CopyFileCallbackAction.Continue;
}

FileRoutines.CopyFile(new FileInfo("source.txt"), new FileInfo("dest.txt"), myCallback);

A: If you just want to show a progress bar for a file copy, you can do this.  It uses the Windows standard dialog that shows a progress bar and time remaining, and it has a Cancel button.  It was just what I needed in basically one line of code.
// The following using directive requires a project reference to Microsoft.VisualBasic.
using Microsoft.VisualBasic.FileIO;

class FileProgress
{
    static void Main()
    {
        // Specify the path to a folder that you want to copy. If the folder is small,
        // you won't have time to see the progress dialog box.
        string sourcePath = @"C:\Windows\symbols\";
        // Choose a destination for the copied files.
        string destinationPath = @"C:\TestFolder";

        FileSystem.CopyDirectory(sourcePath, destinationPath,
            UIOption.AllDialogs);
    }
}


text:
Q: Hibernate @ManyToOne Cascade Mix Recently I've been developing a base project and came across a scenario. Let's say I have a School with a list of Users that might have a new or an existing address, as the following mapping:
@Table("school") @Entity
class School {
    @OneToMany(cascade=CascadeType.ALL, mappedBy="school")
    private List<User> students;
}

@Table("user") @Entity
class User {
    @ManyToOne
    @JoinColumn(...)
    private School school;

    @ManyToOne(cascade=?)
    @JoinColumn(...)
    private Address address;
}

@Table("address") @Entity
class Address { ... } // No bi-directional relationship

Whenever I try to persist I got the outputs:

*

*If the School has only Users with a new address and the cascade type is set to ALL or PERSIST, saving a new instance of School works as expected.

*If the School has only Users with existing address and the cascade type omitted, it works as expected when saving a new School.

*When saving a new instance of School containing Users  with new and existing address and the CascadeType is set to ALL, the following exception is thrown org.hibernate.PersistentObjectException: detached entity passed to persist.(I understand because the list has saved address)

*When saving a instance of School with mixed Users having new and existing address but no cascade type set, a transient exception is thrown, as expected.
I wonder if there's a solution other than saving every user address before saving School object.


text:
Q: ERROR TypeError: firebase.messaging is not a function I'm getting error, ERROR TypeError: firebase.messaging is not a function
Whats wrong with it ?

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth} from 'angularfire2/auth';
import * as firebase from 'firebase/app';

import 'rxjs/add/operator/take';
import { BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class MessagingService {

messaging = firebase.messaging();
currentMessage = new BehaviorSubject(null);

constructor(private db: AngularFireDatabase, private afAuth:
AngularFireAuth) {
}

private updateToken(token) {
  this.afAuth.authState.take(1).subscribe(user => {
    if (!user) { return; }

    const data = { [user.uid]: token };
    this.db.object('fcmTokens/').update(data);
  });
}

getPermission() {
    this.messaging.requestPermission()
        .then(() => {
            console.log('Notification permission granted.');
            return this.messaging.getToken();
        })
        .then(token => {
            console.log(token);
            this.updateToken(token);
        })
        .catch((err) => {
            console.log('Unable to get permission to notify.', err);
        });
}

receiveMessage() {
    this.messaging.onMessage((payload) => {
        console.log('Message received. ', payload);
        this.currentMessage.next(payload);
    });
  }
}

ERROR TypeError: firebase.messaging is not a function

I'm having big probleems with that error, I don't have any idea how to fix that, please help me repair that code. I've done everything like an example, but it doesn't work. thank you so much for your answers.

A: Try changing
import * as firebase from 'firebase/app';
to
import * as firebase from 'firebase';


text:
Q: Why are my links in html ul li not working? I'm currently trying to build my first website (homework). For my dropdown menu, I used Dev Ed's tutorial for a dropdown menu, and it is working except that I can't click on the links in the dropdown bits.
(the mouse coursor still changes into that hand-symbol though)
How can I fix this?

nav {
  grid-column: 1/5;
  background: #2E3045;
  justify-content: center;
  border-radius: 10px;
}

nav a,
button {
  text-decoration: none;
  font-size: 1.7vw;
  font-family: Bahnschrift, sans-serif;
  color: #DFB830;
  font-weight: bold;
}

/* horizontal-menu */

.menu {
  height: auto;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

/* styling horizontal-menu buttons */

.dropdown button,
.dd-buttons {
  background: none;
  border: none;
  cursor: pointer;
  text-transform: uppercase;
  padding-top: 1%;
  padding-bottom: 1%;
}

.menu button:hover,
.dd-buttons:hover {
  color: #ECEEFF;
}

/* styling the dropdown arrow */

@media only screen and (max-width: 480px) {
  .menu img {
    max-width: 7px;
    height: auto;
    display: inline-block;
  }
}

@media only screen and (min-width: 481px) {
  .menu img {
    max-width: 15px;
    height: auto;
    display: inline-block;
  }
}

/* dropdown list */

.dropdown {
  position: relative;
}

.dropdown ul {
  position: absolute;
  background: #DFB830;
  margin-top: 8px;
  min-width: 150%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: column;
  list-style: none;
  border-radius: 5px;
  opacity: 0;
  pointer-events: none;
  transition: all 0.4s ease;
  transform: translateY(10px);
}

/* styling dropdown menu list items */

.dropdown li {
  width: 100%;
  height: 100%;
  line-height: 250%;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.4s ease;
}

.dropdown a {
  font-size: 1.5vw;
  color: #2E3045;
}

/* when hovering over dropdown list */

.dropdown li:hover {
  background-color: #E9CF72;
}

.dropdown button:focus+ul {
  opacity: 1;
  pointer-events: all;
  transform: translateY(0px);
}

    <button class="dd-buttons">YouthDuo</button>
    <button class="dd-buttons">Galactic Spirit</button>

      <button>Feng Shui </button>

Feng Shui Basics

CD's and DVD's

Books and EBooks

      <button>Color Alchemy </button>

Living in Color

Guided Training

Jami Lin's Products

A: remove the pointer-events:none
.dropdown ul {
    position: absolute;
    background: #DFB830;
    margin-top: 8px;
    min-width: 150%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: column;
    list-style: none;
    border-radius: 5px;
    opacity: 0;
    transition: all 0.4s ease;
    transform: translateY(10px);
}


text:
Q: Scheme function that returns shortest of its list arguments I am trying to create a scheme function that will return the shortest of its list of arguments.
(shortest '(1 2) '(2 3 4) '(4) '(5 6 7 8)) should compile (4).
This is what I have so far...
(define (shortest lst) (foldl (lambda (e r) (if (or (not r) (< e r)) e r))
     #f
     lst))

It gives error arity mismatch.

A: Your answer is close to be correct, but you need to actually compare the lengths of the sublists, and make sure that your procedure accepts a variable number of arguments. This should work, with minimum changes:
; the . is for accepting multiple args
(define (shortest . lst)
  (foldl (lambda (e r)
           ; notice how we compare the lengths
           (if (or (not r) (< (length e) (length r))) e r))
         #f
         lst))

It works as expected:
(shortest '(1 2) '(2 3 4) '(4) '(5 6 7 8))
=> '(4)

(shortest '())
=> '()

(shortest)
=> #f

A: Your function has only one argument named lst, but you call it on variable number of lists. So, you should decide which input do you expect:

*

*List of lists

(define (shortest lst)
  (if (null? lst) lst
      (car (sort lst
                 (lambda (l1 l2)
                   (< (length l1) (length l2)))))))

(shortest '((1 2) (2 3 4) (4) (5 6 7 8)))
(shortest '())

*Variable number of lists

(define (shortest . args)
  (if (null? args) args
      (car (sort args
                 (lambda (l1 l2)
                   (< (length l1) (length l2)))))))

(shortest '(1 2) '(2 3 4) '(4) '(5 6 7 8))
(shortest '())

A: One interesting thing to ask is: can you solve this problem without taking the length of all the lists?  If you have a list with a million elements and one with four, do you really need to compute the length of the huge list to know the answer?
Well, the answer is no, you don't.  Here's one approach to doing this:
(define (shortest . args)
  (define (step tail-pairs new-tail-pairs)
    ;; step has a list of pairs of tail & original-list pairs it is looking at,
    ;; and another list of pairs of (cdr tail) & original-list which it will
    ;; look at on the next cycle.
    (if (null? tail-pairs)
        ;; Run out of things to look at, start on the next cycle
        (step new-tail-pairs '())
        (let ((this-tail-pair (first tail-pairs))
              (more-tail-pairs (rest tail-pairs)))
          (if (null? (car this-tail-pair))
              ;; found it: nothing left in this list so return the original
              ;; list
              (cdr this-tail-pair)
              ;; Not empty: add this tail pair with its first element removed to
              ;; the next cycle list, and loop on the remains of this cycle
              (step more-tail-pairs (cons (cons (cdr (car this-tail-pair))
                                                (cdr this-tail-pair))
                                          new-tail-pairs))))))
  ;; build the initial list of tail pairs and start stepping down it.
  (step (map cons args args) '()))


text:
Q: Vim; Executing another application by :MyCommand I want to execute "go install" in current directory (where currently open document resides) with a command (Like :GoInstall).
How can I do that?
Note: I want to see the output of that command too.
I have added command Goin execute "go install" to _gvimrc and _vimrc (I am on Windows), but it does not work - says it's not an editor command - or gives E488 and I am not sure it is being executed in current directory.
UPDATE:
After some struggling to know Vim better and mostly by googling I ended up with this _gvimrc file which works perfectly (at least for me). It adds three commands Gon, Gob and Gor to run go install, go build and go run current_file.go and shows the result in another document (buffer) in Vim. Hope it helps somebody else who is a Vim beginner:
set guifont=Lucida_Console:h11
colorscheme dejavu
set tabstop=4

filetype plugin on
filetype plugin indent on
syntax on

" causes vim opens maximized in windows (@least)
au GUIEnter * simalt ~x

set autochdir
set number

" this made my vim life (as a begginer at least) much happier!
" thanks to @ http://vim.wikia.com/wiki/Display_output_of_shell_commands_in_new_window bottom of the page
function! s:ExecuteInShell(command, bang)
    let _ = a:bang != '' ? s:_ : a:command == '' ? '' : join(map(split(a:command), 'expand(v:val)'))

    if (_ != '')
        let s:_ = _
        let bufnr = bufnr('%')
        let winnr = bufwinnr('^' . _ . '$')
        silent! execute  winnr < 0 ? 'belowright new ' . fnameescape(_) : winnr . 'wincmd w'
        setlocal buftype=nowrite bufhidden=wipe nobuflisted noswapfile wrap number
        silent! :%d
        let message = 'Execute ' . _ . '...'
        call append(0, message)
        echo message
        silent! 2d | resize 1 | redraw
        silent! execute 'silent! %!'. _
        silent! execute 'resize ' . line('$')
        silent! execute 'syntax on'
        silent! execute 'autocmd BufUnload <buffer> execute bufwinnr(' . bufnr . ') . ''wincmd w'''
        silent! execute 'autocmd BufEnter <buffer> execute ''resize '' .  line(''$'')'
        silent! execute 'nnoremap <silent> <buffer> <CR> :call <SID>ExecuteInShell(''' . _ . ''', '''')<CR>'
        silent! execute 'nnoremap <silent> <buffer> <LocalLeader>r :call <SID>ExecuteInShell(''' . _ . ''', '''')<CR>'
        silent! execute 'nnoremap <silent> <buffer> <LocalLeader>g :execute bufwinnr(' . bufnr . ') . ''wincmd w''<CR>'
        nnoremap <silent> <buffer> <C-W>_ :execute 'resize ' . line('$')<CR>
        silent! syntax on
    endif
endfunction

command! -complete=shellcmd -nargs=* -bang Shell call s:ExecuteInShell(<q-args>, '<bang>')
cabbrev shell Shell

command! -complete=shellcmd -nargs=* -bang Gor call s:ExecuteInShell('go run %', '<bang>')
command! -complete=shellcmd -nargs=* -bang Gon call s:ExecuteInShell('go install', '<bang>')
command! -complete=shellcmd -nargs=* -bang Gob call s:ExecuteInShell('go build', '<bang>')

:map <F5> :Gor<CR>
:map <F6> :Gob<CR>
:map <F7> :Gon<CR>

Note: You have to set up at least GOROOT and GOPATH env-vars on your system.

A: :execute is for built-in Ex commands, you want the :! command to execute an external command:
:!go install

It appears that the 'makeprg' option would be beneficial here, too. Compilation is such a frequent task that vi / Vim have a trigger mechanism built-in. If you
:set makeprg=go

you can trigger the build with :make install.

To change to the current directory, either use
:cd %:h

or (to always to this automatically):
:set autochdir


text:
Q: Parsing an FQL result I'm using FQL to get the names of the nearest 5 places like so:
- (void)facebookPlaces {

    NSString *query = @"SELECT name FROM place WHERE distance(latitude, longitude, \"39.750655\", \"-104.999127\") < 500 ORDER BY distance(latitude, longitude, \"23.750655\", \"-180.999127\") limit 5";

    // Set up the query parameter
    NSDictionary *queryParam = @{ @"q": query };
    // Make the API request that uses FQL
    [FBRequestConnection startWithGraphPath:@"/fql"
                                 parameters:queryParam
                                 HTTPMethod:@"GET"
                          completionHandler:^(FBRequestConnection *connection,
                                              id result,
                                              NSError *error) {
                              if (error) {
                                  NSLog(@"Error: %@", [error localizedDescription]);
                              } else {
                                  NSLog(@"Result: %@", result);
                                  // Store the result in an NSData object
                                  NSData *nameData = [result data];
                                  NSLog(@"Test data reads: %@", nameData);

                              }
                          }];

The result is neatly returned like this:
Result: {
    data =     (
                {
            name = "T|aco";
        },
                {
            name = "ChoLon Bistro";
        },
                {
            name = "Illegal Pete's Lodo";
        }, etc...

I stored the data in an NSData object and it reads the exact same way. I would like to parse the result in a way that I can get all of the names in a simple way, and print them to the log. The only way that I could think of was manually parsing the NSData or the result, but I have no idea how to make it only take the stuff in the quotes next to name =. I'm very new to FQL and objective-c, does anyone know how I can do this?
When I researched this, I saw an awesome JSON example that took everything next to name = and stored it in an array. Although it was meant for android and I couldn't figure out how to make it work in iOS. That is ideally what I'm trying to do.

A: The result is being parsed as a JSON object into an NSDictionary.  You can tell because the result object starts with {}.  Inside the data key you see an array (denoted by ()).
So to get an array of names you can do this:
NSMutableArray *names = [NSMutableArray array];
for (NSDictionary *item in result[@"data"]) {
    [names addObject:item[@"name"]];
}

Is this what you're after?


text:
Q: rails 3 link_to with nested content_tag to create Hi I got a noob question, I want to create the following HTML result:
TEXT

In the above HTML I want to have text with a span-class to style in an image via css.
When I try the following implementations the result reflects just one part of the needed implementation:
<%= link_to "TEXT", controller_path, :class => "button-big layer" %>

results in:
TEXT

and
<%= link_to(content_tag(:span, "", :class => "arrow-big"), controller_path, :class => "button-big layer") %>

results in:

Does anyone know how to accomplish?

A: You could also nest tags by using alternative syntax for link_to helper
<%= link_to controller_path, :class=> "button-big layer" do %>
  Text
  <%= content_tag(:span, "", :class => "arrow_big" %>
<% end %>

A: Reading your question I did solve my problem.
Than I propose another way to answer your question.
You could create a helper method to make this kind of link that you need.
It would be something like this
def link_with_text_and_span(href, text, span_options= {}, link_options = {})
    span_tag = content_tag(:span, span_options[:content] || '', :class => span_options[:class] || '')
    link_to(span_tag, href, :class => link_options[:class] || '')
  end

The good about it is that your view will be cleaner.
Then you can just call this helper method in your view
  <%= link_with_text_and_span("/controller/action", "TEXT", {class: 'arrow-big'}, class: button-big) %>

PS: This code can be improved for sure, if other users want to, please do it.

A: Here's another way you could use without the content_tag. Not the cleanest but it works!
<%= link_to ''.html_safe, controller_path, class: "button-big layer" %>

A: Simply concatenate your text with the 'span':
<%= link_to(("TEXT" + content_tag(:span, "", :class => "arrow-big")).html_safe,
             controller_path,
             :class => "button-big layer") %>

You'll need the .html_safe around the concatenation since the + operator will otherwise escape the HTML of the content_tag.


text:
Q: Cast variable changes variable name - SQL I'm a total newb to SQL and am confused about why the variable name is changing when I try to cast a variable as text rather than numeric.
I'm using RSQLite and I would like to extract a few columns from my dbi connection and cast a few of the variable as type text.
Here is my code:
head5_query <- dbSendQuery(con,"SELECT studyid,
candidategroup,
submissionmonth,
submissionyear,
CAST(membercounty AS TEXT),
CAST(serviceprovidercounty AS TEXT),
CAST(admissionsource AS TEXT)
FROM medicalClaims WHERE studyid IS NOT NULL AND dateofservicetomonth = 1 AND dateofservicetoyear = 2011 LIMIT 5")
head_query = dbFetch(head5_query,n = -1)
head_query

which gives me:
> head_query
    studyid candidategroup submissionmonth submissionyear CAST(membercounty AS TEXT) CAST(serviceprovidercounty AS TEXT)
1 145311.10              1               2           2014                    Bristol                             Suffolk
2  36458.10              1               5           2014                    Suffolk                             Suffolk
3  12403.17              1               2           2014                       <NA>                             Suffolk
4  12403.16              1               2           2014                       <NA>                             Suffolk
5  12403.15              1               2           2014                       <NA>                             Suffolk
  CAST(admissionsource AS TEXT) medicalclaimid apcdidcode
1                          <NA>       22778326          4
2                           2.0       46829274          0
3                           1.0       64643334          0
4                           1.0       64643334          0
5                           1.0       64643334          0

Where the variable name has changed to CAST(membercounty AS TEXT), for example.  However, it appears that variable type has changed to text:
> class(head_query$`CAST(admissionsource AS TEXT)`)
[1] "character"

How do I change the variable type without changing the variable name?
Thanks so much!

A: You need to ALIAS your columns (they're not variables in your SELECT statement)  when using a function to modify them.
https://www.tutorialspoint.com/sqlite/sqlite_alias_syntax.htm


text:
Q: Smoothness of the function Suppose $f(x)=x^TAx$, where $A = \begin{bmatrix}100& 0& ...0\\
0&1 &...0\\
...\\
0&0&...1\end{bmatrix}$ is an identity matrix except $A_{11}=100$ instead of 1. How can I compute the smoothness of this function?

A: $A$ is the Hessian of $f$, and it is positive definite, so it is a strictly convex function for all $x$. It is everywhere differentiable, with derivative $\nabla f(x) = 2A'x$. The eigenvalues are on the diagonal, with the largest being 100 and the smallest being 1, so the condition number is 100/1, so I would be aware of the numerical accuracy of matrix calculations if you aren't using closed form solutions.
Is that the kind of thing you are looking for?


text:
Q: React + JS file, Uncaught Error: Minified exception, using Atom + Chrome console I fell this is a very specific error for my current files and since the error in console is Greek to me...
I am not native English speaker. I am trying to put together React and HTML. I have a search form rendered with React in my HTML file. I need the user input in the input-element sent to the function search() in my javascript file. This I have had help with before and it worked fine for a while.
In my JS-file I have the search function. FOR NOW the result render lies there. I do not expect it to work!
My problem is the error I'm getting. It occurs upon hitting the search button. What does it mean? I can't understand it and thus I can't figure out where I'm doing wrong. Where is the error?
I use a downloaded library, I code in Atom and use Chrome's console.
Below are code + error.

> Uncaught Error: Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.
    at r (react.min.js:16)
    at c._renderValidatedComponent (react.min.js:13)
    at c._updateRenderedComponent (react.min.js:13)
    at c._performComponentUpdate (react.min.js:13)
    at c.updateComponent (react.min.js:13)
    at c.performUpdateIfNecessary (react.min.js:13)
    at Object.performUpdateIfNecessary (react.min.js:15)
    at u (react.min.js:15)
    at r.perform (react.min.js:16)
    at o.perform (react.min.js:16)

        <meta charset="utf-8">
        <title>Inlämningsuppgift 6</title>
        <link rel="stylesheet" type="text/css" href="style.css">

    function search(event) {
  event.preventDefault();
  //Variables
  var movies_list = document.getElementById('movies_list');
  var gifs_list = document.getElementById('gifs_list');

  //Input validation and handling
  if(this.elements.query.value === '') {
    alert("Ange ett sökord!");
  } else {
    var rawInputData = this.elements.query.value;
    var fixedInputData = rawInputData.split(" ");
    var inputData = encodeQueryData(fixedInputData);
    var inputDatagif = encodeQueryDatagif(fixedInputData);

    //URL encoding functions
    function encodeQueryData(data) {
       let ret = [];
       for (let d in data)
         ret.push(encodeURIComponent(data[d]));
       return ret.join('%20');
    }

    function encodeQueryDatagif(data) {
       let ret = [];
       for (let d in data)
         ret.push(encodeURIComponent(data[d]));
       return ret.join('+');
    }

    // Objekt to handle AJAX
    var omdbAPI = new XMLHttpRequest();
    var gifAPI = new XMLHttpRequest();
    //Set URLs
    var omdbURL = "http://www.omdbapi.com/?s=" + inputData + "&type=movie";
    var gifURL = "http://api.giphy.com/v1/gifs/search?q=" + inputDatagif + "&limit=1&api_key=dc6zaTOxFJmzC";

    //Handle search response, validate and act
    omdbAPI.addEventListener("load", function() {
      if (this.responseText === '{"Response":"False","Error":"Movie not found!"}')
      {
        alert("Sökningen gav inget resultat.");
      } else {
        //Convert from JSON
        var result = JSON.parse(this.responseText);
        var entries = result.Search;

        //Loop through recieved object and display result.
        for(var entry_key in entries) {
          //control that property is own by the object (not prototype)
          if(entries.hasOwnProperty(entry_key)) {
              //Access the entry
              var entry = entries[entry_key];
              //Display result
            var movie_line = "
Title: " + entry.Title + " (year: " + entry.Year + ")
";
            console.log(movie_line);
            movies_list.innerHTML += movie_line;
          }
        }
      }
    });

    //Rinse and repeat above for gifs and Giphy API
    gifAPI.addEventListener("load", function() {
      if (this.responseText === '{"Response":"False","Error":"Movie not found!"}')
      {
        alert("Sökningen gav inget resultat.");
      } else {
        var result = JSON.parse(this.responseText);
        var gifs = result.data;

        for(var entry_key in gifs) {
          if (gifs.hasOwnProperty(entry_key)) {
            var gif = gifs[entry_key];
            var gif_line = "";
            gifs_list.innerHTML += gif_line;
          }
        }
      }
    });

    //Send
    omdbAPI.open("get", omdbURL, true);
    omdbAPI.send();
    gifAPI.open("get", gifURL, true);
    gifAPI.send();
  }
}

A: You're using the minified versions of React and ReactDOM, which are only meant to be used when you deploy your application out into the wild. They're a lot smaller and faster, but this comes at the cost of a lot of the nice development features being stripped out. This includes all the error messages, which is why they seem so confusing to you!
To fix this, you should make sure you're using the uncompressed, development versions of React and ReactDOM. While generally you should be using NPM and a module bundler like Webpack to install them into your project (or a scaffolding tool like create-react-app), if you just want to download the files you can do so here:

*

*https://unpkg.com/react/dist/react.js

*https://unpkg.com/react-dom/dist/react-dom.js
Once you've replaced the scripts, you'll be able to see what the actual error message is.

A: Actually your error tell you to develop with the non-minified file, in order to see the real error.
So just replace your script injection (react.min.js => react.js, etc ...)

A: You'll have to set NODE_ENV to development to solve the issue.
set NODE_ENV=development

More conveniently configure your package.json accordingly: "scripts": { "start": "set NODE_ENV=production && node app" }
This is for Windows.


text:
Q: please help me replace string pattern with jquery using a twitter display widget and need to add links to the hash tags. so i need a pattern replacement, replacing each string that starts with a hash/pound sign and ends in a space with the twitter search link. i am pretty clumsy w/jquery--can someone point me in the right direction -- thanks, anyone!
something taking me:
// FROM:

Some nutty tweet. #nutty

A fruity tweet here. #fruity

// TO:

Some nutty tweet. #nutty

A fruity tweet here. http://twitter.com/search?q=%23fruity">#fruity

A: Since you are using jQuery, I would recommend the jQuery Tweetify Text from the CSS-Snippets library.
You would then use it like this (given your code):
$("#tweets li").tweetify();

In addition to matching #hashes, it also turns URL's into hyperlinks, and matches @username and links to their profile.


text:
Q: /Recent does not return LastAccessedDateTime https://graph.microsoft.com/v1.0/me/drive/recent

only returns created time and last modified time from fileSystemInfo in the response as below:
"fileSystemInfo": {
  "createdDateTime": "2018-05-14T10:15:21Z",
  "lastModifiedDateTime": "2018-05-14T10:15:00Z"
}

But not the lastAccessedDateTime as documented.

*

*Does Microsoft Graph Recent API capture and include in its response a read-only file open event?  Or is it limited to only the file modified or uploaded events?

*I can see that FileSystemInfo class has a property called LastAccessedDateTime. If Recent API does not return this, what is the alternative way to query and retrieve it?

A: The lastAccessedDateTime property only applies to consumer OneDrive, not SharePoint or OneDrive for Business. From the documentation:

lastAccessedDateTime is not available for items in SharePoint online or OneDrive for Business.


text:
Q: Using $(this) in .js.erb file - Ruby on Rails AJAX I am using Rails3 with jQuery and attempting to do simple ajax calls. I have a link that displays the current status (online/offline) of an application. When clicked it will update the status.
link_to app.status, { :controller => :apps, :action => :live_status, :id => app }, {:remote => true, :class => "#{app.status} status"}

live_status.js.erb:
$(this).fadeOut();
$(this).parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$(this).fadeIn();

status_link will return the updated link_to
However $(this) isn't working how I envision. How can I update the clicked status with the new status?

A: You should give the element you want to update an ID (I added an element to the hash at the very end):
link_to app.status, { :controller => :apps, :action => :live_status, :id => app }, {:remote => true, :class => "#{app.status} status", :id => app.id}

Now, you can use that same identifier to select the right element with jQuery:
$("#<%= @wowza_app.id %>").fadeOut();
$("#<%= @wowza_app.id %>").parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$("#<%= @wowza_app.id %>").fadeIn();

Of course, this assumes that @wowza_app has a method called id that returns the same ID of the link, but you can modify the variables as necessary to select the element with the right ID.

A: you should use a selector. When you have that code interpreted in the ajax response, jQuery doesn't know what "this" are you referring. Better use something like:
$('#my-special-div').fadeOut();
$('#my-special-div').parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$('#my-special-div').fadeIn();
$('#my-special-div').hide(2000, function () {
    $(this).remove();  // here jQuery knows you are talking about 'my-special-div'
});


text:
Q: X-Frame Options Spring Boot So I'm trying to use configure an iframe on my Spring Boot application. However I'm struggling in getting the X-Frame-Options to ALLOW-From. Here's what I have for my html and spring security file.
HTML IFrame:

Security Config:
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers().authenticated()
        .antMatchers( "/", "/about", "/signup", "/signUpForm",
            "/signUpFormError", "/login", "/logOut", "/ForgotPasswordPage", "/Forgot_Password",
            "/SignUp", "/registrationComplete").permitAll()
        .antMatchers("/LoggedInUser/**").hasAnyAuthority("ADMIN", "USER", "MODERATOR")
        .anyRequest().authenticated().and().csrf().disable().formLogin()
        .loginPage("/login").failureUrl("/login?error=true")
        .defaultSuccessUrl("/LoggedInUser/success")
        .usernameParameter("email")
        .passwordParameter("password")
        .and().logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logOut"))
        .logoutSuccessUrl("/")
        .and()
        .headers()
        .frameOptions()
        .disable()
        .addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS",
                "ALLOW-FROM https://www.youtube.com/watch?v=HV2LVEPrKGs&feature=emb_title"));

Any help would be much appreciated. Thanks!

A: X-Frame-Options is an HTTP response header which is set by the server from which you are requesting the resource. It is used to indicate whether or not the browser should be allowed to render a page in an <frame> to avoid click-jacking attacks by ensuring that the content is not embedded into other sites.
Please see the MDN docs about it: X-Frame-Options.
So if a resource on youtube.com sets X-Frame-Options to DENY, then that resource is not allowed to render in an <frame>. If it is SAMEORIGIN, the resource can only be rendered in an <frame> on the same domain as the page itself. ALLOW-FROM uri is an obsolete directive that no longer works in modern browsers.
If you want to embed a youtube video in your site, just use the share feature and copy the HTML code into your site, it should work, here's an example.


text:
Q: I typed g++ -o main.cpp main and I lost my program I've just written the following into the console:
g++ -o main.cpp main

and my main.cpp is gone.
Did I just lose my 3 hours of work?

A: Yes, you did. The -o flag specifies the output file (main.cpp in your case since that's the file name immediately following it):
g++ -o main.cpp main
    \_________/ \__/
              \    \_This is the input file.
               \_____This specifies the output file.

In other words, you have told the compiler to try and compile what would normally be your executable, and write the results to your source file (overwriting it). A more suitable command would have been:
g++ -o main main.cpp

This is one of those educating moments that developers experience from time to time (including old hacks like me), the sort of thing that should convince you to do regular commits to git (or other source control system), or compile code with a build system rather than possibly complex command lines.


text:
Q: Pandas remove rows where several columns are not nan I have a dataframe that looks like this:
   A   B   C    D    E
0  P  10 NaN  5.0  9.0
1  Q  19 NaN  NaN  4.0
2  R   8 NaN  3.0  7.0
3  S  20 NaN  3.0  7.0
4  T   4 NaN  2.0  NaN

And I have a list: [['A', 'B', 'D', 'E'], ['A', 'B', 'D'], ['A', 'B', 'E']]
I am iterating over the list and getting only those rows from the dataframe, for which the columns specified by the list are not empty.
I have tried with the following code:
test_df = pd.DataFrame([['P', 10, np.nan, 5, 9], ['Q', 19, np.nan, np.nan, 4], ['R', 8, np.nan, 3, 7],
                        ['S', 20, np.nan, 3, 7], ['T', 4, np.nan, 2, np.nan]], columns=list('ABCDE'))
priority_list = [list('ABDE'), list('ABD'), list('ABE')]
for elem in priority_list:
    test_df = test_df.loc[test_df[elem].notna()]
    print(test_df)

But this is throwing the following error:
File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 879, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 1097, in _getitem_axis
    raise ValueError("Cannot index with multidimensional key")
ValueError: Cannot index with multidimensional key

How to overcome this issue and check for multiple columns for non-na values in the dataframe?

A: Use DataFrame.all for test if all selected values are Trues:
priority_list = [list('ABDE'), list('ABD'), list('ABE')]
for elem in priority_list:
    test_df = test_df.loc[test_df[elem].notna().all(axis=1)]
    print(test_df)