How can I ensure migration YAML files execute in specified dependency order?

Question: EDIT: To Answer my own question...
I ended up making multiple migration files like this:

Node Type A Part 1 (most fields migrated except the ones that need to reference Node Type B)
Node Type B
Node Type A Part 2 (now you can add the field referencing Node Type B)
etc.

Here's a Github link to my finalized set of real-world migration files which illustrate how I broke up my migration into different sequential parts. Good luck!

Original Question:
My Drupal migration yaml files are not being imported in the correct execution order.
I have 8 migration files, most that depend on another file being executed first. I'm
using a Google Spreadsheet as the source, and targeting Drupal 8.9+. I have tagged all my dependencies, and all was going well with my test imports (using drush migrate:import --tag="Rooster Business") and the corresponding rollback commands. But at some point, after adding a few fields, the migrations began to fail because they were being executed out of order (particularly my business_locations and business_offers migrations).
Here's the exact error:
[error]  Migration rooster_node_business_offers did not meet the requirements.
Missing migrations rooster_node_business_location. requirements: rooster_node_business_location.

The new fields themselves don't fail, so it's not that (I wouldn't think). I think I have correctly set up the dependencies in all the files, but they are NOT being respected (at least not completely).
I have tried the following:

Alphabetizing all the migration id's and filenames (to order them by desired import execution order).
Dropping all migration tables from the database and doing full cache refresh
Changing the last file I want executed (rooster_node_business_offers) to use "optional" dependencies instead of "required." (This causes the failure to go away, but then some of the desired field values are missing from the migration).
Uninstalling and reinstalling the entire custom migration module.
I've tried just migrating the "last" migration with drush migrate:import rooster_node_business_offers --execute-dependencies command which should in theory execute all the files in order as they all depend in a chain on each other. No dice. I get the same error: [error]  Migration rooster_node_business_offers did not meet the requirements...

None of these attempts have solved the problem. I have a theory that it has something to do with the fields names of the sources (because I think I may have changed a few of them, and have definitely added quite a few). But that still doesn't account for why the migrations are not respecting the dependency order.
Bottom line: I have two questions:

Why are the last two migration files (rooster_node_business_location & rooster_node_business_offers) not being executed in order by dependency (and how can I fix this)?
If that is not an easy to answer question, what is the logic of the "default" ordering, and how can I game that logic so I can still get my migration files to execute in the desired order?

Here is the order I'd LIKE to have the migrations to execute in:
rooster_file_bg_photo
rooster_file_logo
rooster_users
rooster_file_logo_to_media
rooster_file_bg_photo_to_media
rooster_node_parent_business
rooster_node_business_location
rooster_node_business_offers

And here is the order that they are actually being migrated in (same as the order displayed after entering the drush ms command:
  Rooster (Rooster)   rooster_file_bg_photo            Idle
  Rooster (Rooster)   rooster_file_logo                Idle
  Rooster (Rooster)   rooster_users                    Idle
  Rooster (Rooster)   rooster_file_logo_to_media       Idle
  Rooster (Rooster)   rooster_file_bg_photo_to_media   Idle
  Rooster (Rooster)   rooster_node_parent_business     Idle
  Rooster (Rooster)   rooster_node_business_offers     Idle
  Rooster (Rooster)   rooster_node_business_location   Idle

I've made a repository of my exact migration files (and I've only redacted the Google Spreadsheet URLs). Here are all the migration files on Github.
Thanks in advance for your help!
Comment: Simply specify `nid` (or uid key in case of user entity) in the `process` section of migration #1B, e.g. through a `migration_lookup` or `entity_lookup`, then you can update an existing entity.
Comment: So, I did some more research. As I suspected, you ARE allowed to reference migration_lookups for migrations that are imported afterwards. BUT, there is a bug. The id of the migration file needed in subsequent references has to be in REVERSE alphabetical order: https://www.drupal.org/project/drupal/issues/3024634
Comment: @miststudent2011 I will have to go back and look at the exact migration files, but I recall that I just made another file that basically filled in the missing lookups after the dependancy was filled in. So...if part of A needs to lookup something populated by B, make a C file that runs after B is complete. I'll share my files after I get into work. Cheers.
Comment: @miststudent2011FYI, I updated my question with a link to a github repo I just created with all my finalized migration files. You'll notice that I broke up the migration into two parts for two different node types because I wanted them to reference each other. Hope that helps
Comment: A migration can't be optional if you use its ID in this migration with `migration_lookup`. And you have a circular dependency between your last two migrations.
Comment: It was my understanding that migrations that need data from a migration that come afterwards will create stubs and then insert that data once the migration becomes available. As a matter of fact, this has worked in my migrations when the migrations were executed in order. Do you know how I can at least get the migrations to execute in the order I want?
Comment: I just commented out the migration_lookup fields that required subsequent migrations. But now my nodes don't have references to each other. Is there a way to write a few additional YAML files that import/process these reference fields (this time, after the requisite migrations) without overwriting the values of all the other previously imported fields? For example, Can Migration #1A with Fields A-C be imported, then Migration #2 which depends on Migration #1A, THEN Migration #1B with field D (which depends on Migration #2)? Basically, I'd like some migration files to UPDATE, not overwrite.
Comment: @Hudri Thanks for you're help...but I'm still facing problems. I tried to do both a migration_lookup and an entity_lookup: ([see file 074_rooster_node_parent_business2](https://gist.github.com/Doomd/458d38ab34a4266003cc5cf0cff5d971)), and I get an error after all the other migrations get processed (`rooster_node_parent_business2 Migration - 9 failed`). I'm sure I set it up wrong, but I there's little documentation on migrating additional fields into the same previously migrated content all in the same migration group/tag...
Comment: @Doomd were you able to resolve the with unmet dependency even though its present ? If yes, can you pls share the solution ?
Comment: @Doomd thanks for the update but it seems URL to the GIT repo is wrong. I was able to solve the issue I will add my solution to this question so others can benefit.
Answer: I was able to solve the migration dependency unmet error.
Here is my approach to resolve the issue.
For example you have three migrations migration_a , migration_b and migration_c , and migration_a is dependent on migration_b and migration_b is dependent on migration_c.
What you have to do is define migration_b as optional dependency in migration_a and similarly define migration_c as optional dependency in migration_a  .
Then import the migration_c manually first with the command drush mim migration_c and later migration_b with command drush mim migration_b and finally drush mim migration_a
Thus you have your migration imported.
Please let me know if you have any additional suggestions to resolve the issue.

There are other solutions which are scattered across the drupal.org to resolve the issue but they did not help me to resolve the issue.

Name the migrations in the alphabetical order respective to their migration order.
Check whether the line is defined $settings['cache']['default'] = 'cache.backend.null'; relevant bug


Smart Card S/MIME with Exchange 2013

Question: I have an Exchange 2013 environment that I'm trying to implement S/MIME with smart cards.  To the best of my knowledge, and the little help I have received on TechNet, I have configured my Exchange server correctly.  I have installed the S/MIME controls on a Windows computer, I am able to log into OWA with a smart card, but when I try to sign an email or tell OWA which certificate to choose for digital signatures, nothing happens.
Has anyone successfully signed or encrypted an email using a smart card with OWA 2013, or have any ideas about what might be causing this problem?
Comment: Is anything logged to the Windows Event logs when you try to choose a certificate?
Comment: Sorry for the late replay.  No events are logged and my card reader does indicate that the card was even accessed.
Comment: If you insert your the smart card to the reader, what are the certificates does your system detects? Does it also detect the certificate for mail encryption?
Comment: All of the certificates are detected just fine.  If I load up Outlook 2013 I can send Signed, Encrypted and Decrypt emails all day.  If I try OWA on the same computer it doesn't work.  Do you have this working in your environment?
Answer: I found the problem.  First, the Signing cert was missing Email Protection EKU.  Second, the emails need to be sent as plain text.  I have yet to find the document that states the users emails must be sent as plain text for this to work in a browser, so if somebody comes across it, please enlighten me.

Smart Card S/MIME with Exchange 2013


Panel data Clustering

Question: I have panel data of variable X consisting of 15 yrs-time points and 103 countries. I want to cluster countries in four group. Please suggest appropriate  method and software to run panel data clustering. Thanks
Answer: In this case you don't necessarily need to take the time-component into account. Just treat your 103 countries as instances, where each instance is represented by a vector of length 15 (the yearly measurements of $X$ for this country) and run a simple $k$-means clustering with $k=4$.
You might want to check for different values of $k$, though, e.g. using the elbow method.
Comment: Thank you Edgar. So I should take one year data point for 103 countries and then run a simple k-mean clustering.

Panel data Clustering


jekyll theme - how can i bypass this color setting

Question: Im editing this jekyll theme with github pages and im trying to add buymeacoffee generated button in menu bar.
It works but for some reason it gets the theme colors, i tried to debug it hours now but it didn't work.
The button should look like this:
https://i.stack.imgur.com/mBgk1.png
But now:
https://i.stack.imgur.com/nr5Lt.png
I added it in _includes/navbar.html in the end of the file. I tried to placed it in other files too, outside divs inside divs with custom css classes nothing worked.
Looks like it gets a "general" color, i tried to find this setting but i couldn't, can any of you help me to figure it out? thank you!
Answer: you can selector level of custom css  in _dark.scss.
Example, you can change with this.
body[data-theme="dark"] .bmc-btn-container > a.bmc-btn:hover {
    color: black;
}

Comment: Hello, thanks for your answer. This worked but it broke the theme :/
Comment: You can import custom scss file in your directory. This file under the theme's *scss file. When you can render, you can see update related color.
Comment: Can you give me an example?


Improved reduce0 CUDA reduction code not working

Question: I have written a CUDA code that basically sums an array for me. THe array size N should be a power of of 2, namely, 2^x. However, my code is not working properly. For example, if the output is 150177410, my code outputs 150177408. I have been trying to debug this for the past 5 hours. Any help will be appreciated. Below is the code:
//only for array size of 2^x and TPB of 2^y as godata is = num of blocks. But num of blocks 2^sth if previous satisfied
//Works for arbitrary size array of type 2^x

#include<stdio.h>

__global__ void computeAddShared(int *in , int *out, int sizeInput){
    //not made parameters gidata and godata to emphasize that parameters get copy of address and are different from pointers in host code
    extern __shared__ float temp[];

    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    int ltid = threadIdx.x;
    temp[ltid] = 0;
    while(tid < sizeInput){
        temp[ltid] += in[tid];
        tid+=gridDim.x * blockDim.x; // to handle array of any size
    }
    __syncthreads();
    int offset = 1;
    while(offset < blockDim.x){
        if(ltid % (offset * 2) == 0){
            temp[ltid] = temp[ltid] + temp[ltid + offset];
        }
        __syncthreads();
        offset*=2;
    }
    if(ltid == 0){
        out[blockIdx.x] = temp[0];
    }

}

int main(){

    int N = 8192;//should be 2^sth
    int size = N;
    int *a = (int*)malloc(N * sizeof(int));
    /* TO create random number
    FILE *f;
        f = fopen("invertedList.txt" , "w");
        a[0] = 1 + (rand() % 8);
        fprintf(f, "%d,",a[0]);
        for( int i = 1 ; i< N; i++){
            a[i] = a[i-1] + (rand() % 8) + 1;
            fprintf(f, "%d,",a[i]);
        }
        fclose(f);
        return 0;*/
    FILE *f;
    f = fopen("invertedList.txt","r");
    if( f == NULL){
            printf("File not found\n");
            system("pause");
            exit(1);
    }
    int count = 0 ;
    long actualSum = 0;
    for( int i =0 ; i < N ; i++){
        fscanf(f, "%d,", &a[count]);
        actualSum+=a[count];
        count++;
    }
    fclose(f);
    printf("The actual sum is %d\n",actualSum);
    int* gidata;
    int* godata;
    cudaMalloc((void**)&gidata, N* sizeof(int));
    cudaMemcpy(gidata,a, size * sizeof(int), cudaMemcpyHostToDevice);
    int TPB  = 256;
    int blocks = 10; //to get things kicked off
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start, 0);
    while(blocks != 1 ){
        if(size < TPB){
            TPB  = size; // size is 2^sth
        }
        blocks  = (size+ TPB -1 ) / TPB;
        cudaMalloc((void**)&godata, blocks * sizeof(int));
        computeAddShared<<<blocks, TPB,TPB*sizeof(int)>>>(gidata, godata,size);
        //cudaFree(gidata);
        gidata = godata;
        size = blocks;
    }
    //printf("The error by cuda is %s",cudaGetErrorString(cudaGetLastError()));

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    float elapsedTime;
    cudaEventElapsedTime(&elapsedTime , start, stop);
    printf("time is %f ms", elapsedTime);
    int *output = (int*)malloc(sizeof(int));
    cudaMemcpy(output, gidata,size *  sizeof(int), cudaMemcpyDeviceToHost);
    //Cant free either earlier as both point to same location
    cudaError_t chk = cudaFree(godata);
    if(chk!=0){
        printf("First chk also printed error. Maybe error in my logic\n");
    }

    printf("The error by threadsyn is %s", cudaGetErrorString(cudaGetLastError()));
    printf("The sum of the array is %d\n", output[0]);
    getchar();

    return 0;
}

Comment: Is it really necessary to post code which relies on an external file we don't have access to and which includs 10s of lines of redundant commented out code and 130+ column wide lines containing nothing but menaingless comments?
Comment: What happens as you step the input domain down in size? The pattern of errors might be helpful in diagnosis.
Comment: I think the reduction kernel itself, while unorthodox, is actually OK, as is the rather odd looking host loop calling the kernel (you only ever need to call any reduction like this *twice*, so why use a loop?). But there is at least a host side buffer overflow in `cudaMemcpy(output, gidata,size *  sizeof(int), cudaMemcpyDeviceToHost);` and possibly other bugs, but because no one can actually run this code, I am not sure how you expect anyone could actually answer this question...
Comment: I am surprised that it gives any answer at all! you are checking that `offset < blockDim.x` as it should be `ltid+offset < blockDim.x`. In the second while loop you are using a shared memory that is not yours. EDIT: and the dynamic `__shared__` size won't do any good because you are using `temp[ltid] = 0;` So only a shared memory with the size of the block is valid.
Answer: As said in advance by talonmies, the kernel itself is OK. Basically, it is the reduce0 kernel of the CUDA SDK improved with algorithm cascading in the sense of Brent's optimization used when improving the reduce5 kernel to reduce6 of the same SDK.
That the kernel works correctly can be shown by the following test code, which also compares the performance of reduce0 with that of the OP's kernel, named reduce0_stackoverflow in the code. The reduce0_stackoverflow kernel also reports, commented, the corresponding code lines of reduce0.
For the test case below, reduce0_stackoverflow executes in 0.030ms as compared to 0.049ms on a GeForce GT540M card.
Please, notice that the code below does not require that the array size must be a power of 2.
#include <thrust\device_vector.h>

#define BLOCKSIZE 256

/********************/
/* CUDA ERROR CHECK */
/********************/
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=true)
{
    if (code != cudaSuccess)
    {
        fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
        if (abort) { getchar(); exit(code); }
    }
}

/*******************************************************/
/* CALCULATING THE NEXT POWER OF 2 OF A CERTAIN NUMBER */
/*******************************************************/
unsigned int nextPow2(unsigned int x)
{
    --x;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    return ++x;
}

/*************************************/
/* CHECK IF A NUMBER IS A POWER OF 2 */
/*************************************/
bool isPow2(unsigned int x)
{
    return ((x&(x-1))==0);
}

/******************/
/* REDUCE0 KERNEL */
/******************/
/* This reduction interleaves which threads are active by using the modulo
    operator.  This operator is very expensive on GPUs, and the interleaved
    inactivity means that no whole warps are active, which is also very
    inefficient */
template <class T>
__global__ void reduce0(T *g_idata, T *g_odata, unsigned int N)
{
    extern __shared__ T sdata[];

    unsigned int tid    = threadIdx.x;                              // Local thread index
    unsigned int i      = blockIdx.x * blockDim.x + threadIdx.x;    // Global thread index

    // --- Loading data to shared memory
    sdata[tid] = (i < N) ? g_idata[i] : 0;

    // --- Before going further, we have to make sure that all the shared memory loads have been completed
    __syncthreads();

    // --- Reduction in shared memory
    for (unsigned int s=1; s < blockDim.x; s *= 2)
    {
        // --- Only the threads with index multiple of 2*s perform additions. Furthermore, modulo arithmetic is slow.
        if ((tid % (2*s)) == 0) { sdata[tid] += sdata[tid + s]; }
        // --- At the end of each iteration loop, we have to make sure that all memory operations have been completed
        __syncthreads();
    }

    // --- Write result for this block to global memory. At the end of the kernel, global memory will contain the results for the summations of
    //     individual blocks
    if (tid == 0) g_odata[blockIdx.x] = sdata[0];
}

/***************************/
/* REDUCE0 - STACKOVERFLOW */
/***************************/
template <class T>
__global__ void reduce0_stackoverflow(T *g_idata , T *g_odata, unsigned int N) {

    extern __shared__ T sdata[];

    unsigned int tid    = threadIdx.x;                              // Local thread index
    unsigned int i      = blockIdx.x * blockDim.x + threadIdx.x;    // Global thread index

    // --- Loading data to shared memory
    //sdata[tid] = (i < N) ? g_idata[i] : 0;                        // CUDA SDK
    sdata[tid] = 0;
    while(i < N){
        sdata[tid] += g_idata[i];
        i+=gridDim.x * blockDim.x; // to handle array of any size
    }

    // --- Before going further, we have to make sure that all the shared memory loads have been completed
    __syncthreads();

    // --- Reduction in shared memory
    //  for (unsigned int s=1; s < blockDim.x; s *= 2)                  // CUDA SDK
    //  {
    //     if ((tid % (2*s)) == 0) { sdata[tid] += sdata[tid + s]; }
    //     __syncthreads();
    //  }
    unsigned int s = 1;
    while(s < blockDim.x)
    {
        // --- Only the threads with index multiple of 2*s perform additions. Furthermore, modulo arithmetic is slow.
        if ((tid % (2*s)) == 0) { sdata[tid] += sdata[tid + s]; }

        // --- At the end of each iteration loop, we have to make sure that all memory operations have been completed
        __syncthreads();

        s*=2;
    }

    // --- Write result for this block to global memory. At the end of the kernel, global memory will contain the results for the summations of
    //     individual blocks
    if (tid == 0) g_odata[blockIdx.x] = sdata[0];

}

/********/
/* MAIN */
/********/
int main()
{
    const int N = 15336;

    thrust::device_vector<int> d_vec(N,3);

    int NumThreads  = (N < BLOCKSIZE) ? nextPow2(N) : BLOCKSIZE;
    int NumBlocks   = (N + NumThreads - 1) / NumThreads;

    // when there is only one warp per block, we need to allocate two warps
    // worth of shared memory so that we don't index shared memory out of bounds
    int smemSize = (NumThreads <= 32) ? 2 * NumThreads * sizeof(int) : NumThreads * sizeof(int);

    // --- Creating events for timing
    float time;
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);

    thrust::device_vector<int> d_vec_block(NumBlocks);

    /***********/
    /* REDUCE0 */
    /***********/
    cudaEventRecord(start, 0);
    reduce0<<<NumBlocks, NumThreads, smemSize>>>(thrust::raw_pointer_cast(d_vec.data()), thrust::raw_pointer_cast(d_vec_block.data()), N);
    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("reduce0 - Elapsed time:  %3.3f ms \n", time);

    // --- The last part of the reduction, which would be expensive to perform on the device, is executed on the host
    thrust::host_vector<int> h_vec_block(d_vec_block);
    int sum_reduce0 = 0;
    for (int i=0; i<NumBlocks; i++) sum_reduce0 = sum_reduce0 + h_vec_block[i];
    printf("Result for reduce0 = %i\n",sum_reduce0);

    /**********************************/
    /* REDUCE0 KERNEL - STACKOVERFLOW */
    /**********************************/
    cudaEventRecord(start, 0);
    reduce0_stackoverflow<<<NumBlocks/2, NumThreads, smemSize>>>(thrust::raw_pointer_cast(d_vec.data()), thrust::raw_pointer_cast(d_vec_block.data()), N);
    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("reduce0 - stackoverflow - Elapsed time:  %3.3f ms \n", time);

    // --- The last part of the reduction, which would be expensive to perform on the device, is executed on the host
    h_vec_block = d_vec_block;
    int sum_reduce0_stackoverflow = 0;
    for (int i=0; i<NumBlocks; i++) sum_reduce0_stackoverflow = sum_reduce0_stackoverflow + h_vec_block[i];
    printf("Result for reduce0_stackoverflow = %i\n",sum_reduce0_stackoverflow);

    getchar();
}


