text:
Q: Proper way to create ghost zones MPI [halos] Good night
I'm attending to a parallel programming course. The teacher gave us an assignment that involves domain partition for stencil calculations. For this type of calculations (finite difference) the most common way to parallelize a code is to partition the domain and create some ghost zones (halos).
For better understand the creation of ghost zones in MPI I programmed this simple example that initialize some arrays with inner values = 123 and boundary values 88. At the end of all communication, all ghost values should remain 8. In one node I'm getting 123 values.
Serial (no ghosts):
   123 - 123 - ... - 123 - 123

Two partitions:
   123 - 123 - ... - 88  |||  88 - ... - 123 - 123

Three partitions:
   123 - 123 - ... - 88  |||  88 - ... - 123 - 123 - 88 ||| 88 - ... - 123 - 123

Aside from this bug, the main question here is about the correct approach to create and maintain ghost zones updated. Is there a cleaner solution for this aside from my messy if(myid == .... else if( myid = ... else type of implementation ?  How people usually implement this kind of parallelism ?
#include<mpi.h>
#include<stdio.h>
#include<stdlib.h>

int WhichSize(int mpiId, int numProc, int tam);

int main(int argc, char *argv[]){

    int i;
    int localSize;
    int numProc;
    int myid;

    int leftProc;
    int rightProc;

    int * myArray;
    int fullDomainSize = 16;

    MPI_Request request;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numProc);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);

    // Lets get each partition size.
    localSize = WhichSize(myid, numProc, fullDomainSize);

    // Allocate arrays acording to proc number.
    if(numProc == 1){

        //printf("Allocating Array for serial usage\n");
        myArray = (int*)malloc(localSize*sizeof(int));

    } else if(numProc == 2) {

        //printf("Allocating Array for 2 proc usage\n");
        myArray = (int*)malloc((localSize+ 1)*sizeof(int));

    } else if(numProc > 2) {

        if (myid == 0 || myid == numProc - 1){

            //printf("Allocating array for boundary nodes usage\n");
            myArray = (int*)malloc((localSize+ 1)*sizeof(int));

        } else {

            //printf("Allocating array for inner nodes usage\n");
            myArray = (int*)malloc((localSize+ 2)*sizeof(int));

        }

    }

    // Now we will fill the arrays with a dummy value 123. For the
    // boundaries (ghosts) we will fill than with 80. Just to differe
    // ntiate.

    if(numProc == 1){

        //printf("----------------------------------------\n");
        //printf("Filling the serial array with values... \n");

        for (i = 0; i<localSize; i++){
            myArray[i] = 123;
        }

    } else if(numProc == 2) {

        ////printf("------------------------------------------------\n");
        //printf("Filling array for two proc usage with values... \n");

        for (i = 0; i<localSize; i++){
            myArray[i] = 123;
        }

        // ghost.
        myArray[localSize+1] = 8;

    } else if(numProc > 2) {

        if (myid == 0 || myid == numProc - 1){

            //printf("--------------------------------------------------\n");
            //printf("Filling boundary node arrays usage with values... \n");

            for (i = 0; i<localSize; i++){
                myArray[i] = 123;
            }

            // ghosts.
            myArray[localSize+1] = 8;

        } else {

            //printf("--------------------------------------------------\n");
            //printf("Filling inner node arrays usage with values... \n");

            for (i = 0; i<localSize; i++){
                myArray[i] = 123;
            }

            // ghosts.
            myArray[localSize+1] = 8;
            myArray[0] = 8;

        }

    }

    // Now lets comunicate the ghosts with MPI_Sendrecv().

    if(numProc == 1){

        //printf("Serial usage, no ghost to comunicate \n");

    } else if(numProc == 2) {

        if (myid == 0){

            //printf("Sending ghost value from proc %d to %d\n", myid, myid + 1);
            MPI_Isend(&myArray[localSize+1],
                      1,
                      MPI_INT,
                      1,
                      12345,
                      MPI_COMM_WORLD,
                      &request);

        } else if (myid == 1) {

            //printf("Receiving ghost value from proc %d to %d\n", myid-1, myid);
            MPI_Irecv(&myArray[localSize+1],
                      1,
                      MPI_INT,
                      0,
                      12345,
                      MPI_COMM_WORLD,
                      &request);
        }

    } else if(numProc > 2) {

        if (myid == 0){

            rightProc = myid + 1;

            if (myid == 0){

                //printf("-------------------------------\n");
                //printf("Communicating Boundary ghosts !\n");
                //printf("-------------------------------\n");

                //printf("Sending ghost value from proc %d to %d\n", myid, myid + 1);
                MPI_Isend(&myArray[localSize+1],
                          1,
                          MPI_INT,
                          rightProc,
                          12345,
                          MPI_COMM_WORLD,
                          &request);

            } else if (myid == rightProc) {

                //printf("Receiving ghost value from proc %d to %d\n", myid-1, myid);
                MPI_Irecv(&myArray[localSize+1],
                          1,
                          MPI_INT,
                          0,
                          12345,
                          MPI_COMM_WORLD,
                          &request);
            }

        } else if (myid == numProc - 1) {

            leftProc  = myid - 1;

            if (myid == numProc - 1){

                //printf("-------------------------------\n");
                //printf("Communicating Boundary ghosts !\n");
                //printf("-------------------------------\n");

                ////printf("Sending ghost value from proc %d to %d\n", myid, myid + 1);
                MPI_Isend(&myArray[localSize+1],
                          1,
                          MPI_INT,
                          leftProc,
                          12345,
                          MPI_COMM_WORLD,
                          &request);

            } else if (myid == leftProc) {

                rightProc = myid + 1;

                //printf("Receiving ghost value from proc %d to %d\n", myid-1, myid);
                MPI_Irecv(&myArray[localSize+1],
                          1,
                          MPI_INT,
                          rightProc,
                          12345,
                          MPI_COMM_WORLD,
                          &request);
            }

        } else {

                //printf("-------------------------------\n");
                //printf("Communicating Inner ghosts baby\n");
                //printf("-------------------------------\n");

                leftProc  = myid - 1;
                rightProc = myid + 1;

                // Communicate tail ghost.
                if (myid == leftProc) {
                    MPI_Isend(&myArray[localSize+1],
                              1,
                              MPI_INT,
                              rightProc,
                              12345,
                              MPI_COMM_WORLD,
                              &request);

                } else if (myid == rightProc){
                    MPI_Irecv(&myArray[localSize+1],
                              1,
                              MPI_INT,
                              leftProc,
                              12345,
                              MPI_COMM_WORLD,
                              &request);
                }

                // Communicate head ghost.
                if (myid == leftProc) {
                    MPI_Isend(&myArray[0],
                              1,
                              MPI_INT,
                              rightProc,
                              12345,
                              MPI_COMM_WORLD,
                              &request);

                } else if (myid == rightProc){
                    MPI_Irecv(&myArray[0],
                              1,
                              MPI_INT,
                              leftProc,
                              12345,
                              MPI_COMM_WORLD,
                              &request);
                }
        }
    }

    // Now I Want to see if the ghosts are in place !.

    if (myid == 0){
        printf("The ghost value is: %d\n", myArray[localSize + 1]);
    } else if (myid == numProc - 1){
        printf("The ghost value is: %d\n", myArray[0]);
    } else {
        printf("The head ghost is: %d\n", myArray[0]);
        printf("The tail ghost is: %d\n", myArray[localSize + 1]);
    }

    MPI_Finalize();

    exit(0);
}

int WhichSize(int mpiId, int numProc, int tam){

    double resto;
    int    tamLocal;

    tamLocal = tam / numProc;

    resto = tam - tamLocal*numProc;

    if (mpiId < resto) tamLocal = tamLocal + 1;

    return tamLocal;
}

thank you guys !

A: Halos can be elegantly implemented in MPI using Cartesian virtual topologies and the send-receive operation.
First of all, having lots of rank-dependent logic in conditional operators makes the code hard to read and understand. It is way better when the code is symmetric, i.e. when all ranks execute the same code. Corner cases can be taken care of using the MPI_PROC_NULL null rank - a send to or receive from that rank results in a no-op. It is therefore enough to do:
// Compute the rank of the left neighbour
leftProc = myid - 1;
if (leftProc < 0) leftProc = MPI_PROC_NULL;
// Compute the rank of the right neighbour
rightProc = myid + 1;
if (rightProc >= numProc) rightProc = MPI_PROC_NULL;

// Halo exchange in forward direction
MPI_Sendrecv(&myArray[localSize], 1, MPI_INT, rightProc, 0,   // send last element to the right
             &myArray[0], 1, MPI_INT, leftProc, 0,            // receive into left halo
             MPI_COMM_WORLD);
// Halo exchange in reverse direction
MPI_Sendrecv(&myArray[1], 1, MPI_INT, leftProc, 0,            // send first element to the left
             &myArray[localSize+1], 1, MPI_INT, rightProc, 0, // receive into right halo
             MPI_COMM_WORLD);

That code works for any rank, even for those at both ends - there either the source or the destination is the null rank and no actual transfer occurs in the corresponding direction. It also works with any number of MPI processes, from one to many. It requires that all ranks have halos on both sides, including those that don't really need it (the two corner ranks). One can store in those dummy halos useful things like boundary values (e.g. when solving PDEs) or simply live with the memory waste, which is usually negligible.
In your code, you use incorrectly non-blocking operations. Those are tricky and require care to be taken. MPI_Sendrecv could and should be used instead. It performs both send and receive operations at the same time and thus prevents deadlocks (as long as there is a matching receive for each send).
If the domain is periodic, then the rank computation logic becomes simply:
// Compute the rank of the left neighbour
leftProc = (myid - 1 + numProc) % numProc;
// Compute the rank of the right neighbour
rightProc = (myid + 1) % numProc;

Instead of doing the arithmetic, one could create a Cartesian virtual topology and then use MPI_Cart_shift to find the ranks of the two neighbours:
// Create a non-periodic 1-D Cartesian topology
int dims[1] = { numProc };
int periods[1] = { 0 };   // 0 - non-periodic, 1 - periodic
MPI_Comm cart_comm;
MPI_Cart_create(MPI_COMM_WORLD, 1, dims, periods, 1, &cart_comm);

// Find the two neighbours
MPI_Cart_shift(cart_comm, 0, 1, &leftProc, &rightProc);