CLLocationManager Repeating Few Times

Question: Having a bit of an issue. I have a GMSMapView in my application and it points to the users location upon loading. When the app loads I have the locationManager set to display the latitude in the log once it finds the users position. Right now it displays the latitude over 3 times (I plan to make this post to my server). When I launch my application I will have quite a few users and the extra 3 server requests per user would be a lot for a server to handle. I am wondering is there anything I have done wrong in the code or is there a way to get around this? Will attach the code below.
Thanks!
<code>- (void)viewDidLoad
{

    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    [self.locationManager setDelegate:(id)self];
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager startMonitoringSignificantLocationChanges];
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [self.locationManager stopUpdatingLocation];

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:newLocation.coordinate.latitude
                                                            longitude:newLocation.coordinate.longitude
                                                                 zoom:17.0];
    [self.mapView animateToCameraPosition:camera];
    latitude = newLocation.coordinate.latitude;
    longitude = newLocation.coordinate.longitude;
    NSLog(@"latitude = %g", latitude);

}
</code>
Answer: didUpdateToLocation was deprecated way back in iOS6. Use the replacement didUpdateLocations, and then just pick off the last element of the array e.g.:
<code>- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    location = [locations lastObject];
    // ...
    latitude = location.coordinate.latitude;
    longitude = location.coordinate.longitude;