The code for the halo exchange remains the same with the only difference that cart_comm should replace MPI_COMM_WORLD. MPI_Cart_shift automatically takes care of the corner cases and will return MPI_PROC_NULL when appropriate. The advantage of that method is that you can easily switch between non-periodic and periodic domains by simply flipping the values inside the periods[] array.
The halos have to be updates as often as necessary, which depends on the algorithm. With most iterative schemes, the update must happen at the beginning of each iteration. One could reduce the communication frequency by introducing multi-level halos and using the values in the outer levels to compute the values in the inner ones.
To conclude, your main function could be reduced to (without using a Cartesian topology):
int main(int argc, char *argv[]){

    int i;
    int localSize;
    int numProc;
    int myid;

    int leftProc;
    int rightProc;

    int * myArray;
    int fullDomainSize = 16;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numProc);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);

    // Compute neighbouring ranks
    rightProc = myid + 1;
    if (rightProc >= numProc) rightProc = MPI_PROC_NULL;
    leftProc = myid - 1;
    if (leftProc < 0) leftProc = MPI_PROC_NULL;

    // Lets get each partition size.
    localSize = WhichSize(myid, numProc, fullDomainSize);

    // Allocate arrays.
    myArray = (int*)malloc((localSize+ 2)*sizeof(int));

    // Now we will fill the arrays with a dummy value 123. For the
    // boundaries (ghosts) we will fill than with 80. Just to differe
    // ntiate.

    //printf("--------------------------------------------------\n");
    //printf("Filling node arrays usage with values... \n");

    for (i = 1; i<localSize; i++){
        myArray[i] = 123;
    }

    // ghosts.
    myArray[localSize+1] = 8;
    myArray[0] = 8;

    //printf("-------------------------------\n");
    //printf("Communicating Boundary ghosts !\n");
    //printf("-------------------------------\n");

    //printf("Sending ghost value to the right\n");
    MPI_Sendrecv(&myArray[localSize], 1, MPI_INT, rightProc, 12345,
                 &myArray[0], 1, MPI_INT, leftProc, 12345,
                 MPI_COMM_WORLD);

    //printf("Sending ghost value to the left\n");
    MPI_Sendrecv(&myArray[1], 1, MPI_INT, leftProc, 12345,
                 &myArray[localSize+1], 1, MPI_INT, rightProc, 12345,
                 MPI_COMM_WORLD);

    // Now I Want to see if the ghosts are in place !.

    printf("[%d] The head ghost is: %d\n", myid, myArray[0]);
    printf("[%d] The tail ghost is: %d\n", myid, myArray[localSize + 1]);

    MPI_Finalize();

    return 0;
}


text:
Q: KVM and rdtsc latency As part of debugging our guest VM, we use rdtsc quite extensively to monitor the amount of time (ok, clock cycles) being used. The question was raised that this was expensive in itself as rdtsc yields a VM exit. I can think of no lower level means of finding out how much clock time or equivalent has elapsed. Is there any other solution ? Is this really expensive ?

A: It is not necessary for every rdtsc to result in VM Exit, atleast not on Intel CPU's. ASAIK, the Virtual Machine Control Structure(VMCS) has a bit which dictates whether every RDTSC should cause a VM-Exit. Check "Definitions of Primary Processor-Based VM-Execution Controls – BIT 12" (Table 21-6) of Intel Architecture Manual
There is a nifty script(vmxcap.py) which can be used to quickly dump this info. For example, on my machine where RDTSC does not incur VM-Exit, I get the below:
[root@XYZ ~]# ./vmxcap.py  | grep -i rdtsc
RDTSC exiting                            no

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Move next available column value to previous available column space in informatica 0
votes
1 view
Hi,
I have a scenario, where in we have a single record and multiple columns like this
Record_number cd1 cd2 cd3 cd4 cd5 cd6 cd7 cd8 cd9

Here are values for the for the above record
123           12 null 13 14 null 15 16 17 null
Here we have value for cd1 and not for cd2 and we have value for cd3 so cd2 is empty so cd3 should get into cd2 since it was empty so we should move the next available values to previous available spaces.
Does anyone know how to achieve this scenario?

A: If I understand your question correctly, this can be easily done using an expression transformation.

A: First create a variable port that would concatenate all the non-null values using some separator, e.g.|, like:
IIF(ISNULL(cd1),'',cd1 || '|') ||
IIF(ISNULL(cd2),'',cd2 || '|') ||
...
IIF(ISNULL(cd9),'',cd9 || '|') ||

This should result in pipe delimited list with the nulls removed, e.g.:
123|12|13|14|15|16|17|
Next create an output port for each column, that would get the correct substring using index of the separator. I'll leave coding this part to you, but if you'd have issues, please let me know.

A: One approach could be to use an expression transformation as follows:
First concatenate all the ports in a single field using a delimiter (for example ',')
v_CONCAT:= cd1||','||cd2||','||cd3||','||cd4||','||cd5||','||cd6||','||cd7||','||cd8||','||cd9

Now create the output ports using regular expressions
o_cd1:=REG_EXTRACT(v_CONCAT,',*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*)',1)
o_cd2:=REG_EXTRACT(v_CONCAT,',*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*)',2)
o_cd3:=REG_EXTRACT(v_CONCAT,',*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*),*([^,]*)',3)
.
.
and so on.

REG_EXTRACT extracts a substring from the input string that matches the regular expression.

*

*() - a group. There will be as many groups as your ports cd1-cd12

*,* - zero or more commas, if a value is null two commas will appear consecutively

*[^,] - anything other than comma

*[^,]* - zero or more of any character other than comma

The third parameter to REG_EXTRACT denotes which group you want as output. For o_cd1 we want the first non-NULL value, so it is 1 and for o_cd2, it is 2 and so on


text:
Q: composing two comparison functions? I'd like to sort by one property and then by another (if the first property is the same.)
What's the idiomatic way in Haskell of composing two comparison functions, i.e. a function used with sortBy?
Given
f :: Ord a => a -> a -> Ordering
g :: Ord a => a -> a -> Ordering

composing f and g would yield:
h x y = case v of
          EQ -> g x y
          otherwise -> v
        where v = f x y

A: vitus points out the very cool instance of Monoid for Ordering. If you combine it with the instance instance Monoid b => Monoid (a -> b) it turns out your composition function is just (get ready):
mappend

Check it out:
Prelude Data.Monoid> let f a b = EQ
Prelude Data.Monoid> let g a b = LT
Prelude Data.Monoid> :t f `mappend` g
f `mappend` g :: t -> t1 -> Ordering
Prelude Data.Monoid> (f `mappend` g) undefined undefined
LT
Prelude Data.Monoid> let f a b = GT
Prelude Data.Monoid> (f `mappend` g) undefined undefined
GT

+1 for powerful and simple abstractions

A: You can use the <> operator. In this example bigSort sorts string by their numerical value, first comparing length and then comparing lexicographically.
import Data.List (sortBy)
import Data.Ord (compare, comparing)

bigSort :: [String] -> [String]
bigSort = sortBy $ (comparing length) <> compare

Example:
bigSort ["31415926535897932384626433832795","1","3","10","3","5"] =
        ["1","3","3","5","10","31415926535897932384626433832795"]

<> is an alias of mappend from the Data.Monoid module (see jberryman answer).
The (free) book Learn You a Haskell for Great Good! explains how it works here in Chapter 11

instance Monoid Ordering where
   mempty = EQ
   LT `mappend` _ = LT
   EQ `mappend` y = y
   GT `mappend` _ = GT

The instance is set up like this: when we mappend two Ordering values, the one on the left is kept, unless the value on the left is EQ, in which case the right one is the result. The identity is EQ.


text:
Q: Is this SQL Statement Safe for Concurrent Access? Is the SQL statement below 'safe' for concurrent access? At what point will A get locked? If it's just before the INSERT is there a chance that the first @count may be wrong?
BEGIN TRAN;
    SELECT @count = count(1) from A
    DELETE FROM A where x=z
    SELECT @newCount = count(1) from A
    SELECT @newCount - @count
COMMIT TRAN;

A: BEGIN TRAN;
    DECLARE @RC INT
    EXEC @RC = sp_getapplock @Resource='ArchiveLock', @LockMode='Exclusive',  @LockOwner='Transaction', @LockTimeout=15000
    SELECT @count = count(1) from A
    DELETE FROM A where x=z
    SELECT @newCount = count(1) from A
    SELECT @newCount - @count
COMMIT TRAN;

Try this. I used this recently to handle set of Delet statements which are called by multiple processes in parallel. The sp_getapplock creates a lock until the transaction is committed which makes other process to wait.
Hope this helps!