</code>

CLLocationManager Repeating Few Times


How to simplify the use of too many IF statements when finding specific cases

Question: I have code which a user will select different perameters from 5 dropdown menus, these can be: "None", 'Name', 'Manager', 'AccessLevel', 'Inhabitant' and 'Location' these will be matched with jtextfields that are searched to get the inputed value. However to get these values i am basically do alot of if statements to determine the combination of values e.g. Name, Manager and Location together will give the SQL statement:
<code>query = "SELECT * FROM propertyInfo WHERE propertyName = ? AND propertyManager = ? AND propertyLocation = ?"; </code>
this leads to a convoluted mess of if statements, is there any way to simplify it?
it works however to actually create it i would have to do hundreds of lines for different combinations and it will be hard to expand later. however this is some of my current code:
<code>`if (searchingForName == true) {
          if (searchingForManager == true) {
              if (searchingForAccessLevel == true) { // final lvl 1
                   query = "SELECT * FROM propertyInfo WHERE propertyName = ? AND propertyManager = ? AND accessLevelRequired = ?";
                   query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyName = ? AND propertyManager = ? AND accessLevelRequired = ?";
              }else if ((searchType1.equals("Inhabitant") || searchType2.equals("Inhabitant") || searchType3.equals("Inhabitant"))) { // final lvl 2
                query = "SELECT * FROM propertyInfo WHERE propertyName = ? AND propertyManager = ? AND propertyInhabitant = ?";
                query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyName = ? AND propertyManager = ? AND propertyInhabitant = ?";
            }else if ((searchType1.equals("Location") || searchType2.equals("Location") || searchType3.equals("Location"))) { // finaly lvl 3
                query = "SELECT * FROM propertyInfo WHERE propertyName = ? AND propertyManager = ? AND propertyLocation = ?";
                query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyName = ? AND propertyManager = ? AND propertyLocation = ?";
            }
          }  else if ((searchType1.equals("AccessLevel") || searchType2.equals("AccessLevel") || searchType3.equals("AccessLevel"))) { // sub lvl 2
               if ((searchType1.equals("Inhabitant") || searchType2.equals("Inhabitant") || searchType3.equals("Inhabitant"))) { //final lvl 1
                query = "SELECT * FROM propertyInfo WHERE propertyName = ? AND accessLevelRequired = ? AND propertyInhabitant = ?";
                query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyName = ? AND accessLevelRequired = ? AND propertyInhabitant = ?";
            }else if ((searchType1.equals("Location") || searchType2.equals("Location") || searchType3.equals("Location"))) { // final lvl 2
                query = "SELECT * FROM propertyInfo WHERE propertyName = ? AND accessLevelRequired = ? AND propertyLocation = ?";
                query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyName = ? AND accessLevelRequired = ? AND propertyLocation = ?";
            }
          } else if ((searchType1.equals("Inhabitant") || searchType2.equals("Inhabitant") || searchType3.equals("Inhabitant"))) { // sub lvl 3
               if ((searchType1.equals("Location") || searchType2.equals("Location") || searchType3.equals("Location"))) { // final lvl 1
                query = "SELECT * FROM propertyInfo WHERE propertyName = ? AND propertyInhabitant = ? AND propertyLocation = ?";
                query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyName = ? AND propertyInhabitant = ? AND propertyLocation = ?";
          }

      //}
      }else if ((searchType1.equals("Manager") || searchType2.equals("Manager") || searchType3.equals("Manager"))) { // main lvl 2

          if ((searchType1.equals("AccessLevel") || searchType2.equals("AccessLevel") || searchType3.equals("AccessLevel"))) { // sub lvl 1

            if ((searchType1.equals("Inhabitant") || searchType2.equals("Inhabitant") || searchType3.equals("Inhabitant"))) {// final lvl 1
                   query = "SELECT * FROM propertyInfo WHERE propertyManager = ? AND accessLevelRequired = ? AND propertyInhabitant = ?";
                   query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE   propertyManager = ? AND accessLevelRequired = ? AND propertyInhabitant = ?";

            }else if ((searchType1.equals("Location") || searchType2.equals("Location") || searchType3.equals("Location"))) { // final lvl 2
                query = "SELECT * FROM propertyInfo WHERE propertyManager = ? AND accessLevelRequired = ? AND propertyLocation = ?";
                query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyManager = ? AND accessLevelRequired = ? AND propertyLocation = ?";
            }
          }  else if ((searchType1.equals("Inhabitant") || searchType2.equals("Inhabitant") || searchType3.equals("Inhabitant"))) { // sub lvl 2
                if ((searchType1.equals("Location") || searchType2.equals("Location") || searchType3.equals("Location"))) { // final lvl 1
                query = "SELECT * FROM propertyInfo WHERE propertyManager = ? AND propertyInhabitant = ? AND propertyLocation = ?";
                query2 = "SELECT COUNT(*) AS recordCount FROM propertyInfo WHERE  propertyManager = ? AND propertyInhabitant = ? AND propertyLocation = ?";
            }
          }
        `  }
      }
</code>
Comment: Have you tried building the prepared statement dynamically based on the conditions you have?
Comment: https://xyproblem.info/ Provide the problem itself.
Comment: you could try reversing if elses as in https://softwareengineering.stackexchange.com/questions/47789/how-would-you-refactor-nested-if-statements
Comment: Unrelated, but never do `if (foo == true) {` and instead always do `if (foo) {`. It's just cleaner and less risky.
Answer: You can simplify this process by dynamically constructing the SQL query based on the selected parameters. Here's a more structured approach:
<code>// Define the base query
String query = "SELECT * FROM propertyInfo WHERE 1 = 1";

// Initialize a list to store query parameters
List<Object> parameters = new ArrayList<>();

// Check if Name is selected
if (searchingForName) {
    query += " AND propertyName = ?";
    parameters.add(nameValue);
}

// Check if Manager is selected
if (searchingForManager) {
    query += " AND propertyManager = ?";
    parameters.add(managerValue);
}

// Check if AccessLevel is selected
if (searchingForAccessLevel) {
    query += " AND accessLevelRequired = ?";
    parameters.add(accessLevelValue);
}

// Check if Inhabitant is selected
if (searchingForInhabitant) {
    query += " AND propertyInhabitant = ?";
    parameters.add(inhabitantValue);
}

// Check if Location is selected
if (searchingForLocation) {
    query += " AND propertyLocation = ?";
    parameters.add(locationValue);
}

</code>
For each selected parameter (e.g., Name, Manager, etc.), you dynamically add a corresponding condition to the query string and add the parameter value to the parameters list. Finally, you can execute the query using a prepared statement with the parameters.
Have a good one!
Comment: @ThomasHumphreys, here is the _Java_ tutorial on the _Collections Framework_, which includes the _ArrayList_ class.  _[Trail: Collections (The Java™ Tutorials)](https://docs.oracle.com/javase/tutorial/collections/index.html)_
Comment: That code looks really good, and is what im looking for, but the issue is that i dont know how arraylists work and how to take the output from this into the actual code, can you please link an article so i can learn about arraylists?
Comment: @ThomasHumphreys  It's not a tutorial, but Oracle has the APIs for Classes and Interfaces online.  Check out the [ArrayList API](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html) . If you want to find tutorials, you can [Google for them](https://www.google.com/search?q=java+arraylist+tutorial&oq=java+arraylist+tutorial)


Help clicking a button in Greasemonkey

Question: 1st- I'm not a programmer, so assume I know nothing about JavaScript.  In fact, I just figured out that Greasemonkey is JavaScript.
2nd - But I have been searching and reading for several days trying to do it myself.  I'm not lazy, it's just that I'm in way over my head.
http://userscripts.org/scripts/review/57265
The program automatically clicks a radio button and adds a new button.  When you click the new button it automatically fills text in the box.  I'm trying to simply modify this Greasemonkey Script to automaticaly click the new button.
But I've learned this isn't so simple.  Apparently I need an XPath for this?  That's about all I've figured out so far. I really don't want to learn all of JavaScript just to do this one thing.
I've tried inserting this in at the end:
function click(elm) {
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, window, 0, 1, 1, 1, 1, false, false, false, false, 0, null);
elm.dispatchEvent(evt);
It didn't work.  Maybe I'm missing something?
I also tried this from another program:
  var rep = document.getElementById("report");
  if( (rep != null) ) ) {
  var repk = rep.childNodes;
  for( var repidx=0; repidx<repk.length; repidx++ ) {
      var rep2 = repkrepaidx];

}
But again I don't think I put it in right?
Comment: What exactly are you trying to accomplish? that is to say, what is the end goal of your user script?
Answer: assuming the "report" in your example is a form, you can just submit it.
form.submit
If the element used to submit the form is input type="submit" or input type="button", you can "click" it.
buttonElement.click();

Help clicking a button in Greasemonkey


How to package a single Python script with nix?

Question: I have a single Python script called myscript.py and would like to package it up as a nix derivation with mkDerivation.
The only requirement is that my Python script has a run-time dependency, say, for the consul Python library (which itself depends on the requests and six Python libraries).
For example for myscript.py:
#!/usr/bin/env python3

import consul
print('hi')

How to do that?
I can't figure out how to pass mkDerivation a single script (its src seems to always want a directory, or fetchgit or similar), and also can't figure out how to make the dependency libraries available at runtime.
Answer: When you have a single Python file as your script, you don't need src in your mkDerivation and you also don't need to unpack any source code.
The default mkDerivation will try to unpack your source code; to prevent that, simply set dontUnpack = true.
myscript-package = pkgs.stdenv.mkDerivation {
  name = "myscript";
  propagatedBuildInputs = [
    (pkgs.python3.withPackages (pythonPackages: with pythonPackages; [
      consul
      six
      requests2
    ]))
  ];
  dontUnpack = true;
  installPhase = "install -Dm755 ${./myscript.py} $out/bin/myscript";
};

If your script is executable (which we ensure with install -m above) Nix will automatically replace your #!/usr/bin/env python3 line with one which invokes the right specific python interpreter (the one for python36 in the example above), and which does so in an environment that has the Python packages you've specifified in propagatedBuildInputs available.
If you use NixOS, you can then also put your package into environment.systemPackages, and myscript will be available in shells on that NixOS.
Answer: This helper function is really nice:
pkgs.writers.writePython3Bin "github-owner-repos" { libraries = [ pkgs.python3Packages.PyGithub ]; } ''
 import os
 import sys
 from github import Github

 if __name__ == '__main__':
     gh = Github(os.environ['GITHUB_TOKEN'])

     for repo in gh.get_user(login=sys.argv[1]).get_repos():
         print(repo.ssh_url)
''

https://github.com/nixos/nixpkgs/blob/master/pkgs/build-support/writers/default.nix#L319
Comment: This is wonderful! Should be more widely documented IMHO


Install/distribute a Specific Version of CPython Interpreter and Dependent Modules Along With My Script to Customers

Question: I have a fairly complex Python application that I want to install on customers' computers. I am thinking to install a private copy of the python interpreter and the libraries along with my scripts. Is there any way to do this?
Note that I am not looking for pyexe/pyinstaller kind of solution. Such a solution creates a giant executable containing the interpreter, the libraries, and my scripts. When it runs it dynamically retrieves everything and starts the script. I cannot use such solution because my script runs my other scripts by spawning subprocesses. There are so many subprocesses I spawn that it will be prohibitively slow if I freeze the subprocesses into an exe file, as it usually takes a long to start due to the unfreezing every time a subprocess is spawned.
What I am looking for is a way to install my python scripts along with a private copy of the interpreter and libraries. I am hoping that I can create an installer to do the job. The installer will just install all the necessary files to a directory and ideally will create an icon on the desktop.
It is clearly possible. I was looking at the WingIDE. It is very possible that it was built in python but distributes a frozen version of python with it.
BTW: I am using windows.
Answer: Check out PortablePython  .  It's self contained and has no registry dependencies. You will probably need to set up a sitecustomize.py that points at your application and possible also block a system level PythonPath variable to avoid running code from another install
Comment: That's certainly one way. I have checked out PortablePython. One problem appears that it might be a bit tricky to install new libraries not included with it. Some blogs suggest that easy_install will be fine, but it is not clear that modules that cannot be installed with easy_install will be fine. But it's not clear modules that cannot be handled by easy_install will be fine.
Comment: I've had pretty good luck with easy_install, and where that did not work manual installation to the site_packages in my PortablePython directory.  In my application this is distributed to users who are all synced to a the same perforce directory so I only maintain the one copy and everybody gets that (no installer, but of course you have to be on our perforce.) I haven't seen any significant differences from standard windows python - i've distributed QT and the perforce api, which both include compiled PYDs, this way.


Dúvida MySQLi Paramento new_link

Question: A antiga função de PHP mysql_connect possuía o parametro new_link que permitia conexão com vários bancos diferentes no mesmo script:
Exemplo:
$connect = mysql_connect($host,$user,$pass,$new_link);

Como funciona isso em mysqli? Ele tem esse parâmetro? Ou não precisa?
$mysqli = new mysqli($host, $user, $pass, $database);

Pesquisei na documentação mas não localizei.
Answer: Cada instância mysqli é completamente independentes uma da outra e, portanto, cada conexão db de uma instância é um new_link. Portanto, não existe nada equivalente ao new_link no mysqli.
Answer: O quarto argumento da função mysql_connect() serve para obrigar o php a criar uma nova conexão, o comportamento padrão é uma chamado mysql_connect() ele retorna a conexão, no caso de uma segunda com as mesmas informações(servidor, usuário senha) ele retorna a mesma conexão, na extensão do mysqli não exite esse parametro.

Dúvida MySQLi Paramento new_link


How to use multiprocessing for a big 3d image stack? python

Question: I have a 3d image stack(4000×2048×2048),I want to do some operation in every sigle 2d array(2048×2048),eg. Gaussian filtering, image enhancement,resize img ...
import numpy as np
from tifffile import imread,imwrite
import multiprocessing as mp
import cv2

def gaussian_blur_2d(img):
    blur = cv2.GaussianBlur(img,(5,5),0)
    return blur

file_path = "F:\\Ctest\\123.tif"
img = imread(file_path)
for i in range(0,img.shape[0]):
    img[i,:,:] = gaussian_blur_2d(img[i,:,:])

How can I accelerate the for loop by using multiprocessing?
My idea is two split the raw image stack into four or eight parts,and using pool.map to the split stack.But how can I using the split processing result to get a final full stack.I don not want to write the split stacks. This will increase extra IO time. When the split stacks too big, it would cause return error in pool.map in my experience.
On the other hand, I've tried just sticking the multidimensional array into mp.Array which gives me TypeError: only size-1 arrays can be converted to Python scalars.
Comment: does that actually all fit in memory? (~16 gigs with 8-bit greyscale) If so, I would construct numpy arrays in each process from a `multiprocessing.shared_memory`  object.. Your big problem is almost definitely going to be efficiently getting the data to and from child processes.
Answer: As I mentioned in the comments, getting all that data to be accessible between several worker processes is the biggest challenge here, because one of the key tenants of using multiprocessing is that generally no memory is shared between processes. Therefore we must explicitly tell the operating system that we want access to a chunk of memory that "is" shared between the processes, and create our numpy array with that chunk of memory. Beyond that it's just a little multiprocessing housekeeping which is pretty standard and well explored in other tutorials and examples.
import numpy as np
from multiprocessing import Process, shared_memory, Queue, cpu_count
from queue import Empty
import cv2

class STOPFLAG: pass #a simple flag to tell the worker to stop

def worker_process(in_q, shm_name):
    shm = shared_memory.SharedMemory(name=shm_name) #create from the existing one made by the parent process
    img_stack = np.ndarray([4000, 2048, 2048], dtype="uint8", buffer=shm.buf) #attach a numpy array to the memory object
    while True: #until the worker runs out of work
        try:
            task = in_q.get(1) #don't wait forever on anything if you can help it.
        except Empty: #multiprocessing.Queue uses an exception template from the queue library
            print("assuming all tasks are done. worker exiting...") #assume waiting for a while means no more tasks (we shouldn't hit this, but it could prevent problems in the child if a crash happens elsewhere)
            break
        if isinstance(task, STOPFLAG):
            print("got stop flag. worker exiting...")
            break

        #process the image slice (no mutexes are needed because no two workers will ever get the same index to work on at the same time)
        img_stack[task] = cv2.GaussianBlur(img_stack[task],(5,5),0)

    shm.close() #cleanup after yourself (close the local copy. This does not close the copy in the other processes)

if __name__ == "__main__": #this is needed with multiprocessing

    #create shared memory space where numpy will work from
    shm = shared_memory.SharedMemory(create=True, size=4000*2048*2048) #OS may have a hard time allocating this memory block because it's so big...
    #create the numpy array from the allocated memory
    img_stack = np.ndarray([4000, 2048, 2048], dtype="uint8", buffer=shm.buf)

    #Here is where you would load the image data onto the img_stack array. It will start out with whatever random data was previously in ram similar to numpy.empty.

    #create a queue to send workers tasks (image index to work on)
    in_q = Queue()

    #create a couple worker processes
    processes = [Process(target=worker_process, args = (in_q, shm.name)) for _ in range(cpu_count())]
    for p in processes:
        p.start()

    #fill up the task queue with image indices that need computation
    for i in range(4000):
        in_q.put(i)

    #send a stop signal for each worker
    for _ in processes:
        in_q.put(STOPFLAG())

    #wait for all children to finish
    for p in processes:
        p.join()

    #do something (save?) with the img_stack
    np.save("processed_images.npy", img_stack)

    shm.close() #cleanup
    shm.unlink() #unlink is called only once after the last instance has been "close()"d

Comment: Your answer shocked me. It's amazing! I learned a lot as a rookie,and I heartily appreciate your great kindness to me.


How to write unit tests for Angular Flex-layout directives (fxHide, fxShow)?

Question: I think that the Angular Flex-Layout library is great, but I couldn't figure out how to test its directives like fxHide or fxShow
For example, if you have a template like that:

Should not be visible for small devices (xs, sm)

How should you mock the screen size values to test it?
Answer: So I've found the answer inside the @angular/flex-layout internal unit tests here.
To mock the values you have to inject a mocked version of MatchMedia like this:
import {
  FlexLayoutModule,
  ɵMatchMedia as MatchMedia,
  ɵMockMatchMedia as MockMatchMedia,
} from '@angular/flex-layout';

describe('template tests', () => {
  let mediaController: MockMatchMedia;

  let fixture: ComponentFixture<MyComponent>;
  let component: MyComponent;
  let el: DebugElement;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [FlexLayoutModule],
        providers: [{ provide: MatchMedia, useClass: MockMatchMedia }],
        declarations: [MyComponent],
      })
        .compileComponents()
        .then(() => {
          fixture = TestBed.createComponent(MyComponent);

          inject([MatchMedia], (_matchMedia: MockMatchMedia) => {
            mediaController = _matchMedia;
          })();

          component = fixture.componentInstance;
          el = fixture.debugElement;
        });
    }),
  );

  afterEach(() => {
    mediaController.clearAll();
  });

  it('should not display day of week for mobile', () => {
    mediaController.activate('lt-md');
    fixture.detectChanges();
    const divDbEl = el.query(By.css('.my-div'));
    expect(divDbEl).toBeTruthy();
    expect(divDbEl.styles.display).toEqual('none'); // Should be hidden
  });
});