text:
Q: Data loss with Collector for ArcGIS Last week we used Collector for ArcGIS (version 10.3 on an iPad Air, AT&T) with our ArcGIS Online organization account for field data collection. We experienced loss of data, sometimes everything including the point feature itself, other times photo attachments. Since the collection was at or near urban areas and cellular signal strength was good in general, we didn't use offline mode and it was all done real time.
On day 2 of the collection there were a few instances with multi-photo points when the "submit" button was tapped it would take the App a while to process then a submission failed message would appear, offering two options – "Cancel" and "Retry". Initially "Retry" was selected but the same failure message would appear again and again, so eventually the field crew clicked on "Cancel". At that point the collected feature as well as attributes and photos were visible on the App, so they moved on to the next site.
When they were back at the hotel (on Wi-Fi) they realized 2 points they collected during the day were completely gone, and 3 other points were missing all the photo attachments. They also noticed 2 points from day 1 were completely gone (they couldn't recall with certainty whether the "failed to submit" message was encountered with them). Not knowing how to avoid more data loss, they went with paper and pen for the remaining of the collection and re-collection of the lost points.
Once they were back in the office we did more testing. While the cellular signal strength was at least 3 bars out of 5, it was pretty easy to duplicate the issue by taking more than 3 or 4 photos and submit.
Here are our questions:

*

*Is our instinct correct that our issue could be caused by the data volume submitted each time?

*We like the convenience and ease of set up with this solution. However based on our first project the reliability is too low for serious application. I can't imagine we are the only one needing multiple photos for each collected features. Has data loss been a common issue?

*What is everyone else doing to make this solution work? I assume the reliability will improve if each submission is limited to one photo, but it's such an interruption to the workflow.

*When collecting in "online mode", is there a way to explicitly back up the data collected onto the mobile device?

*We are thinking maybe offline mode can be more reliable and will do some tests. But from experience, will syncing (Wi-Fi or cellular) be problematic if a collected feature contains a large number of photo attachments?

*Any recommendation on more reliable solutions that works with ArcGIS Online?

*How about complete on device Apps?
Update: after talking with an ESRI technical support back and forth, he started being able to duplicate the problem on his end, and has registered this issue as a bug. We did perform more tests of our own. It seems that one photo per submission/update is problem free, so while on cellular only if multi photos are needed for a collection point you'll have to update after each photo is taken. Offline mode seems to be working fine.

A: Here are some responses based on my experiences working with a team using Collector over the last year or so.
Is our instinct correct that our issue could be caused by the data volume submitted each time?

*

*we've only used fairly light datasets so far, but see the photo
bullet.

We like the convenience and ease of set up with this solution. However based on our first project the reliability is too low for serious application. I can't imagine we are the only one needing multiple photos for each collected features. Has data loss been a common issue?

*

*We've never lost data. only had to recover it by downloading on iPad
geodatabase when synch'ing fails.

What is everyone else doing to make this solution work? I assume the reliability will improve if each submission is limited to one photo, but it's such an interruption to the workflow.

*

*We have scripted the removal of photos from the geodatabase on server
side so that Collector is not trying to sync large amounts of data
(photos), and yes limited to only a couple of photos.  If you're
taking a lot of photos, you need a different toolset, in my opion.
Collector also appears to remove all the exif data that is of use, so
avoiding it for photos is not a bad idea.

When collecting in "online mode", is there a way to explicitly back up the data collected onto the mobile device?

*

*good question.  i don't know.

We are thinking maybe offline mode can be more reliable and will do some tests. But from experience, will syncing (Wi-Fi or cellular) be problematic if a collected feature contains a large number of photo attachments?

*

*we generally are working in areas of intermittent cellular coverage so we've usually worked in an offline mode, however we rarely have data submission issues when online, only when synch'ing from offline

A: Disclaimer: I work for AmigoCloud and we have a data collection solution.
Some answers:

Is our instinct correct that our issue could be caused by the data
  volume submitted each time?

Doesn't seem like a big volume, so I doubt that was the issue.

We like the convenience and ease of set up with this solution. However
  based on our first project the reliability is too low for serious
  application. I can't imagine we are the only one needing multiple
  photos for each collected features.

Multiple photos associated with a feature is not out of the ordinary.

Has data loss been a common issue?

This is a bigger question. There are workflows that can cause data loss, for example, if you edit the schema (e.g. add a field) while the devices are out on the field.

What is everyone else doing to make this solution work? I assume the
  reliability will improve if each submission is limited to one photo,
  but it's such an interruption to the workflow.

Your workflow should work with any of the data collection solutions, this doesn't seem to the issue.

When collecting in "online mode", is there a way to explicitly back up
  the data collected onto the mobile device?

Most of the data collection solutions keep a copy of the data submitted locally - even in "online mode". That data is usually deleted when the device syncs.

We are thinking maybe offline mode can be more reliable and will do
  some tests. But from experience, will syncing (Wi-Fi or cellular) be
  problematic if a collected feature contains a large number of photo
  attachments?

Should not be a problem.
Now to answer your question about Collector, if I had to guess, it probably has to do with schemas changing or intermittent connection which kills the sync before it can finish submitting the records. This is a typical problem with most data collection apps.

Any recommendation on more reliable solutions that works with ArcGIS
  Online?

Here is where the shameless plug comes in. You can get that project setup in AmigoCloud in less than 1 minute.
Check out this 60s video: https://youtu.be/lj6OeTZgzM8


text:
Q: Inverter DC link voltage rises when motor decelerates For a voltage-source-inverter (VSI) powered PMSM, as shown in the picture below, the DC bus voltage across the DC bus capacitor Udc normally drops frequently, which will cause no harm to the cap itself. However, when the low speed command is given, the motor will decelerate because smaller speed ref leads to a smaller Iq ref value, which means less torque is generated. In this case, the capacitor voltage could often increase to be higher than the battery voltage if the battery can't be charged, which could damage the DC cap and MOSFETs. It is especially so when deceleration is high.

I found another question Regenerated current during deceleration of PMSM motors and one of the answer mentioned that during motor deceleration, the motor and the DC cap forms a boost converter that results in the increase of cap voltage.
My question is

*

*Is the motor always in regenerative mode when the it decelerates? isn't it dynamic braking if we don't purposely implement regenerative braking? If it is dynamic braking, why DC cap voltage increases?

*I think the motor current is still in phase with its back-EMF when
decelerating, only the current amplitude becomes smaller because PWM
duty is smaller. Am I correct about this?

A:
Is the motor always in regenerative mode when the it decelerates?

The motor is only in regenerative mode if the deceleration rate is faster than the motor would decelerate if it were simply disconnected from power. In other words, if the losses in the motor and load use up all of the energy that must be taken from moving mass, there will be no regeneration.

If it is dynamic braking, why DC cap voltage increases?

Dynamic braking involves dissipating energy in braking resistors. If that is not taking place, it is not dynamic braking.

I think the motor current is still in phase with its back-EMF when decelerating, only the current amplitude becomes smaller because PWM duty is smaller. Am I correct about this?

The relationship between the motor current and voltage waveforms is whatever it needs to be consistent with the controller operation and the motor performance.
If the motor is "under control," it will act as a generator if it is called upon to provide braking torque. That will result in energy being pushed back into the controller regardless of whether or not the controller can dissipate the energy or return it to the source. If the controller receives energy from the motor that it can not dissipate or push back to the source, it will put it in the capacitors. That will increase the capacitor voltage until something fails. At that point, the energy will be dissipated in the resulting explosion and in the the motor or wherever else there are conductors forced to carry fault currents.

A:
Is the motor always in regenerative mode when the it decelerates? isn't it dynamic braking if we don't purposely implement regenerative braking? If it is dynamic braking, why DC cap voltage increases?

There's no such thing as regenerative mode on a motor. There is, however, generator mode and a motor braking is always in generator mode.
And the answer is no, because there's more than two options. If you connect up a braking resistor, that is dynamic braking. If you just short out the motor in the H-bridge that is also a form of dynamic braking. If you connect the power supply up in reverse that is regenerative braking. It's not just two options because there are more than two ways you can throw the inverter switches to brake the motor.


text:
Q: Fantasy series about a disabled protagonist I've spent years trying to find this book series. I can't remember the name of the book I read, the author, or the characters, but I remember some key parts about the protagonist.

*

*I think he was an outlaw (or at least wanted), but no one thought it was him since he appeared to be disabled, or that he could barely move properly and needed someone to take care of him (he actually was, but he could make himself "better" per se).

*He was a master swordsman who I think was trained by some special people or society, and he could only act to his full power when he focused on gems.

*Later on in the story or maybe in the next book, he received a special gem thing that I think went on his forehead, which contained several rare gems he could use and meant he didn't need to physically hold the gems.

*Near the end I think it was taken from him in a fight where he nearly dies, but discovers that he can focus without the gems to a certain degree.

*I think there was a character who was part of a church or sanctuary?

*Might have used gems to heal, not knowing how it actually worked, which I think was how the protagonist could move properly, but he did it on himself, but had to be in constant contact with the crystal, which is why the gem thing on his forehead was so important (I think it had an actual name, but no amount of research I've done has found it).

If anyone knows the name of this book, the series it's part of or the author, it would be greatly appreciated!

A: This sounds like The Highwayman by R.A. Salvatore.
From Wikipedia:

Bransen utilizes both sides of his heritage in the novel to overcome his crippled state and become the Highwayman. With help from a soul stone, the hematite, combined with his knowledge of The Book of Jhest, Bransen overcomes his physically weak form by centering his chi, which greatly increases his mobility. With his newfound ability, he rescues Cadayale from the bullies who wished to rape and beat her for helping him, killing the lead bully, Tarkus Breen. After weeks of robbing from the tax collectors to give back to the poor, becoming a local Robin Hood, Bransen risks everything to rescue Cadayale and Callen from Bernivvigar and Prydae, who sought to rape Cadayale to beget an heir, leading to the deaths of both men.

So it has the main points you mentioned: the main character is an outlaw, who avoids suspicion by virtue of his being crippled.  He uses a gem to focus his energy to make him a superior fighter.  His mother is rescued by Brother Bran Dynard, a follower of   Blessed Abelle, which is probably your church reference.


text:
Q: Demographic Analysis across multiple zip codes/area I am trying to analyze demographic information across 10 main zip codes that surround my area of interest.  How would I be able to compile the information I have to give me the demographics of the combined areas?

A: You may need to provide more information regarding the format of your data. Is it in .csv files or in shapefiles (i.e., shp)? Shapefiles may require specialized software in order to modify. No matter what your file format you will need to define variables of interest for the zip codes and make sure that you produce a categorical variable containing the zip code value.
Also, some more information regarding what you want to analyze will be helpful. This may determine how you organize your input data file for analysis. The statistical package will also matter.
Wooldridge (2009) has a good chapter (ch. 19) for preparing for an econometric analysis project that you may want to review.


text:
Q: algorithm to search for duplicated information? I'm trying to code a program that prompts the user that the information they enter is duplicated. But Dev-C++ keeps telling me 'class Student' has no member named 'p', so I'm guessing there's something wrong with the algorithm or the code, please have a look:
Student.h
#ifndef STUDENT_H_
#define STUDENT_H_

#include "Person.h"

class Student: public Person {
    int ent_year;
    string major;
    public:
        Student *next;
        Student ();
        Student (int i_pid, string i_fname, string i_dob, string i_addr, int i_ent_year, string i_major);
        void Show ();

        void Set_ent_year (int i_ent_year);
        void Set_major(string i_major);

        int Get_ent_year();
        string Get_major();
};

#endif

StudentList.h
 #ifndef STUDENTLIST_H_
    #define STUDENTLIST_H_

    #include "Student.h"

    class StudentList {
        private:
            Student *head, *tail;

        public:
            Student p;
            Student *next;
            StudentList ();

            void SList_Init ();
            void AddTail (Student *p);
            void SubString (string s);
            void ListShow ();
            void ReadFile ();
            void findID();
            void findName();
            void findDOB();
            void findAddr();
            void findMajor();
            void findEY();
            void changeName();
            void changeDOB();
            void changeAddr();
            void changeMajor();
            void changeEY();
            void Add_Student ();

            bool is_duplicate(Student t);
    };

    void Open_file (string file_name);
    void Close_file ();

    #endif

.cpp file
bool equalStudent(Student s1, Student s2)
{
    return (s1.Get_ent_year() == s2.Get_ent_year())
            && ((s1.Get_addr()).compare(s2.Get_addr()) == 0)
            && ((s1.Get_dob()).compare(s2.Get_dob()) == 0)
            && ((s1.Get_fname()).compare(s2.Get_fname()) == 0)
            && ((s1.Get_major()).compare(s2.Get_major()) == 0);
}

bool is_duplicate(Student s1) {
    Student *head;
    Student *h1 = head;
    while (h1 != NULL) {
        if (equalStudent(h1->p, s1)) {
            return true;
        }
        h1 = h1->next;
    }
    return false;
}

void StudentList:: Add_Student ()
{
    int new_pid, new_ent_year;
    string new_fname, new_dob, new_addr, new_major;
    cout << endl << "Enter student information:" << endl;
    cout << "Full name: "; cin.ignore(1); getline (cin,new_fname);
    cout << "Date of birth: "; getline (cin,new_dob);
    cout << "Address: "; getline (cin,new_addr);
    cout << "Entrance year: "; cin >> new_ent_year;
    cout << "Major: "; cin.ignore(1); getline (cin,new_major);

bool duplicate = is_duplicate(new_pid, new_ent_year, new_fname, new_dob, new_addr, new_major); // call function to check for duplicate info
if (duplicate) {
    string proceed;
    cout << "Duplicated! Continue?  Proceed? [y/n] "; cin.ignore(1); getline (cin, proceed);
    if (proceed != "y") {
        return;
    }
}
Student *p = new Student (new_pid, new_fname, new_dob, new_addr, new_ent_year, new_major);
AddTail (p);

f.seekg(0, ios::end);
f << endl << new_pid << ":" << new_fname << ":" << new_dob << ":" << new_addr << ":" << new_ent_year << ":" << new_major;

}

Here's the whole error message:
In function 'bool is_duplicate(Student)':
[Error] 'class Student' has no member named 'p'
In member function 'void StudentList::Add_Student()':
[Error] no matching function for call to 'StudentList::is_duplicate(int&, int&, std::string&, std::string&, std::string&, std::string&)'
[Note] candidate is:
In file included from StudentList.cpp
[Note] bool StudentList::is_duplicate(Student)
[Note] candidate expects 1 argument, 6 provided

A: I think you should change your is_duplicate to
bool StudentList::is_duplicate(Student s1) { //this is a class member function, hence the StudentList::
    Student *h1 = head; //starting with the head of the list, just 1 variable is enough to iterate
    while (h1 != NULL) {
        //comparing current student with s1
        if (equalStudent(*h1, s1)) {
            return true;
        }
        h1 = h1->next;
    }
    return false;
}

Also pay attention to your function definitions. While your Add_Student is defined right (void StudentList::Add_Student()), the rest of the functions are missing the StudentList:: part, which makes them just global functions, not member functions.

A:  private:
        Student *head, *tail;

    public:
        Student p;

your 'p' is an object of type Student in your StudentList class.
What you are saying in you code is to get the object 'p' from Student and not StudentList.
On top of that, Im not completely sure but I think you want 'p' to be a pointer which you define in your cpp later

A: bool is_duplicate(Student s1) {
    Student *head;
    Student *h1 = head;
    while (h1 != NULL) {
        if (equalStudent(h1->p, s1)) {
            return true;
        }
        h1 = h1->next;
    }
    return false;
}

Problem: by declaring a duplicate Student *head; in the scope of the method your Student *h1 = head; is going to initialize h1 to the uninitialized local variable, not the class member.


text:
Q: Is sed \{x,y\} range greedy? I would like to know if, for instance, \{x,y\} in sed will try to match as much or as little as possible characters.
Also, can someone explain to me the bellow unexpected behaviour of sed?
echo "baaab" | sed 's/a\{1,2\}//'
bab

echo "baaab" | sed 's/a\{0,2\}//'
baaab

In the first line, sed becomes greedy, in the second apparently it doesn't, is there a reason for that?
I'm using GNU sed version 4.2.1.

A: Yes, it's greedy.
In POSIX compliant system, not only sed but also all tools which use Basic Regular Expression, the matched pattern will always be greedy:

The search for a matching sequence starts at the beginning of a string
  and stops when the first sequence matching the expression is found,
  where "first" is defined to mean "begins earliest in the string". If
  the pattern permits a variable number of matching characters and thus
  there is more than one such sequence starting at that point, the
  longest such sequence is matched. For example, the BRE "bb*" matches
  the second to fourth characters of the string "abbbc", and the ERE
  "(wee|week)(knights|night)" matches all ten characters of the string
  "weeknights".
Consistent with the whole match being the longest of the leftmost
  matches, each subpattern, from left to right, shall match the longest
  possible string. For this purpose, a null string shall be considered
  to be longer than no match at all. For example, matching the BRE
  "(.)." against "abcdef", the subexpression "(\1)" is "abcdef", and
  matching the BRE "(a*)*" against "bc", the subexpression "(\1)" is
  the null string.

The pattern a\{0,2\} matched any occurrence of character a between zero and two. Zero occurrence means the empty string, which is considered to be longer than no match as the spec indicated above.
The problem with your usage is that you did not use the global flag for sed substitution command. Without global flag, sed stop doing substitution as soon as it found the first match, which is the empty string at the beginning of the line.

The general form is \{m,n\} with 0 <= m <= n <= RE_DUP_MAX, with RE_DUP_MAX is 32767 in most platform:
$ getconf RE_DUP_MAX
32767

A: a\{0,2\} will match the empty string at the start of the line (actually, any empty string, but g wasn't specified):
$ echo "baaab" | sed 's/a\{0,2\}/y/'
ybaaab

Since GNU sed does matching from left to right, and a global replacement wasn't specified, only the start of the line matched. If you'd used g:
$ echo "baaab" | sed 's/a\{0,2\}/y/g'
ybyyby

The empty strings at the start and end matched, and the aa, and the remaining a.


text:
Q: Xamarin Forms for iOS 'Could not AOT the assembly' i am develop an app using xamarin forms, when i deploy for android it works fine but for iOS it gives an error
Could not AOT the assembly '/Users/MyUser/Library/Caches/Xamarin/mtbs/builds/DemoApp.iOS/1200d99a740029217aed9915fa08d90d/C:/Users/MANISH~1.TIW/AppData/Local/Temp/vs370F.tmp/iPhone/Debug/device-builds/iphone6.1-12.0/mtouch-cache/3-Build/DemoApp.iOS.exe'   DemoApp.iOS
So can anyone please help me out from this issue ?
Build Log:
2>E:\BudhiPrakash Data\android-sdk-new\tools\XamarinProjects\MyApps\ExampleApp\ExampleApp.iOS\Controls\CustomElementFrameRenderer.cs(35,35,35,75): warning CS0618: 'Frame.OutlineColorProperty' is obsolete: 'OutlineColorProperty is obsolete as of version 3.0.0. Please use BorderColorProperty instead.'
2>E:\BudhiPrakash Data\android-sdk-new\tools\XamarinProjects\MyApps\ExampleApp\ExampleApp.iOS\Service\IosDownloader.cs(34,30,34,32): warning CS0168: The variable 'ex' is declared but never used
2>E:\BudhiPrakash Data\android-sdk-new\tools\XamarinProjects\MyApps\ExampleApp\ExampleApp.iOS\Controls\CustomElementFrameRenderer.cs(67,33,67,64): warning CS0618: 'Frame.OutlineColor' is obsolete: 'OutlineColor is obsolete as of version 3.0.0. Please use BorderColor instead.'
2>  ExampleApp.iOS -> E:\BudhiPrakash Data\android-sdk-new\tools\XamarinProjects\MyApps\ExampleApp\ExampleApp.iOS\bin\iPhone\Debug\ExampleApp.iOS.exe
2>  Detected signing identity:
2>    Code Signing Key: "iPhone Developer: AVC SDF (234)" (3434)
2>    Provisioning Profile: "iOS Team Provisioning Profile: *" (23423-423423-4234-234-234)
2>    Bundle Id: com.app
2>    App Id: SDFSDFSD.com.app
2>  /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/bin/mtouch @/Users/rajeev/Library/Caches/Xamarin/mtbs/builds/ExampleApp.iOS/1200d99a740029217aed9915fa08d90d/C:/Users/MANISH~1.TIW/AppData/Local/Temp/vs370F.tmp/iPhone/Debug/device-builds/iphone6.1-12.0/response-file.rsp -v -v -v -v
2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Xamarin\iOS\Xamarin.iOS.Common.targets(842,3): warning : The runtime version supported by this application is unavailable.
2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Xamarin\iOS\Xamarin.iOS.Common.targets(842,3): error MT3001: Could not AOT the assembly '/Users/rajeev/Library/Caches/Xamarin/mtbs/builds/ExampleApp.iOS/1200d99a740029217aed9915fa08d90d/C:/Users/MANISH~1.TIW/AppData/Local/Temp/vs370F.tmp/iPhone/Debug/device-builds/iphone6.1-12.0/mtouch-cache/3-Build/ExampleApp.iOS.exe'
========== Build: 1 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

Diagnose Log:
CopyingFile - Path: /Users/rajeev/Library/Caches/Xamarin/mtbs/builds/HelpBuddiePrism.iOS/1200d99a740029217aed9915fa08d90d/bin/iPhone/Debug/device-builds/iphone6.1-12.0/HelpBuddiePrism.iOS.app/Close.png
 CopyingFile - PercentComplete: 99%
 CreatingStagingDirectory - PercentComplete: 5%
 ExtractingPackage - PercentComplete: 15%
 InspectingPackage - PercentComplete: 20%
 TakingInstallLock - PercentComplete: 20%
 PreflightingApplication - PercentComplete: 30%
 VerifyingApplication - PercentComplete: 40%
 APIInternalError: Failed to unhide archs in executable file:///private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.MG8Wit/extracted/HelpBuddiePrism.iOS.app/HelpBuddiePrism.iOS


text:
Q: rails server not responding to remote connections I have a rails server on a remote box (debian wheezy, ruby 2.2, rails 4.2) and the server does not respond when I try to connect to it in my local browser or curl. The request times out. However when I ssh into the box and wget localhost:3000 it gets me the root page perfectly. Any suggestions?

A: Rails 4.2 changed the default IP address that rails server binds to, instead of binding to 0.0.0.0 (ie. all interfaces) it binds only to localhost.
Edit
Sorry, I see now that you made no mention of production, just a remote box. So I removed that bit from above.
To get around this you can do two things, either always start with the -b option:
rails s -b 0.0.0.0

Or, there's a little trick to add that to the default, see https://stackoverflow.com/a/8998401/152786 (note that you only need to merge in the :Port and :Host options, and you can set the :Host to 0.0.0.0 if you want).

A: To bind the server without using command arguments you can append this to bin/rails after line require_relative '../config/boot' and the code is executed only for the rails server command:
if ARGV.first == 's' || ARGV.first == 'server'
  require 'rails/commands/server'
  module Rails
    class Server
      def default_options
        super.merge(Host:  '0.0.0.0', Port: 3000)
      end
    end
  end
end

The bin/rails file loks like this:
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application',  __FILE__)
require_relative '../config/boot'

# Set default host and port to rails server
if ARGV.first == 's' || ARGV.first == 'server'
  require 'rails/commands/server'
  module Rails
    class Server
      def default_options
        super.merge(Host:  '0.0.0.0', Port: 3000)
      end
    end
  end
end

require 'rails/commands'


text:
Q: Dynamic GUI in Python? I had a question about whether it would be possible to make something like the following in Python:
I'd like to have a GUI such that, upon starting there are simply two fields allowing you load two particular files.
When those files have been selected it parses and displays the contents, and dynamically generates a set of checkboxes to allow the user to select or not options based on the content of the file.
Is such a thing possible in Python, or would i need to look elsewhere?
Cheers
Lindley

A: At least three ways of doing this:

*

*Gi (GTK with Python) (The API here is for the C language, but
is the same more or less for Python)

*PyQt

*Tkinter


text:
Q: Css3 Body Animation makes Options in a select form twitch jsFiddle: http://jsfiddle.net/Dm7uE/
HTML:
<form action="delete.php" method="get">
    <label for="delete">DELETE ONE</label>
    <select name="id">
        <option value="test">test</option>
        <option value="test">test</option>
        <option value="test">test</option>
    </select>
</form>

CSS
@-moz-keyframes pulse
{
    0% {background-color: #45CEEF;}
    25% {background-color: #FFF5A5;}
    50% {background-color: #FFD4DA;}
    75% {background-color: #99D2E4;}
    100% {background-color: #D8CAB4;}
}
@keyframes pulse
{
    0% {background-color: #45CEEF;}
    25% {background-color: #FFF5A5;}
    50% {background-color: #FFD4DA;}
    75% {background-color: #99D2E4;}
    100% {background-color: #D8CAB4;}
}
@-webkit-keyframes pulse {
    0% {background-color: #45CEEF;}
    25% {background-color: #FFF5A5;}
    50% {background-color: #FFD4DA;}
    75% {background-color: #99D2E4;}
    100% {background-color: #D8CAB4;}
}
body
{
    -webkit-animation: pulse 80s infinite alternate;
    -moz-animation: pulse 80s infinite alternate;
    animation: pulse 80s infinite alternate;
    background-color: #45CEEF;
}

For some reason, when I have a pulsating background,it messes up my select options. If you try to hover on one of the options in the form, it just twitches back and forth .. what's causing this and how would I be able to fix it? Thank you
EDIT: If I remove the CSS, the form functions as normal.

A: I've been playing around with the fiddle and looking around various sites - they all implement it the same way as you do - I guess the only other alternative would be to use JS?


text:
Q: RichTextBox performance issues(Too much text in the textbox) Currently I am trying to load my log files into a RichTextBox, but the problem is that when I scroll down the text always loads because the log file has a lot of data (65mb). The performance deteriorates so much within 50 seconds that my program freezes.
Does anyone have improvement suggestions or a solution for me .
My current trainee task is to write a search tool where you can read log files and search them for certain keywords. Should I possibly use an element other than a RichTextBox?

A: 65meg of data is a lot to hold into memory, whichever way you look at this.
Meaning there could well be other issues you will encounter along the way.
Work on them when you find them though.
For now you need something that can possibly work.
This sample here uses a listbox to present a row per line.
Each row is a listview which is horizontally arranged.
The data for each listview consists of the strings split using a regex.
One with no match, up to three if one match is found in a line.
There is a viewmodel (RunHI) per chunk which has a IsMatch property.
When that is true, the background is set to yellow by a datatrigger.
https://gallery.technet.microsoft.com/WPF-Highlight-Matching-71ad5a04
The sample works with a fixed list of strings but you can readallines https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=netframework-4.8 into an array and foreach that.


text:
Q: Get count of day types between two dates I am trying the get the count of week days between two dates for which I have not found the solution in BigQuery standard sql. I have tried the BQ sql date function DATE_DIFF(date_expression_a, date_expression_b, date_part) following published examples, but it did not reveal the result.
For example, I have two dates 2021-02-13 and 2021-03-31 and my desired outcome would be:

MON
TUE
WED
THUR
FRI
SAT
SUN

6
6
6
6
7
7
7

A: Consider below approach
with your_table as (
  select date
  from unnest(generate_date_array("2021-02-13", "2021-03-30")) AS date
)
select * from your_table
pivot (count(*) for format_date('%a', date) in ('Mon','Tue','Wed','Thu','Fri','Sat','Sun'))

with output

Or you can just simply do
select
  format_date('%a', date) day_of_week,
  count(*) counts
from your_table
group by day_of_week

with output

A: You can do the following:
SELECT
  CASE EXTRACT(DAYOFWEEK
  FROM
    dates)
    WHEN 1 THEN 'MON'
    WHEN 2 THEN 'TUE'
    WHEN 3 THEN 'WED'
    WHEN 4 THEN 'THU'
    WHEN 5 THEN 'FRI'
    WHEN 6 THEN 'SAT'
    WHEN 7 THEN 'SUN'
END
  AS day_of_week,
  COUNT(*) AS day_count
FROM
  UNNEST(GENERATE_DATE_ARRAY("2021-02-13", "2021-03-30")) AS dates
GROUP BY 1

The important part is the GENERATE_DATE_ARRAY function, that will return all the dates between the dates you're interested in. UNNEST will return one row for each date (instead of one row for the array of all dates).
From there, you can extract the day of the week thanks to the BQ date functions, and count the number of occurences with a GROUP BY day_of_week.
The above query gives the following result:


text:
Q: PowerShell error: Missing '=' operator after key in hash literal. The hash literal was incomplete I am trying to execute powershell command through cloudformation template. it is throwing below error from the log. and the same time same command is working if i execute manually from the windows powershell.
please help me! i am very new to the powershell requirements.
2023-02-13 06:24:11,459 [ERROR] Command 2-Reboot (powershell.exe -Command {Import-Module -name AWSPowerShell; [string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-se
conds" = "21600"} -Method PUT -Uri http://169.254.169.254/latest/api/token; $instanceId = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} -Method GET -Uri http://169.254.
169.254/latest/meta-data/instance-id; Write-Output "reboot instance $instanceId through API"; Restart-EC2Instance -InstanceId $instanceId}) failed
2023-02-13 06:24:11,459 [DEBUG] Command 2-Reboot output: At line:1 char:84

+ ... WSPowerShell; [string]$token = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

Missing '=' operator after key in hash literal.

At line:1 char:84

+ ... WSPowerShell; [string]$token = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

The hash literal was incomplete.

At line:1 char:231

+ ... atest/api/token; $instanceId = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

Missing '=' operator after key in hash literal.

At line:1 char:231

+ ... atest/api/token; $instanceId = Invoke-RestMethod -Headers @{X-aws-ec2 ...

+                                                                  ~

The hash literal was incomplete.

    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException

    + FullyQualifiedErrorId : MissingEqualsInHashLiteral

i am trying to execute powershell command through cloudformation template. it is throwing above error from the log. and the same time same command is working if I execute manually from the windows PowerShell.


text:
Q: Getting Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays I'm trying to acces API on localhost 8080 called eatGroups:
I'm getting this error in a Angular8 frontend:
component.html file looks like
   <li *ngFor="let eatGroup of eatgroupService">
        {{ eatGroup.name }}
   </li>

component.ts looks like:
import { Component, OnInit } from '@angular/core';
import { EatgroupService} from "../eatgroup.service";

@Component({
  selector: 'app-eatgroup-list',
  templateUrl: './eatgroup-list.component.html',
  styleUrls: ['./eatgroup-list.component.css']
})
export class EatgroupListComponent implements OnInit {
  eatgroups: Array<any>;

  constructor(private eatgroupService: EatgroupService) { }

  ngOnInit() {
    this.eatgroupService.getAll().subscribe(data => {
      this.eatgroups = data;
      }
    );
  }
}

eatgroup.service.ts look like:
import { Injectable } from '@angular/core';
import { HttpClient} from "@angular/common/http";
import { Observable} from "rxjs";

@Injectable({
  providedIn: 'root'
})

export class EatgroupService {

  constructor(private http: HttpClient) {
  }

  public getAll(): Observable<any> {
    return this.http.get('//localhost:8080/eatGroups');
  }

}

Browser
But when i go to my browser, i get a message in the console:
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Any ideas?

A: You're using an *ngFor on eatgroupService which is essentially an Object. I think you wanted to iterate through eatgroups which is your array.
This:
<li *ngFor="let eatGroup of eatgroupService">
    {{ eatGroup.name }}
</li>

Should be:
<li *ngFor="let eatGroup of eatgroups">
    {{ eatGroup.name }}
</li>

You might also want to initialize them to an empty array:
eatgroups: Array<any> = [];

BETTER APPROACH
Don't subscribe to the Observable. Use the async pipe in the template instead:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/observable';
import { EatgroupService} from "../eatgroup.service";

@Component({
  selector: 'app-eatgroup-list',
  templateUrl: './eatgroup-list.component.html',
  styleUrls: ['./eatgroup-list.component.css']
})
export class EatgroupListComponent implements OnInit {
  eatGroups$: Observable<Array<any>>;

  constructor(private eatgroupService: EatgroupService) { }

  ngOnInit() {
    this.eatGroups$ = this.eatgroupService.getAll();
  }
}

And then in your template:
<ul *ngIf="eatGroups$ | async as eatGroups">
  <li *ngFor="let eatGroup of eatGroups">
    {{ eatGroup.name }}
  </li>
</ul>

PS: Make sure that you are indeed getting an array from the getAll() method.


text:
Q: Type hint for returning loguru logger Does anyone know the proper type hint for returning a loguru logger? Using loguru.Logger passes mypy checks, but when the function get_logger is called I get the error AttributeError: module 'loguru' has no attribute 'Logger'
import copy
from pathlib import Path
from sys import stdout

from loguru import logger
import loguru

def get_logger(log_path: Path) -> loguru.Logger:
    logger.remove()
    logger_ = copy.deepcopy(logger)
    logger_.add(stdout)
    logger_.add(f"{log_path}.log")

    return logger_

A: I learned that loguru.Logger is correct and can be used without throwing an error if from __future__ import annotations is added to the list of imports.
This comes from the loguru type hint documentation

A: I tried the answer above answer but failed, well I solved it by
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from loguru import Logger


text:
Q: Able to read childByAutoId but not custom named nodes? I'm trying to read the child "Arts & Humanities" by reading:
Database.database().reference().child("posts")
//NOT WORKING

However it's not working. However, when my data is structured like the image below, it works

NOTE: I'm avoiding coding it like:
Database.database().reference().child("Arts & Humanities)

since there are other Childs on this level that I need to read (i.e "Science")
What am I doing wrong?

A: It's a bit hard to understand your question and issues ("Not working" is of little help).
However, the following code allows you to iterate over the children of "posts".
let dbRef = Database.database().reference(withPath: "posts")
dbRef.child("Arts & Humanities").observeSingleEvent(of: .value, with: { (snapshot) in

    // Iterate over auto ids
    for id in snapshot.children.allObjects as! [DataSnapshot] {

        // Print the id
        print(id.key)

        // Get the value of id children like this
        let genre = id.childSnapshot(forPath: "genre").value as? String
        // ...and so on
    }
})


text:
Q: Multiple Conditional formatting to highlight a third cell when two cells match I wanted to highlight a third cell when a first cell matches with a second cell in a list. I used this formula which worked =COUNTIF(V5,$E$5:$E$310) with V5 being the first cell and e5 to e310 being the list I'm looking in. This worked out well except the problem is I have almost 600 cells I want to do this too and I don't want to have to enter in each cell the same conditional formating. When I tried to do it for all cells I realised that I could only get them to look in the same first cell V5, not V5 then the next cell down V6 then V7 etc.
Is there a way to do mass conditional formatting or this or any other type of way to basically highlight or fill in a third cell when matching a 1st with a second cell in a list with the 1st cell changing by dropping down a cell each time?
I hope I've explained this well.

A: Are you sure =COUNTIF(V5,$E$5:$E$310) is giving you the results you want?
I believe that you should be using =COUNTIF($E$5:$E$310,V5).
Are the 600 cells in the same column, consecutive?
If so, just select them, go into Conditional Formatting, and insert the rule.
It should work the way you want


text:
Q: Firebase Firestone rules with collection group ressource data I want to delete all students in my Firestore database, to do this I used collection group but I had a problem with rules: I can't achieve to authorize read, delete & update permissions.
Code
Here is the dart code in Flutter to retrieve all students in any nested collections AND delete them:
FirebaseFirestore.instance
  .collectionGroup('students')
  .where('studentId', isEqualTo: studentId)
  .get()
  .then((querySnapshot) async {
    for (var snapshot in querySnapshot.docs) {
      await snapshot.reference.delete();
    }
  }
});

Rules
The rules I used but doesn't work because It seems resource.data.classId can't be accessed...
function isClassBelongToUser(classId) {
  return classId in get(/databases/$(database)/documents/users/$(request.auth.uid)).data.classIds
}

match /{path=**}/students/{id} {
  allow read, delete, update: if isSignedIn() && isClassBelongToUser(resource.data.classId); // TODO: resource.data.classId seems to not work
}

My database
classes / CLASS_ID / (students: collection, name: string, ...)
users / USER_ID / (classIds: array, firstName: string, ...)

A: Security rules don't filter data, but instead merely ensure that the operation you perform is authorized. See the documentation on rules are not filters.
Since your isClassBelongToUser check requires that the user exists in the classIds of a specific document, your query must ensure this condition is satisfied too. Since Firestore can only filter on values in the documents it returns, such a condition is unfortunately not possible.
You will have to adapt your data model to allow the use-case, for example by replicating the necessary information into the students document(s).


text:
Q: What should I do to create iOS Build in React Native Expo? Reason: Unknown reason, raw: {"type":"Spaceship::ProgramLicenseAgreementUpdated","message":"You currently don't have access to this membership resource. To resolve this issue, agree to the latest Program License Agreement in your developer account. Please manually log into your Apple Developer account to review and accept the updated agreement.","backtrace":["/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/client.rb:742:in detect_most_common_errors_and_raise_exceptions'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/client.rb:708:inparse_response'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/portal/portal_client.rb:115:in block in apps'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/client.rb:317:inblock in paging'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/client.rb:315:in loop'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/client.rb:315:inpaging'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/portal/portal_client.rb:108:in apps'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/portal/app.rb:85:inall'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/vendor/ruby/2.2.0/gems/fastlane-2.136.0/spaceship/lib/spaceship/portal/app.rb:111:in find'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/app/ensure_app_exists.rb:21:inensure_app_exists'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/app/ensure_app_exists.rb:42:in block in <main>'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/app/funcs.rb:4:inwith_captured_stderr'","/mnt/c/Users/Dell/AppData/Roaming/npm/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux/traveling-fastlane-1.11.4-linux-x86_64/lib/app/ensure_app_exists.rb:38:in `'"]}
This is the error I am getting in Console. But I am unable to resolve this. If anyone has any idea, please share.

A:
message":"You currently don't have access to this membership resource.
  To resolve this issue, agree to the latest Program License Agreement
  in your developer account. Please manually log into your Apple
  Developer account to review and accept the updated agreement."

Try to access this URL http://developer.apple.com/membercenter/index.action and login with your Apple developer account. You need to agree to the licenses there.
I've seen some cases where people report that it's better to do this in Safari (sometimes the alerts don't show in other browsers)


text:
Q: Android : How to add child view on top of Softkeyboard for Emoji? I want to add a view with EmojiView on top of keyboard using EmojiView. Now I want functionality like when I onkey like primary code anything for EmojiView. I want to display a EmojiView on top of Softkeyboard. Means like adding pick from own view as subview of keyboard.
How can I do this?
Thanks for advance. Please share your code..

A: You can use PopupWindow, it shows on top of Softkeyboard.
Look at https://github.com/ankushsachdeva/emojicon

A: Add library in your project and use following code:
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);

View popupView = layoutInflater.inflate(R.layout.popup, null);
popupWindow = new EmojiconsPopup(popupView, getApplicationContext());
// final PopupWindow popupWindow = new PopupWindow();
popupWindow.setSizeForSoftKeyboard();
popupWindow.setSize(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
popupWindow.showAtLocation(mInputView.getRootView(), Gravity.BOTTOM, 0, 0);

// Bring soft keyboard up : NOT WORKING
final InputMethodManager mInputMethodManager = (InputMethodManager) getBaseContext()
    .getSystemService(Context.INPUT_METHOD_SERVICE);

mInputMethodManager.showSoftInput(popupView, 0);

// If the text keyboard closes, also dismiss the emoji popup
popupWindow.setOnSoftKeyboardOpenCloseListener(new OnSoftKeyboardOpenCloseListener() {

    @Override
    public void onKeyboardOpen(int keyBoardHeight) {

    }

    @Override
    public void onKeyboardClose() {
        if (popupWindow.isShowing())
        popupWindow.dismiss();
    }
});

popupWindow.setOnEmojiconClickedListener(new OnEmojiconClickedListener() {

    @Override
    public void onEmojiconClicked(Emojicon emojicon) {
        mComposing.append(emojicon.getEmoji());
        commitTyped(getCurrentInputConnection());

        customToast("" + emojicon.getEmoji());
    }
});

popupWindow.setOnEmojiconBackspaceClickedListener(new OnEmojiconBackspaceClickedListener() {

    @Override
    public void onEmojiconBackspaceClicked(View v) {
        KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
        customToast(" " + event);
        handleBackspace();
    }
});


text:
Q: JavaScript runtime error: Unable to get property 'split' of undefined or null reference While debugging I got this error in my below part of code..
 queryStirngValue = document.referrer.split("myQuryString")[1].split("%")[1].split("253D")[1];
    alert(queryStirngValue);

A:  document.referrer.split("myQuryString")[1].split("%")

You first split on myQuryString (which by itself is misspelled?)
With [1] you then want the second array value (because arrays start at 0)
So if myQuryString is not in the QueryString you now have a null value
So
null.split("%")

causes: Uncaught TypeError: Cannot read property 'split' of undefined(…)


text:
Q: weird font size setting in different apps and random places ever since the update from 13.10 to 14.04 i have a font-size issue.
for example. With Evolution email the email will show in extremely large font-size (~18px)
while the folders and menu's are displayed in normal font-size
The same goes for Bluefish, directory and menu are displayed in normal font-size, while the edited file is displayed in extremely small font-size (< 6px)
Today i noticed a similar behavior in Mysql workbench. here the menu is displayed in extremely small font-size, while models and shortcuts are displayed normal.
i believe the only common item here is GTK. does anybody have a solution for this? or can confirm this!


text: Q: CakePHP 2.x and Atlassian Crowd I'm rolling out a number of cakePHP-based internal tools and would like to leverage our Crowd instance for user management. Has anyone successfully integrated Crowd with Cake? Do I treat it like any other LDAP provider?


text:
Q: Pulling data in a for loop where data sometimes does not exist Let's say I have four data values and one of them exists sometimes.
My For loop crashes because the path doesn't exist.
I would like to pass a "" in the cell instead of crashing.
myJSON.data[i].bank[0].money <- this part is my problem, because the bank[0].money sometimes doesn't exist.
I would like to keep the cell empty.
I tried an If but I didn't get it formatted properly, same goes for error handling.
Sub DATA()
    Set RDict = CreateObject("Scripting.Dictionary")
    Set dlist = CreateObject("Scripting.Dictionary")
    JSON_String = Form.fromURL("exampleurl")
    With CreateObject("htmlfile")
        With .parentWindow
            .execScript "var myJSON = " & JSON_String & ", csvstring = '';for (i = 0; i < myJSON.data.length; i++) {csvstring += myJSON.data[i].name + ',' + myJSON.data[i].bank[0].money + ',' + myJSON.data[i].location + ',' + myJSON.data[i].planneddate + ';';};"
            RData = Split(.csvstring, ";")
        End With
    End With
    For i = 0 To UBound(RData) - 1
        DaData = Split(RData(i), ",")
        If DaData(0) <> "null" Then RDict(DaData(0)) = DaData
    Next i
    Dim RSheet() As Variant
    If RDict.Count > 0 Then
        ReDim RSheet(2 To RDict.Count + 2, 1 To 7)
        i = 0
        For Each D In RDict
            datalist(RDict(Da)(2)) = True
            For j = 0 To 6
                RSheet(i + 2, j + 1) = RDict(Da)(j)
            Next j
            i = i + 1
        Next Da
        RSData.Cells(2, 1).Resize(i, 6) = RSheet
    End If

End Sub

A: You can handle null by using optional chaining with default nullish coalescing (#3 in example).
Something like this should work
Change myJSON.data[i]?.bank[0]?.money
To myJSON.data[i]?.bank[0]?.money ?? 'Unknown'
You can do the same with your other variables (myJSON.data[i].location and myJSON.data[i].planneddate) if they have the potential to be undefined or null as well
EDIT - Use Optional IF when optional chaining is not available
If that feature is not available in HTMLDocument's javascript maybe you can use basic conditional if?
This should work for undefined object, because undefined is == null
(myJSON.data[i].bank[0].money != null ? myJSON.data[i].bank[0].money : '-')


text:
Q: Auto-link regular expression I am using a PHP function to automatically turn URLs in a text string into an actual link that people can click on. It seems to work in most cases, however I have found some cases where it does not.
I don't really understand regular expressions at all, so I was hoping someone could help me out with this.
Here is the pattern I'm currently using:
$pattern = "/(((http[s]?:\/\/)|(www\.))(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9.,_\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";

However here are some links I have found that this pattern is not matching:

*

*www.oakvilletransit.ca - Not sure, but assuming it doesn't match because of the two-letter country code

*www.grt.ca - Another one with the .ca domain that is not working

*Several other .ca addresses

*freepublictransports.com - Addresses without www. or http:// in front of them. I would like these to work as well.

*www.222tips.com - Assuming it doesn't match because of the numbers at the beginning of the address.

Does anyone know how I can modify that regex pattern to match these cases as well?
EDIT - It should also match URLs that may have a period at the end. If a URL is the last part of a sentence there may be a period at the end that should not be included in the actual link. Currently this pattern takes that into account as well.
EDIT 2 - I am using the pattern like this:
$pattern = "/((http|https):\/\/)?([a-z0-9-]+\.)?[a-z][a-z0-9-]+(\.[a-z]{2,6}){1,3}(\/[a-z0-9.,_\/~#&=;%+?-]*)?/is";
  $string = preg_replace($pattern, " $1", $string);
  // fix URLs without protocols
  $string = preg_replace("/href='www/", "href='http://www", $string);
  return $string;

A: The following regex will match URLs:

*

*(Optionally) With http:// or https://

*(Optionally) With a subdomain (www.example.com, help.example.com, etc)

*With 1-3 domain extensions, which each must be 2-6 characters (www.example.com.gu, www.example.com.au.museum, etc)

*(Optionally) With a forward slash at the end

*(Optionally) With valid characters after the forward slash

The /i at the end makes it case insensitive.
/((http|https):\/\/)?([a-z0-9-]+\.)?[a-z0-9-]+(\.[a-z]{2,6}){1,3}(\/[a-z0-9.,_\/~#&=;%+?-]*)?/is
Edit: This will not match any "hanging" periods at the end (such as the end of a sentence) because it's not part of the URL, and shouldn't be included in the href attribute of your link.
Edit 2: In your first preg_replace(), change $1 to $0. This will insert the entire matched string instead of a single part of it.
Edit 3: (Update 2) Here's a better way you can check for a http:// or https:// at the beginning:
preg_replace("/href='[^h][^t][^t][^p][^s]?[^:]/", "/href='http:\/\/", $string);

A: I had problems with all the examples above.
Here is one that works:
function autolink($string){
        $string= preg_replace("#http://([\S]+?)#Uis", '\\1', $string);
        return $string;
}


text:
Q: Proving $\cos 36° > \tan 36° $ How do we  prove that  $\cos  36° > \tan 36° $ ? Please help . Thank you.

A: Since $\cos x$ and $\tan x$ are monotonic in the $[0,\pi/2]$, they cross at a single point, namely when:
$$\cos^2x=\sin x\ \rightarrow\  1 -\sin^2x-\sin x =0 $$
Or when:
$$\sin x=\varphi-1\ \rightarrow \ x\approx38.2^\circ$$
Since $36^\circ<38.2^\circ$, we also have $\cos 36^\circ >\tan 36^\circ$.
$_\blacksquare$

A: We all know that $\pi^2<10$. It follows that
$$\cos{\pi\over 5}>1-{1\over2}\left({\pi\over5}\right)^2>1-{10\over50}={4\over5}\ .$$
From this we conclude that
$$\cos^2{\pi\over5}>{32\over50}>{\pi\over5}>\sin{\pi\over5}\ ,$$
which is equivalent to the claim.

A: $\cos36 > \tan36 \iff \cos36 > \dfrac{\sin36}{\cos36} \iff \cos^2{36} > \sin36 \iff 1 - \sin^2{36} > \sin36 \iff \sin^2{36} + \sin36 - 1 < 0 \iff \sin36 < \dfrac{\sqrt{5} - 1}{2} (*)$. We prove $(*)$ true. let $x = \sin18$, then using $\cos36 = \sin54$ gives: $\cos(2\cdot 18) = \sin(3\cdot 18) \iff 1 - 2x^2 = 3x - 4x^3 \iff (x - 1)(4x^2 + 2x -1) = 0$. Since $0 < x < 1$, this equation gives only one solution: $x = \dfrac{\sqrt{5} - 1}{4}$. So $\cos36 = 1- 2x^2 = \dfrac{\sqrt{5} + 1}{4}$. So $\sin36 = \sqrt{1 - \cos^2{36}} = \dfrac{\sqrt{10 - 2\sqrt{5}}}{4} < \dfrac{\sqrt{5} - 1}{2} \iff \dfrac{10 - 2\sqrt{5}}{16} < \dfrac{6 - 2\sqrt{5}}{4} \iff 3\sqrt{5} < 7 \iff 45 < 49$. The last inequality is obviously true. This implies $(*)$ is true, and we're done.


text:
Q: Find UPPER Alphabets in mysql in LIKE clause? I would like to search state_Abbreviation like TX. below is the query I tried so far:
SELECT *
FROM `usa_address`
WHERE   ' One American Center, Suite 3000 600 Congress Avenue Austin , TX  78701'
             LIKE CONCAT('%',usa_address.city,'%')
    AND ' One American Center, Suite 3000 600 Congress Avenue Austin , TX  78701  '
             LIKE CONCAT('%',UPPER(usa_address.state_Abbreviation),'%')


text:
Q: Random sampling, what is the error in my reasoning Taken from Ross, first course in probability, question 11, chapter 1, self-evaluating questions:
From 10 married couples, we want to select a group of 6 people that is not allowed to contain a married couple
Books answer, which I agree makes total sense:

My answer is different,:
First pick has 20 choices, second 18, etc, giving 20*18*16*14*12 = 967680
Of those, we divide by 5! to remove dupicates (or fiveplicates I should say) of sampling, where ABCDE is the same group as EDCBA
That gives me 8048
What is the error in my reasoning?
Thanks
Christian

A: You have the right idea, but your arithmetic is off!
First off, we are choosing $6$ people. $20 \times 18 \times 16 \times 14 \times 12$ represents $5$ choices though. Instead we need $20 \times 18 \times 16 \times 14 \times 12 \times 10$. Further, we will divide by $6!$, not $5!$ to remove the 'sixplicates'. So, we have that
\begin{equation*}
\frac{20 \cdot 18 \cdot 16 \cdot 14 \cdot 12 \cdot 10}{6!} = 13440
\end{equation*}
Hope this helps


text:
Q: Python 3d Pyramid I'm new to 3d plotting. I just want to build a pyramid out of 5 Points and cut a plane through  it. My problem is I don't know how to fill the sides.
points = np.array([[-1, -1, -1],
                   [1, -1, -1 ],
                    [1, 1, -1],
                   [-1, 1, -1],
                   [0, 0 , 1]])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = [-1,1]

X, Y = np.meshgrid(r, r)

ax.plot_surface(X,Y,-1, alpha=0.5)
ax.plot_surface(X,Y,0.5, alpha=0.5,  facecolors='r')

ax.scatter3D(points[:, 0], points[:, 1], points[:, 2])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

Any help is appreciated.

A: You have to use polygons:
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# vertices of a pyramid
v = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1],  [-1, 1, -1], [0, 0, 1]])
ax.scatter3D(v[:, 0], v[:, 1], v[:, 2])

# generate list of sides' polygons of our pyramid
verts = [ [v[0],v[1],v[4]], [v[0],v[3],v[4]],
 [v[2],v[1],v[4]], [v[2],v[3],v[4]], [v[0],v[1],v[2],v[3]]]

# plot sides
ax.add_collection3d(Poly3DCollection(verts,
 facecolors='cyan', linewidths=1, edgecolors='r', alpha=.25))

plt.show()


text: Q: Is there a way to link a field of one table to a record of another table on Microsoft Access? I'm currently working on an Access model where I have 2 tables. One table would display chip IDs and the different processes it goes through, where the different process fields are yes/no checkboxes, and the other table shows the process IDs (where they are the same as the process fields of the other table) and the time taken for each process. I need to link the checked process fields for a particular chip ID to the time taken. Is there a way to link the fields to a record of the same name?


text:
Q: Moment generating function of bounded variables According to the answer of this question a moment generating function exists if the random variable $X$ is bounded.
The proof is not quite obvious to me. More formally, let $(\Omega,\mathcal{A},\mu)$ be a probability space and $X$ be a random variable taking values in an inner product space $(K,\langle\cdot,\cdot\rangle)$ over $\mathbb{R}$.
If $X$ is bounded, then there exists a constant $M\in\mathbb{R}$, such that $||X(t)||\leq M$ for all $t\in\Omega$, where $||x|| = \sqrt{\langle x,x\rangle}$.
A moment generating function $m(t)=\mathbb{E}e^{\langle t,X\rangle}$ is said to exist, iff
$$
\int_\Omega e^{\langle t,X\rangle} \, \mathrm{d}\mu < \infty.
$$
Can someone point me to the proof?

A: Almost surely for $P(\mathrm d\omega)$, $\mathrm e^{\langle t,X(\omega)\rangle}\leqslant \mathrm e^{\|t\|\cdot\|X(\omega)\|}\leqslant \mathrm e^{\|t\|\cdot M}$, hence $m(t)\leqslant\mathrm e^{\|t\|\cdot M}$.

A: For a fixed $t$ we have  $\left\langle t,X\right\rangle \leq\left\Vert t\right\Vert \left\Vert X\right\Vert \leq\left\Vert t\right\Vert M$
and consequently $$e^{\left\langle t,X\right\rangle }\leq e^{\left\Vert t\right\Vert \left\Vert X\right\Vert }\leq e^{\left\Vert t\right\Vert M}$$

edit:
If $\mu$ is a probablity measure then for constant $c$ we find: $$\int_{\Omega}cd\mu=c\int_{\Omega}d\mu=c\mu\left(\Omega\right)=c$$
Applying that here gives:  $$\int_{\Omega} e^{\left\langle t,X\right\rangle }d\mu\leq\int_{\Omega} e^{\left\Vert t\right\Vert M}d\mu=e^{\left\Vert t\right\Vert M}$$


text:
Q: Text dissapears when image is loaded from picasso - Android I have a recycler view which loads an image and a text. When the image is loaded from the url though picasso other elements is the recycler view loose their text. The elements who loose their text they dont load their image from www but from android drawable folder. All the images are the same size and i tried it with the same image and it still happens. If you could provide any insights because i dont know what to do or try.

Here is a gif of my problem: https://giphy.com/gifs/hR5w7IrCZ14T9M8o7A
--- Edit ----
Tried the answer from Radesh didnt work. Tried glide instead of picasso (seems glide to be much faster). The problem seems to be the way recycler updates.
My onBindViewHolder
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, int i) {
    myViewHolder.textItem.setText(categoryItem.get(i).getEng_name());
    if (categoryItem.get(i).getDefault_image().equals("empty") || categoryItem.get(i).getDefault_image().length() == 0) {
        Picasso.get().load(R.drawable.no_image).into(myViewHolder.image);
    } else {
        Glide.with(myViewHolder.context).load("https://i.ibb.co/wwT602t/lake-plastira.jpg").into(myViewHolder.image);
        //Picasso.get().load("https://i.ibb.co/wwT602t/lake-plastira.jpg").placeholder(R.drawable.loading_image).error(R.drawable.failed_to_load).into(myViewHolder.image);
    }
}

My xml for the items loaded
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardBackgroundColor="?attr/color4">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/item_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:src="@drawable/no_image"
        android:scaleType="fitStart" />
    <TextView
        android:id="@+id/item_name"
        android:textColor="?attr/color6"
        android:textSize="20sp"
        android:gravity="center"
        android:layout_gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>

My recyclerView code
    recyclerView = (RecyclerView) findViewById(R.id.categories_rec);
    recyclerView.setHasFixedSize(true);
    layoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(layoutManager);
    mAdapter = new SpecificCategoryAdapter(categoryItem);
    recyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();

A: change this code
   <TextView
        android:id="@+id/item_name"
        android:textColor="?attr/color6"
        android:textSize="20sp"
        android:gravity="center"
        android:layout_gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

To this
  <TextView
        android:id="@+id/item_name"
        android:textColor="?attr/color6"
        android:textSize="20sp"
        android:gravity="center"
        android:singleLine="true"
        android:maxLines="1"
        android:layout_gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

A: So I find a solution I used a runnable and the problem was solved. If you have any other idea please post it. I believe that this behaviour happened because that function never ended because it was waiting for the image.
 myViewHolder.textItem.setText(categoryItem.get(i).getEng_name());
  if (categoryItem.get(i).getDefault_image().equals("empty") || categoryItem.get(i).getDefault_image().length() == 0) {
      Picasso.get().load(R.drawable.no_image).into(myViewHolder.image);
  } else {
      final Handler handler = new Handler();
      final Runnable r = new Runnable() {
          public void run() {
              Glide.with(myViewHolder.context).load("https://i.ibb.co/wwT602t/lake-plastira.jpg").into(myViewHolder.image);
          }
      };
      handler.postDelayed(r, 1000);
  }


text:
Q: What is the best way to implement a timer that will be stopped and restarted in a Java Swing Application? Ok, I'm working on my final dilemna for my project.  The project is an IPv4 endpoint updater for TunnelBroker's IPv6 tunnel.  I have everything working, except for the timer. It works, however if the user disables the "automatic update" and reenables it, the application crashes.  I need the timer to be on an thread outside of the EDT (in such a way that it can be destroyed and recreated when the user unchecks/checks the automatic update feature or changes the amount of time between updates).
What I'm pasting here is the code for the checkbox that handles automatic updates, and the timer class.  Hopefully this will be enough to get an answer on how to do this (I'm thinking either it needs to be a worker, or use multi-threading--even though only one timer will be active).
 private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
    // TODO add your handling code here:
    // if selected, then run timer for auto update
    // set time textbox to setEditable(true) and get the time from it.
    // else cancel timer.  Try doing this on different
    // class to prevent errors from happening on reselect.
    int updateAutoTime = 0;

    if (jCheckBox1.isSelected())
    {
        updateAutoTime = Integer.parseInt(jTextField4.getText())*60*1000;
        if (updateAutoTime < 3600000)
        {
            updateAutoTime = 3600000;
            jTextField4.setText(new Integer(updateAutoTime/60/1000).toString());
        }
        updateTimer.scheduleAtFixedRate(new TimerTask() {
    public void run()
    {
        // Task here ...
        if (jRadioButton1.isSelected())
        {
            newIPAddress = GetIP.getIPAddress();
        }
        else
        {
            newIPAddress = jTextField3.getText();
        }
         strUsername = jTextField1.getText();
         jPasswordField1.selectAll();
         strPassword = jPasswordField1.getSelectedText().toString();
         strTunnelID = jTextField2.getText();
         strIPAddress = newIPAddress;
         if (!newIPAddress.equals(oldIPAddress))
         {
             //fire the tunnelbroker updater class
             updateIP.setIPAddress(strUsername, strPassword, strTunnelID, strIPAddress);
             oldIPAddress = newIPAddress;
             jLabel8.setText(newIPAddress);
             serverStatus = updateIP.getStatus().toString();
             jLabel6.setText(serverStatus);
         }
         else
         {
             serverStatus = "No IP Update was needed.";
             jLabel6.setText(serverStatus);
         }
        }
}, 0, updateAutoTime);

    }
    else
    {
       updateTimer.cancel();
       System.out.println("Timer cancelled");
       System.out.println("Purged {updateTimer.purge()} tasks.");
    }

}

As I mentioned, this works once. But if the user deselects the checkbox, it won't work again. And the user can't change the value in jTextField4 after they select the checkbox.
So, what I'm looking for is this:

*

*How to make this so that user can select and deselect the checkbox as they want (even if it's multiple times in a row).

*How to make this so the user can change the value in jTextField4, and have it automatically cancel the current timer, and start a new one with the new value (I haven't done anything with the jTextField4 at all, so I'll have to create an event to cover it later).

Thanks, and have a great day:)
Patrick.

A: Perhaps this task would be better suited to a javax.swing.Timer.  See Timer.restart() for details.
Note that Timer is relatively inaccurate over long time periods.  One way to account for that is to have it repeat frequently but perform it's assigned task only one a certain time has been reached or passed.

Would I be able to wrap everything in the "task" portion of the call to Swing Timer, or do I have to create another class that handles the task?

You might want to wrap the grunt work in a SwingWorker to ensure the EDT is not blocked.

..I'm assuming that I would have to create the timer as a class-level declaration .. correct?

Yes, that is what I was thinking.


text:
Q: React Native - Unable to resolve module Before adding this question , I have checked previous answers. Unfortunately I didn't find any fit to this. I'm a beginner in React Native and I'm following a tutorial. I'm getting this error.

index.android.js
import React from 'react';
import { AppRegistry } from 'react-native';
import Header from './src/components/header';

const App = () =>(
    <Header/>
);

AppRegistry.registerComponent('albums' , ()=>App);

header.js
    import React from 'react';
import { Text } from 'react-native';

const Header = () => {
  return <Text> Albums ! </Text>;
};

export default Header;

A: //import lib
import React from 'react';
import {AppRegistry,View} from 'react-native';
import Header from './src/components/Header';

// create the component
const App = () => {
  return (
              <Header />
    );
};
// render the component
AppRegistry.registerComponent('ListItem', () => App);

Header.js
import React from 'react';
import { Text } from 'react-native';

const Header = (props) => {
  return(
     <Text > Albums ! </Text>
 );
};

export default Header;

A: You are providing a wrong path please correct this
import Header from './src/components/Header';

With
import Header from '../src/components/Header';

A: I think you need to pass in the props from your index.android.js to your header.js.In your original code,you set const Header = (props) => { in your header.js,but you didn't pass the props in your index file.
    //import lib
import React from 'react';
import {AppRegistry,View} from 'react-native';
import Header from './src/components/Header';

// create the component
const App = () => {
  return (
       <Header headerText={'Albums'} />
    );
};
// render the component
AppRegistry.registerComponent('ListItem', () => App);

header.js
import React from 'react';
import { Text } from 'react-native';

const Header = (props) => {
  return(
     <Text > {props.headerText} </Text>
 );
};
export default Header;


text:
Q: Call a new batch file or add VB script? What I have below allows a user to enter the name of a device, from a batch Menu, which will then telnet in a new command window and automatically log them in. After the below batch runs I then want the user to be prompted for a new variable (Host). Once the user enters the new variable (Host) I want the batch to continue on, within the same window, and ping the new variable (Host).
I tried the call command but it opens a new window every which way i try it. Do I need a vbscript? I'm a bit lost.
@echo off
:A
color 0A
Cls
echo.
echo.
echo.
echo Putty SSH
echo.
echo.
echo.
set /p computer=HOST:
start putty.exe -ssh xxxxxx@%computer% -pw xxxxxx
goto:options

Example of what I want to come next. I do not know how to add the lines below to the batch script above and make them execute in the window opened by "start putty.exe -ssh xxxxxx@%computer% -pw xxxxxx. I want the %computer% to be a new variable. Not from the variable in the batch above.
"
set /p computer=HOST:
ping %computer%

A: Sadly there's no way to do this from batch files.
As soon as you "call a command" from a batch it is considered as something independent from the rest of your batch calls either executed previously or will execute later.
I'd recommend creating a vbs file even on the first go and use that for all the operations you want.
Here's a little sample code for you to see how to 'manage' a command window you started up from your vbs:

    Option Explicit
Dim oShell

Set oShell = CreateObject("WScript.Shell")
REM 1 == windowstate normal, false==don't wait for app to finish running
Call oShell.Run ("cmd /K CD C:\", 1, false)
Call WScript.Sleep (300)

REM you don't need it right after cmd.exe started up as it'll be
REM focused/activated by OS but may need later
REM Call oShell.AppActivate ("cmd.exe")

Call oShell.SendKeys ("echo yay! {ENTER}")

SET oShell = Nothing

You can find a list of commands you may use with 'SendKeys' function:
http://msdn.microsoft.com/en-us/library/8c6yea83%28v=vs.84%29.aspx
Hope this helps!