So, you need:

Import mocks from @angular/flex-layout/core: import { ɵMatchMedia as MatchMedia, ɵMockMatchMedia as MockMatchMedia } from '@angular/flex-layout/core';
Declare let mediaController: MockMatchMedia;
Inside beforeEach configure the testing module:

imports: [FlexLayoutModule],
providers: [{ provide: MatchMedia, useClass: MockMatchMedia }]

After you compile the component, inject the mocked version of MatchMedia:

inject([MatchMedia], (_matchMedia: MockMatchMedia) => {
        mediaController = _matchMedia;
})();

Inside afterEach you can reset some values:

    afterEach(() => {
        mediaController.clearAll();
    });

Activate the screen size you need: mediaController.activate('lt-md');
Test the display style is set to 'none': expect(divDbEl.styles['display']).toEqual('none');


All solutions of $a+b+c=abc$ in natural numbers

Question: I was observing some nice examples of equalities containing the numbers $1,2,3$ like $\tan^{-1}1+\tan^{-1}2+\tan^{-1}3=\pi$ and $\log 1+\log 2+ \log 3=\log (1+2+3)$. I found out this only happens because $1+2+3=1*2*3=6$. I wanted to find other examples in small numbers, but I failed. How can we find all of the solutions of $a+b+c=abc$ in natural numbers?The question seemed easy, but it seems difficult to find. I would prefer an elementary way to find them! What I did: We know if $a+b+c=abc$, $a|a+b+c$ so $a|b+c$. Similarly, $b|a+c$ and $c|a+b$. Other than that, if we multiply both sides by $b$, we get $b^2+1=(bc-1)(ab-1)$. If we also divide both sides by $abc$, we get $\frac{1}{bc}+\frac{1}{ac}+\frac{1}{ab}=1$. I don't know how to go further using any of these, but I think they are a good start. I would appreciate any help.
Comment: Umm, $\log 1=0$ so $\log 1 +\log 2+\log 3\neq \log 1 \log 2\log 3$.
Comment: Your division, and size considerations, do the job. One of the terms must be $\frac{1}{2}$, meaning that one variable is $1$ and another is $2$. The end.
Comment: Your equality with logs is not correct. RHS is 0 and LHS is $\log(2) + \log(3)$.
Comment: I think that the post I linked has the best answers (thus my vote). But it seems the mod has spoken.
Comment: You can show that if $\frac{1}{x}+\frac1{y}+\frac 1{z}=1$ with $x,y,z$ natural, then either $x,y,z=3,3,3$ or $x,y,z=2,3,6$.Then which $a,b,c$ can we choose to get either of these solutions?
Comment: http://math.stackexchange.com/questions/202679/sum-of-digits-and-product-of-digits-is-equal-3-digit-number/202693#202693
Comment: Perhaps you meant $\log(1 + 2 + 3) = \log(1) + \log(2) + \log(3)$ ?
Comment: I'm sorry. i corrected the equality with logs. Huge type mistake!
Comment: also related with $n=1$: https://math.stackexchange.com/questions/2378804/numbers-of-the-form-fracxyzxyz-second-question
Comment: Does this answer your question? [Find all integral solutions to $a+b+c=abc$.](https://math.stackexchange.com/questions/1176875/find-all-integral-solutions-to-abc-abc)
Comment: @ArcticChar I think you meant the other way round as your linked post was in 2015.
Answer: Without loss of generality $a \leq b \leq c$. Then $a+b+c \leq 3c$ and hence
$$abc=a+b+c \leq 3c$$
Thus, either $c =0$, in which case $a=b=c=0$, or
$$ab \leq 3 \,.$$
This leads to only four possibilities to check: $a=0$ or $(a,b)=(1,1)$ or $(a,b)=(1,2)$ or $(a,b)=(1,3)$.
Answer: If $a=0$ then you require $b+c=0$ and hence $b=c=0$.
Note that you can assume $a\leq b \leq c$. If $a, b, c \geq 2$ then $abc \geq 4c > c + b + a$. Hence at least one of $a,b,c$ is equal to $1$.
Wlog assume $a=1$, and look for solutions to $b+c+1 = bc$. If $b,c\geq 3$ then $bc \geq 3c > b + c + 1$, hence at least one of $b,c$ is less than $3$
Wlog assume $b=2$, and look for solutions to $c+3 = 2c$, which implies $c=3$.
So the only solutions are $(0,0,0)$ and $(1,2,3)$ and their permutations.
Comment: From $b+c+1 = bc$, $(b-1)(c-1) = 2$.
Answer: Here's a start of a full solution: The right side grows way faster than the left side, so it's unlikely that there are very many solutions. More formally, suppose that $a, b, c \ge 2$, and that $c$ is at least as large as $a, b$. Then we have
$$abc \ge 4c > c + c + c \ge c + b + a$$
so it's necessary that one of the numbers (which we'll call $a$) is $1$. So we can reduce the problem to studying
$$b + c = bc - 1$$
which has fewer variables.
Comment: Thanks. I knew the solutions would contain inequalities, but couldn't find any except too general ones.
Answer: leaving aside the solution in which $a=b=c=0$ order the numbers so $a \le b \le c$
as OP shows, $c|(a+b)$ so we have:
$$
\frac{a+b}{c} \le 2
$$
thus only the values $1$ and $2$ are possible for $\frac{a+b}c$. these give $a+b=c$ and $a+b=2c$ respectively. however the latter is only possible if all three numbers are equal, as $c$ cannot be the arithmetic mean of two smaller numbers.
if all three numbers are equal they must each be $\sqrt{3}$, not a natural number solution.
plugging $a+b=c$ back into the equation $a+b+c=abc$ gives $ab=2$ hence $a=1, b=2, c=3$


CGRectContainsPoint with object in UIScrollView

Question: With this code I am trying to detect when a UIbutton moved by the user with his finger is released over another UIButton (or UIImageView):
CGPoint dropPoint = [gesture locationInView:gesture.view.superview];

if (CGRectContainsPoint(btn.frame, dropPoint)) {

....

The btn is the UIButton being dragged, while the dropPoint is the location in the view where the user takes away his finger. This method works perfectly if the bnt in in the self.view, but if the btn is in a UIScrollView it doesn't work. How can I make it work even in a UIScrollView?
Answer: The dropPoint needs to be in the coordinate system of btn. Assuming btn is a direct subview of gesture.view.superview:
CGPoint dropPoint = [gesture locationInView:gesture.view.superview];

CGPoint dropPointInBtn = [gesture.view.superview convertPoint:dropPoint toView:btn];

if (CGRectContainsPoint(btn.frame, dropPointInBtn)) {

....

Comment: thanks for your answer. btn is in a UIScrollView on the main view. This code doesn't work...
Comment: But by doing CGPoint dropPointInBtn = [gesture.view.superview convertPoint:dropPoint toView:my scroll view]; works, but not when I slide the scroll view left or right...
Comment: @Alessandro - when the `UIScrollView` is scrolled, use the scroll view's `contentOffset` property to adjust the drop point.


Como o Oracle age após a execução de um script PHP sem commit?

Question: Se eu executar uma série de comandos SQL com banco de dados Oracle, biblioteca OCI, sem executar o commit e definindo que não irá ser feito commit automático.
O que o Oracle fará ao final da execução do script PHP? Um rollback ou um commit?
Comment: Por que não testa você mesmo?
Comment: Isso depende da configuração do banco.
Comment: @rray essa pergunta é meio ampla, né?
Comment: Em parte essa pergunta responde => [O que é ACID em banco de dados?](https://pt.stackoverflow.com/q/203857/91) que seria o conceito de atomicidade.
Comment: Pessoal, melhorei a pergunta e tentei deixar mais claro.
Answer: PHP não faz nada porque é uma linguagem de programação, a questão é se a biblioteca faz, mas qual está usando? A padrão, na configuração padrão do DB? Não faz automático. Tem que chamar o oci_commit(). Usando OCI_COMMIT_ON_SUCCESS ele será executado no fim da execução da query se estiver tudo ok.
Comment: Então, estou usando a OCI mesmo mas sem commit automático. Gostaria de saber como o Oracle irá agir nesse caso.


relative transformation of coordinates on a flat surface

Question: I have a few coordinates that form a triangle. I have a relative point to that triangle. if the coordinates get translated to a new triangle I want to calculate the new relative point. How do I do this generally not only for 2 dimensions but for larger ones too?
# triangle translation
(5, 2) -> (2, -3)
(2, -3) -> (-3, 6)
(-3, 6) -> (6, 5)
# relative point
(5, -7) -> (x, y)
how do I solve for x, y?

EDIT: as I've done more research into basic geometric transformations I can see that I'm asking for a generalization of all possible transformations of the space. This is not merely a rotation, or a dilation, etc. This particular example rotates the space then stretches it in various ways. So what is the generalized solution for calculating spatial transformations? What are the steps to solve for X?
EDIT AGAIN: thinking about this intuitively I think there might be two answers to the question: one where the 2d space is not rotated and one where it is.

I think the first, straightforward solution is the one I'm looking for. But I don't know how to compute it. But if the case can be made that the second rotational solution is more generalized maybe I'd rather use that, idk. I think I'd be happy with either solution.
Can you help me?
Additional Edit:
Here is the starter code I have produced from John Hughes linear transformation calculation below.

def extrapolate(domain_coordinates, result_coordinates, point):
    '''
    given a set of input coordinates and their resulting
    coordinates post-transformation, and given an additional
    input coordinate return the location (coordinate) in the
    post-transformation space that corresponds to the most
    logical linear transformation of that space for that
    additional point. "extrapolate where this point ends up"
    '''
    import numpy as np

    # Add the number 1 to the coordinates for each point
    domain = [(x, y, 1) for x, y in domain_coordinates]

    # Do the same for the "target" coordinates too
    result = [(x, y, 1) for x, y in result_coordinates]

    # Put these coordinates, arranged vertically, into a 3×3 matrix
    domain = np.array(domain).T
    result = np.array(result).T

    # D^−1 is the "matrix inverse"
    inverse = np.linalg.inv(domain)

    # Let M=RD^−1
    matrix = result * inverse         # why do I need M?...

    # Do the same for the extrapolation point
    xpoint = [(x, y, 1) for x, y in [point]]
    xpoint = np.array(xpoint).T

    # extrapolate ???
    extrapolated_point = matrix * xpoint    # this isn't right...

    return extrapolated_point

extrapolate(
    domain_coordinates=[(5, 2), (2, -3), (-3, 6)],
    result_coordinates=[(2, -3), (-3, 6), (6, 5)],
    point=(5, -7))

This code is not working right, for instance, if I insert this test just before the return...
    print(domain * np.array([[1],[0],[0]]).T)
    print(domain * np.array([[1],[0],[0]]).T * matrix)

it prints...
[[5 0 0]
 [2 0 0]
 [1 0 0]]
[[ 1.73076923  0. -0.]
 [-0.57692308 -0.  0.]
 [-0.34615385  0.  0.]]

whereas I would expect it to print...
[[5 0 0]
 [2 0 0]
 [1 0 0]]
[[ 2  0.  0.]
 [-3  0.  0.]
 [-1  0.  0.]]

as per this statement:

Then multiplication by the matrix R will take A to A′

Can you show me where I've gone wrong?
Answer: Assuming that you're referring to linear transformations (informally: those that take straight lines to straight lines), and that you only want to consider those that are invertible (i.e., that don't send everything to a point, or to a single line), here's your answer. It also works for $n+1$ points in $n$-space (here you have three points -- A, B, C -- in 2-space).
Step 1: add the number 1 to the coordinates for each point, so you have
coordinate rewrite:
(5, 2) -> (5, 2, 1)
(2, -3) -> (2, -3, 1)
(-3, 6) -> (-3, 6, 1)

Do the same for the "target" coordinates too.
Put these coordinates, arranged vertically, into a $3 \times 3$ matrix:
coordinate rewrite:
(5  2  -3)
(2 -3   6)
(1  1   1)

And call that matrix $D$ (for "domain"). If you multiply D by the three standard coordinate vectors, the results will be your three (rewritten) original points; for example,
$$
\pmatrix{
5 & 2 & -3 \\
2 & -3 & 6 \\
1 & 1 & 1
}
\pmatrix{0\\1\\0} =
\pmatrix{2 \\-3\\1}.
$$
By the way, the three standard coordinate vectors are usually called $e_1, e_2, e_3$, where $e_i$ has a "1" in position $i$, and zeroes elsewhere. This generalizes nicely to higher dimensions.
So now we have $De_1 = A, De_2 = B, De_3 = C$, where $A,B,C$ denote your original points, but with the extra "1" at the bottom.
Do the same thing for the "target" points to get a matrix $R$ (for "result"):
$$
R = \pmatrix{
2 & -3& 6 \\
-3 & 6 & 5 \\
1 & 1 & 1}
$$
By the same argument, we have $Re_1 = A', Re_2 = B', Re_3 = C'$, where $A'$ denotes the "new" location for $A$, again with a $1$ appended, i.e.,
$$
A' = \pmatrix{2\\-3\\1}.
$$
Now comes the fun part: Let
$$
M = RD^{-1}.
$$
Then multiplication by the matrix $R$ will take $A$ to $A',$ and $B$ to $B'$, and $C$ to $C'$. You can also multiply $X$ (your "extra point", but with a "1" appended) by $R$ to get $X'$ (the new location of the "extra point", from which you'll want to delete the extra "1" at the bottom).
It's possible you'll find yourself asking "What does $D^{-1}$ mean?" and the answer is "it's the matrix inverse," and you can read all about it in any linear algebra book. If you're writing software, a great many matrix libraries have an "inverse" operation. Small warning: computing $D^{-1}$ is generally expensive. IF you're hoping to transform a bunch of "X" points, compute $RD^{-1}$ once, and then use it over and over, rather than recomputing each time.
Comment: I've fixed that type with the $(2, -3, 1)$. As for your second comment...there is exactly one "affine transformation of the plane" (i.e., transformation preserving lines, but not necessarily sending the origin to the origin) that takes A,B,C to A', B', C', and I've written it down for you. I've implemented that affine transformation as the restriction of a *linear* transformation of 3-space to the $z = 1$ plane, but that doesn't really matter. What matters is that if you want a (continuous) lines-to-lines map that sends those 3 points to the other 3, this is it.
Comment: If you show me the starting point for some python code (especially what things you're importing), I might be able to help out further.
Comment: in step 1 do you mean to say: (2, -3) -> (2, -3, 1)?
Comment: Also, does this answer perform a linear transformation according to the origin or according to the center of the triangle? probably the origin right? so if I want to do it from the center of the triangle I'll have to just make that my origin first? See my image #2. Furthermore, I'm not quite following this answer 100% though I can tell this is what I need. and, Yes I am doing this for some software written in python.
Comment: Well, the starting code I had in python took a completely different approach, I was attempting to get the ratios between all points in terms of distance along the X and Y axes, averaging those points to give me a small triangle which I would then get the center of and that would be my X location. so. I couldn't get that to work, so I need to translate the math speak you have here (which I don't speak) into code, I'll put what I have for this new approach so far in the question as an additional edit, but it won't be much at all. I appreciate any and all of your help!
Comment: I've added more code to my attempt. I'm failing to understand what you're saying here at the very end. M=RD−1. Why do I need to compute M? You say multiplication by the matrix R will take A to A' etc. in the example code I must be doing something wrong because I don't get those kinds of results, and therefore I can't extrapolate X correctly. Do you see where I'm going wrong?
Answer: You'll want to double-check all my arithmetic, but here's a valid strategy.
If $x$ is mapped to $Ax+b$ for square matrix $A$ and vector $b$, $A(\sum_iw_ix_i)+b=\sum_iw_i(Ax_i+b)$ provided $\sum_iw_i=1$. So we try to write$$\binom{5}{-7}=w_1\binom{5}{2}+w_2\binom{2}{-3}+(1-w_1-w_2)\binom{-3}{6}\iff\binom{8}{-13}=w_1\binom{8}{-4}+w_2\binom{5}{-9}.$$This gives simultaneous equations in $w_1,\,w_2$, with solution $w_1=\frac{7}{52},\,w_2=\frac{18}{13}.$Since $1-w_1-w_2=\frac{-27}{52}$. So $\binom{5}{-7}$ is mapped to$$\frac{7}{52}\binom{2}{-3}+\frac{18}{13}\binom{-3}{6}-\frac{27}{52}\binom{6}{5}=\frac{1}{13}\binom{-10}{69}.$$


Some questions from forall x

Question: I was doing practice exercises of chapter-3 of the textbook forall x: Calgary An Introduction to Formal Logic.
There are some questions confusing me (there answers are not given in the solution booklet):

B. For each of the following: Is it a necessary truth, a necessary falsehood, or contingent?

(3) If wood were a good building material, it would be useful for building things.
(5) If gerbils were mammals they would nurse their young.

D. Which of the following pairs of sentences are necessarily equivalent?

(2) Thelonious Monk played gigs with John Coltrane. John Coltrane played gigs with Thelonious Monk.

Now, for the questions, I think (5) is a necessary truth because of the meaning of 'mammals' (but not 100% sure).
But, I am not able to decide for (3), which feels too ambiguous (e.g., good building material for what? Can there be good building material for something which is not counted in our notion of 'things').
Also, the pair in (2) should be equivalent unless there can be a primary and a secondary role related to 'playing gigs', which I am not sure of.
So, what are the right answers to these questions? Please explain.
Comment: I agree with the above comment...  (2) is not "necessarily true" i.e. it is not provable on the base of logic alone. We have to rely on our empirical knowledge that "playing gigs with" is symmetric. Consider the similar "Thelonious Monk is older than John Coltrane." It is not equiv to "John Coltrane is older than Thelonious Monk.
Answer: pg.18

For the rest of this section, we'll take cases in the sense of
conceivable scenario, i.e., in the sense in which we used them to
define conceptual validity.... if we use a different idea of what counts
as a "case" we will get different notions. And as logicians we will,
eventually, consider a more permissive definition of case than we
do here.

pg. 21

An argument is valid if there is no case where the premises are all    true and the conclusion is not; it is invalid otherwise.
A necessary truth is a sentence that is true in every case.
A necessary falsehood is a sentence that is false in every case.
A contingent sentence is neither a necessary truth nor a necessary falsehood; a sentence that is true in some case and false in some other case.
Two sentences are necessarily equivalent if, in every case, they    are both true or both false.

From the above excerpts, it appears that the author means this: "necessary truth" means logical truth, "necessary falsehood" means logical falsehood, "necessary equivalence" means logical equivalence, and "valid argument" means an argument whose conclusion is a logical consequence of its premises.
As such, I'd say that

(3) $\;[P\rightarrow P]\;$ is a tautological, therefore necessary,
truth;
(5) $\;[P\rightarrow Q]\;$ is a (probably true) contingent sentence;
(2) $\;[G(x,y)\leftrightarrow G(y,x)]\;$ is a true contingent sentence. (Whether the predicate/relation $G$ is symmetric depends on interpretation.) So, the pair of sentences is not "necessarily equivalent".

Some questions from forall x


Does electric guitar's body shape really effect its sound?

Question: As I know electric guitar's sound is transferred to electric signal by Faraday's law, that a changing magnetic field produces electricity. So this is independent by shape of guitar then why so many people keep saying electric guitar's body shape is important for sound of guitar?
Edit1: Here it is shown :

Edit2: And here it is explained
Comment: This question is quite similar and already has many answers: https://music.stackexchange.com/questions/14019/how-much-does-an-electric-guitars-body-physics-affect-the-tone-playability-et
Comment: Oh Thank you a lot I did not see it. Then this question can be closed
Answer: It is true that the body shape won't have any effect on the way microphones are picking the sound.
However, the strings (which are vibrating) are attached to the body. Part of the string vibration will be transferred to the body and, obviously part of the vibration of the body will be transferred to the strings.
This way, the shape of the body can actually have an influence on the sound produced by the strings: if some frequencies are favored or not, depending, for instance, if the body will "resonate" well at these frequencies. The exact way it will influence the strings or vibrates is, I think, a very difficult question though. But it is clear that the strings are not attached to an "unmovable" frame like we like them to be attached in Physics…
Obviously, this is a secondary effect, but as the system body+strings is quite coupled, you can imagine the former has an effect on the behavior of the later.


Cron failed with drush: Segmentation fault

Question: In Drupal 6, whenever I run cron from web interface I get an Internal server error and when I run
drush cron

I just get
Segmentation fault

What can be wrong here and how can I fix it?
Answer: It sounds like a resource problem.  Memory limits tend to be the culprit.
Check to see that drush is using the same php.ini file your site is.
drush status

Tells you what php you are using for drush.
Running the following will give you memory output information when running cron
drush cron -d

if that memory stack is near what your php.ini limit is.. raise it up an integer of 32Mb. (i.e. 128mb to 160mb)  and then test again.
Comment: The first bit of advice is important.  I have seen system installs where the web and CLI versions of PHP have different ini files.
Comment: This happened to me not long ago, in preconfigured VM's I had to work with, when I am in devel mode, *especially* with theme_devel enabled. I simply pushed up memory setting in php as this answer states at the end.
Comment: Well, drush uses /etc/php5/cli/php.ini. I set memory_limit=512M and retried after issuing 'drush --yes vset cron_semaphore 0' (otherwise cron would not run). But now after issuing 'drush cron -d' I still get  a bunch of bootstraps which end up with: 'Initializing drush commandfile: user [0.29 sec, 42.79 MB]                                                  [bootstrap] Segmentation fault
Comment: I had the same problem with a 5.x version of drush.... downgrade to 4.6 and see if you are getting the same error..
Comment: @PhiloSurfer I'm using drush 4.5.
Comment: up to 4.6-dev and see if this resolves... there are some drush bugs floating around.
Answer: After starting cron from the web interface check your apache access and error logs for more information.
When starting cron with drush, make sure you have xdebug installed. It can record traces, memory usage and give you a stack trace in case php crashes.
Comment: Well, I am using nginx+php-fpm, not apache. Can I still install xdebug? How?
Answer: According to Metaltoad, Views (among other modules that execute regexs with preg_match()) can create runaway regex's that eat up memory and cause segfaults because preg_match() can't prevent backtracking overflows.


Syntax error or access violation: 1067 while installing module

Question: I am getting error while installing custom module. please let me know where am i doing wrong.
<code>function product_enquiry_schema() {
  $schema['product_enquiry'] = array(
    'description'=>'product enquiry',
    'fields'=>array(
      'id' => array(
        'description'=>'primary key value',
        'type'=>'serial'
      ),
      'product_id'=>array(
        'description'=>'product\'s id',
        'type'=>'int',
        'default'=>0
      ),
      'email'=>array(
        'type'=>'varchar',
        'length'=>100
      ),
      'message'=>array(
        'type'=>'varchar',
        'length'=>255
      ),
      'status'=>array(
        'type'=>'int',
        'default'=>1
      )
    )
  );

  return $schema;
}
</code>
Comment: please provide more information on error, which you're getting in "Recent Log Messages". As I can see some of the attributes are missing in your schema. Check [schema definition example](https://api.drupal.org/api/drupal/modules%21node%21node.install/function/node_schema/7.x) for ref.
Comment: Thanks for your reply. here is the response error : PDOException: SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'id': CREATE TABLE {product_enquiry} ( `id` INT unsigned NOT NULL auto_increment DEFAULT 0, `product_id` INT DEFAULT 0, `email` VARCHAR(100) DEFAULT '', `message` VARCHAR(255) DEFAULT '', `status` INT DEFAULT 0, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'product enquiry'; Array ( ) in db_create_table() (line 2776 of D:\drupal_new\includes\database\database.inc).
Answer: You need to set the default value of id column or simple replace the above code with the following one:
<code>'id' => array(
        'description'=>'primary key value',
        'type'=>'serial'
        'unsigned' => TRUE,
        'not null' => TRUE,
 ),
</code>


Need advise to link a cck field with several values to another cck field

Question: I am going to try to explain what I need to do. I have a content type called Goals. This content type has a cck text field. This field can has several values in order to write a goal in each value of the field.
What I want is when a user write a new goal (each goal is a value in the same cck field), he has a list tex field to point if he completed the goal.
How can i do this? What is the best option I have?
After I would like to create I view to show the goals completed and incompleted, so the goal and completed-incompleted must be linked in certain way.
Thanks a lot!
Answer: As per your requirement I think you have need to create something like project & the task related to the project. I have done something like this.
For this you will have to create a main content type to hold the project, which will have TITLE & BODY without any other fields.
Create one another content type with reference to first content type. User can add as many task as needed below the first content if permission is given. Add a field named STATUS in 2nd content type, which will hold this COMPLETED or NOT-COMPLETED status of the task.
You can make views of it below the first content type by adding relation between first & second content type & adding the fields by help of the relation.
Let me know if it works in your scenario..
Comment: Thank you, finally I did it with this field collection module. You can try it
Comment: @Santinuro - Congrats..but I don't need it as I am running with my own solution very efficiently..


How to get latitude and longitude passing pincode in Android

Question: How to get latitude and longitude by passing parameter as pincode.I have form with pincode. when entered some pincode number into text box,then how to get latitude and longitude.but not passing address how to get latitude and longitude only passing pincode as a parameter.
tried like this it's not working.can any one help me
java
final Geocoder geocoder = new Geocoder(getActivity());
                    pincode = pincode1.getText().toString();
                    try {
                        List<Address> addresses = geocoder.getFromLocationName(pincode, 1);
                        if (addresses != null && !addresses.isEmpty()) {
                            Address address = addresses.get(0);
                            // Use the address as needed
                            String message = String.format("Latitude: %f, Longitude: %f",
                                    address.getLatitude(), address.getLongitude());
                            Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                        } else {
                            // Display appropriate message when Geocoder services are not available
                            Toast.makeText(getActivity(), "Unable to geocode zipcode", Toast.LENGTH_LONG).show();
                        }
                    } catch (IOException e) {
                        // handle exception
                    }

Answer: Try this....
You can make http Get request for the following link.
http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:638701&sensor=false
Demo result:
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "638701",
               "short_name" : "638701",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "Tamil Nadu",
               "short_name" : "TN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Tamil Nadu 638701, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 11.12035,
                  "lng" : 77.7041998
               },
               "southwest" : {
                  "lat" : 10.9142493,
                  "lng" : 77.4507146
               }
            },
            "location" : {
               "lat" : 11.0179181,
               "lng" : 77.58486649999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 11.12035,
                  "lng" : 77.7041998
               },
               "southwest" : {
                  "lat" : 10.9142493,
                  "lng" : 77.4507146
               }
            }
         },
         "place_id" : "ChIJl35xdEKfqTsRcr8NKDs37OM",
         "types" : [ "postal_code" ]
      }
   ],
   "status" : "OK"
}

change the postal code Element According to your requirements
https://developers.google.com/maps/documentation/geocoding/intro?csw=1#JSON


How do I use the setting "Park (Day)" for the environment under Lighting from the gltf viewer to A-Frame?

Question: I'm trying to load a gltf model (link) to A-frame, but it appears dark, I've checked it using the link and the difference is that in the gltf viewer, under lighting, there's a field called environment which is set to "Park (Day)".
with environment set to: None

with environment set to: Park (Day)

How do I apply this setting to my model in A-Frame?
The other difference is the gammeOutput property which I have already fixed with "colorManagement: true" in the a-scene renderer.
Currently using version 0.9.0 of A-Frame
Answer: If you see an image being reflected by the model, it's an environment map. Its used when you want your object to reflect its surroundings or any other environment.
You can set it on primitives with either envMap (cubemap) or sphericalEnvMap (360 image) property:

Check it out in this fiddle.

With models, you'd need to dig in a bit deeper. You'd need to traverse the model, and set each mesh envMap property:
let texture = THREE.TextureLoader()
const mesh = element.getObject3D('mesh');
const envMap = texture;
if (!mesh) return;

mesh.traverse(function (node) {
  if (node.material && 'envMap' in node.material) {
    node.material.envMap = envMap;
    node.material.needsUpdate = true;
  }
});

Comment: Thank you for the response, I understand what it is now. I will try and apply my own environment map then.
Comment: @AxelRaymundo i see its working, glad i could help :)


Is it possible to embed a content creation form in views header?

Question: Suppose I am building a twitter-like site, and allow members to form groups with OG. So I have set up a view to list all the posts in a given group. However, I would like to embed a content creation form in the header (similar to how twitter is at the moment) with group audience set automatically to the group (therefore is not shown as an option in the form). Is there a way to do it without writing code (I haven't been doing drupal module development after D6...)?
Comment: I am using commons. As you know, everything on commons in associated with groups. How I can assign everything to single group automatically and hide it on the site.
Comment: commons? what is it?
Comment: It is a distribution
Answer: It doesn't have to be in the view header. Just place it block above the view and adjust the css so they sit together.
If you use entity forms and entity form blocks, you can just place a block above the view block (or panel pane).
Rules will allow you to create a new node, set the current OG_context as the new new node's group and then redirect back to the same page or to the new node.
Comment: so practically i can create an entity form, and somehow do something to publish a new content node (via rules?)? what if I do not have the OG_context set, cos the page I want to embed the form is actually a views page (OG_context can be set in a views?)?
Comment: It would make more sense for the view to be a block or panel in a group node. That way the new nodes will be subgroups. Then you can have different parent pages. As for rules, yea, you add an event for saving an entity form, add "entity has field" conditions and then actions to create new entity and set data or list fields.
Comment: Erm, now I have created an entity form with just the body field (from the content node), but i still don't see how everything is linked together @.@ so I include the form block to the group node page? how do I get the form to include the group nid?
Comment: In your rule, there should be a site:Current node from OG context or something like that. Use that to set the group for the node you create. I think you need the OG context module enabled.
Comment: If that doesn't work, I think you can create an entity reference field on the entity form and use the entity form prepopulate module and set it to hidden. That way the entity form has the OG node automatically for you to use in rules.
Comment: it works, the problem is that, I don't find a way to make the form follow the access control of group (without writing code that is), entity rules module is just confusing as .
Comment: Are you using panels or a block?
Comment: entityforms block module
Comment: Do you have mini-panels on the site? What I'm getting at here is it's really easy using panels "visibility" options.. It's not worth installing it for this use-case but it's great if you have it already.
Comment: nope, just pure blocks for now
Comment: You're going to need a custom module.. I'm not qualified to give you the best advice here so you should post a new question.
Comment: yea, looks like it
Answer: So based on @Niall Murphy's answer, my solution to the problem is as follows:

Instead of embeding the form in a view, I create an entity form and make it available as a block with entity forms block module. Then the block is shown in all the group content type node.
Also, in order to prepopulate the group id in the block, I installed Organic Groups Entityform Integration for that purpose.
Then I use the rules module to capture the form submission event, and then check if it has the fields in the entity form. If the fields exist, then I create a new content. Then the value value of the content is copied from the submitted form. Lastly, the form itself is deleted as they are not needed anymore.
Comment: bug: doesn't consider organic group permission
Comment: just found out about entity rules, figuring out how to get the form access rules working


What statistical test to use to examine attitude and which components have strong/weak influnces on attitude? 4-point Likert Scale survey

Question: This is a quantitative study using survey to examine attitude towards online reading. In the survey, there are 5 main components which contribute to overall attitude. Each component has different number of items. Four of those components using 4-point Likert Scale and one of the components is using "Never","Sometimes","Often","All the time."

Cognitive and Behavioral Engagement : 12 items (4 point likert scale "Strongly agree","Agree","Disagree","Strongly disagree")
Self-Regulatory Behavior: 14 items ("Never","Sometimes","Often","All the time")
Anxiety: 8 items (4 point Likert scale "Strongly agree", "Agree", "Disagree", "Strongly disagree")
Value/Interest: 12 items (4 point Likert scale "Strongly agree", "Agree", "Disagree", "Strongly disagree")
Efficacy for Online Reading: 8 items (4 point likert scale "Strongly agree", "Agree", "Disagree", "Strongly disagree")

My Research objectives and research questions are:

RO: To examine attitude towards online reading.
RQ: What is the attitude towards online reading?
RO: To determine the components that have strong/weak influence on overall attitude
RQ1: Which component has strong influence on attitude?
RQ2: Which component has weak influence on attitude?

What statistical test should I use to answer my research questions?I am using SPSS.Attitude is measured in an ordinal scale; positive, neutral and negative (if I'm not mistaken). I really hope you could help me solve this problem.
Thank you in advance for the help.
Answer: Adilah,
Attitudes toward online reading can be assessed with components 1, 3, 4, and 5. Attitude cannot be assessed with component 2 because this component represents self-behavior and the response options for component two are about frequency of behaviors, not attitudes.
Before assessing attitudes, I recommend running a cronbach's alpha test of internal consistency on each set of questions representing the components. The outcomes will tell you whether responses to each question is adequately related to other questions within the same component. If one question does not seem to fit too well, consider dropping it from a component. Make sure that you reverse score negatively phrased items, if there are any, before running cronbach's alpha. Cronbach's alpha is found under Scale in the SPSS Analyze drop down list -- choose reliability analysis.
Next aggregate the outcomes within each component. In other words, sum the responses for each question and then divide by the number of questions. For example, if component 3 (anxiety) is composed of items/questions 1, 2, 3, 4, 5, 6, 7, 8, then for each participant add up all 8 scores and then divide by 8. This will give you an overall component score for anxiety. Your anxiety score can then be compared using factors like gender and race. Note that although the data are ordinal, as you pointed out, when you combine items into an overall score, it is appropriate to use parametric statistics with  analyses on the overall component scores.
If you want to determine overall attitude you would need to repeat the above process combining all items except #2. Determining weak vs. strong influence of components on overall attitude could be tricky because an attitude in either the left or right direction can be equally strong. I suppose that components with overall scores closest to the mean (between disagree and agree) would qualify as those being the weakest because it suggests neutral attitude.
Comment: I give a lengthy description that contains information about something I do on a continual basis in a professional setting and have published articles on in peer-reviewed journals, and somebody down votes my reply! The person who down voted my reply can pay $100 learning the same thing from a statistical consultant if they don't believe me. This voting format is silly. I am out of here. So long Cross Validated.


Erro de módulo no AngularJS

Question: Não consigo entender e corrigir esse erro. estou usando ionic.

Uncaught Error: [$injector:modulerr] Failed to instantiate module
  inparty due to: Error: [$injector:modulerr] Failed to instantiate
  module inparty.controllers due to: Error: [$injector:nomod] Module
  'inparty.controllers' is not available! You either misspelled the
  module name or forgot to load it. If registering a module ensure that
  you specify the dependencies as the second argument.

angular.module('inparty.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
  // Form data for the login modal
 $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
   scope: $scope
  }).then(function(modal) {
$scope.modal = modal;
 });

// Triggered in the login modal to close it
    $scope.closeLogin = function() {
    $scope.modal.hide();
 };

 // Open the login modal
   $scope.login = function() {
    $scope.modal.show();
  };

   // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
     console.log('Doing login', $scope.loginData);

    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
   $timeout(function() {
      $scope.closeLogin();
   }, 1000);
};
})

 .controller('PlaylistsCtrl', function($scope,$http) {
     $scope.dados = Array();

    $http.get("js/dados.php").success(function(data){
        $scope.dados = data.dados;
        console.log($scope.dados);
    }).error(function(data){
        alert("Error...");
        console.log(data);
    });
})

.controller('PlaylistCtrl', function($scope, $stateParams) {
 var idParaEncontrar = $stateParams.id;
console.log(idParaEncontrar);
var objectoEncontrado = undefined;

               for(var i = 0; i < $scope.dados.length: ++i){
            if($scope.dados[i].id === idParaEncontrar) {
                objectoEncontrado = $scope.dados[id];
            break;
            }
            }
if(objectoEncontrado !== undefined) {
    console.log("objecto encontrado")
  }
 });

app.js
angular.module('inparty', ['ionic', 'inparty.controllers','ngRoute'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
   // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
     // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
   }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
   }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
   $stateProvider

  .state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "templates/menu.html",
    controller: 'AppCtrl'
 })

 .state('app.search', {
   url: "/search",
    views: {
     'menuContent': {
        templateUrl: "templates/search.html"
      }
    }
  })

  .state('app.browse', {
     url: "/browse",
   views: {
      'menuContent': {
        templateUrl: "templates/browse.html"
      }
   }
  })
   .state('app.playlists', {
     url: "/playlists",
      views: {
        'menuContent': {
          templateUrl: "templates/playlists.html",
          controller: 'PlaylistsCtrl'
        }
      }
   })

 .state('app.single', {
    url: "/playlists/:id",
    views: {
     'menuContent': {
        templateUrl: "templates/playlist.html",
        controller: 'PlaylistCtrl'
      }
    }
 });
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/playlists');
});

Answer: De acordo com a descrição do erro, me parece que o módulo inparty.controllers ainda não está carregado/definido quando o angular inicia seu bootstrap.
Teste as seguintes alterações:
app.js
var inpartyControllers = angular.module('inparty.controllers', []);

angular.module('inparty', ['ionic', 'inparty.controllers','ngRoute'])
.run(function($ionicPlatform) {
// Seu código continua aqui.

E quando você for definir seu controle consuma a referência ao módulo inicializado, assim:
inpartyControllers
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
  // Form data for the login modal
 $scope.loginData = {};
 // Seu código continua aqui.

Comment: Blz aparentemente de certo e consegui entender o porque disso mais infelizmente passou a ocorrer este erro ... Argument 'AppCtrl' is not a function, got undefined
Comment: @MatheusMonteiro em que parte? Quando você configura suas rotas?
Comment: não sei te dizer estou meio perdido ... segue o codigo de como ficou com as suas alterações .... http://pastebin.com/ZU3aqXh3    http://pastebin.com/vaEwXdwf
Comment: @MatheusMonteiro Posso dar uma olhada na exception também? Ajudaria bastante
Comment: segue o projeto .. https://mega.co.nz/#!lEIxXS4I!xy3eG0g60y5VoUKC2rN3bqeRyLruYuEcKA76MAHpom0
Answer: Amigo, tenta usar normalmente a definição do módulo no angular, pode ser que esteja dando redundância de módulos:
angular.module('inparty.controllers', [])

tente colocar isso no seu arquivo "controllers.js".
Apague a linha:
inpartyControllers

Comment: Tente também não criar a função "inpartyControllers", deixe ela de lado por enquanto.

Erro de módulo no AngularJS


What does the matrix $\frac{1}{n-1} X^{t}X$ represent?

Question: Let be $Y$ the matrix of observations with $n$ lines and $m$ columns.
Let be $X$ the centered matrix, where $X_{i,j} = Y_{i,j} - \overline{Y_{.,j}}$ , $i = 1:n$, $j = 1:m$
Edit : $\overline{Y_{.,j}}$ is the mean of each column
$X^{t}$ is the transpose matrix
What is this matrix $\frac{1}{n-1} X^{t}X$ ?
Comment: The squared deviations from the median?
Comment: Looks like a sample variance covariance matrix where the centering has been done using the median
Answer: It is the estimated variance-covariance matrix of the Y's. It is a square, symmetric matrix with the variances on the diagonal (for i = 1, 2, ..., n). The covariances are in the off-diagonal cells where the covariance of Yi and Yj is in the (i, j) cell.


Liferay and Oracle DB

Question: I'm installing liferay community edition with an Oracle database, I managed to get it running with the user SYSTEM, but I don't like this... I want to create another user in another tablespace, the problem is that it seems that liferay needs to create tables and alter them according during its lifetime.
Do you know what permission and roles need to be assigned to the user?
Thanks a lot in advance.
Answer: The default Oracle install normally has a USERS tablespace. If you are happy with that, try
CREATE USER liferay IDENTIFIED BY password DEFAULT TABLESPACE users QUOTA UNLIMITED ON users;
GRANT CREATE SESSION, CREATE TABLE, CREATE TRIGGER, CREATE SEQUENCE, CREATE VIEW TO liferay;
That might be sufficient. If the setup script errors, then other permissions may be required.
Comment: FYI: The extra permissions are only required during installation or update (or deployment of new plugins) - during the "normal" runtime, only the standard operations SELECT, INSERT, UPDATE and DELETE are required.
Comment: Ok, that seems to be working, thanks a lot for your help!
Answer: Be careful using the USERS tablespace. It's not technically good practice, but it will work fine.
Here's what I use and it works pretty well.
CREATE TABLESPACE LPORTAL7 DATAFILE '/opt/oracle/data/liferay_01.dbf' SIZE 2G AUTOEXTEND ON MAXSIZE UNLIMITED;
CREATE USER LPORTAL7 IDENTIFIED BY <password> DEFAULT TABLESPACE LPORTAL7;
GRANT CONNECT, RESOURCE, CREATE VIEW TO LPORTAL7;
ALTER USER LPORTAL7 QUOTA UNLIMITED ON LPORTAL7;

Liferay and Oracle DB