text:
Q: Efficiently process each unique permutation of a vector when number of unique elements in vector is much smaller than vector size In a program I need to apply a function in parallel to each unique permutation of a vector. The size of the vector is around N=15
I already have a function void parallel_for_each_permutation which I can use in combination with a std::set to only process each unique permutation exactly once.
This all works well for the general case. However, in my use case the number of unique elements k per vector is very limited, usually around k=4. This means that I'm currently wasting time constructing the same unique permutation over and over again, just to throw it away because it has already been processed.
Is it possible to process all unique permutations in this special case, without constructing all N! permutations?
Example use-case:
#include <algorithm>
#include <thread>
#include <vector>
#include <mutex>
#include <numeric>
#include <set>
#include <iostream>

template<class Container1, class Container2>
struct Comp{
    //compare element-wise less than
    bool operator()(const Container1& l, const Container2& r) const{
        auto pair = std::mismatch(l.begin(), l.end(), r.begin());
        if(pair.first == l.end() && pair.second == r.end())
            return false;
        return *(pair.first) < *(pair.second);
    }
};

template<class Container, class Func>
void parallel_for_each_permutation(const Container& container, int num_threads, Func func){
    auto ithPermutation = [](int n, size_t i) -> std::vector<size_t>{
        // https://stackoverflow.com/questions/7918806/finding-n-th-permutation-without-computing-others
        std::vector<size_t> fact(n);
        std::vector<size_t> perm(n);

        fact[0] = 1;
        for(int k = 1; k < n; k++)
            fact[k] = fact[k-1] * k;

        for(int k = 0; k < n; k++){
            perm[k] = i / fact[n-1-k];
            i = i % fact[n-1-k];
        }

        for(int k = n-1; k > 0; k--){
            for(int j = k-1; j >= 0; j--){
                if(perm[j] <= perm[k])
                    perm[k]++;
            }
        }

        return perm;
    };

    size_t totalNumPermutations = 1;
    for(size_t i = 1; i <= container.size(); i++)
        totalNumPermutations *= i;

    std::vector<std::thread> threads;

    for(int threadId = 0; threadId < num_threads; threadId++){
        threads.emplace_back([&, threadId](){
            const size_t firstPerm = size_t(float(threadId) * totalNumPermutations / num_threads);
            const size_t last_excl = std::min(totalNumPermutations, size_t(float(threadId+1) * totalNumPermutations / num_threads));

            Container permutation(container);

            auto permIndices = ithPermutation(container.size(), firstPerm);

            size_t count = firstPerm;
            do{
                for(int i = 0; i < int(permIndices.size()); i++){
                    permutation[i] = container[permIndices[i]];
                }

                func(threadId, permutation);
                std::next_permutation(permIndices.begin(), permIndices.end());
                ++count;
            }while(count < last_excl);
        });
    }

    for(auto& thread : threads)
        thread.join();
}

template<class Container, class Func>
void parallel_for_each_unique_permutation(const Container& container, Func func){
    using Comparator = Comp<Container, Container>;
    constexpr int numThreads = 4;

    std::set<Container, Comparator> uniqueProcessedPermutations(Comparator{});
    std::mutex m;

    parallel_for_each_permutation(
        container,
        numThreads,
        [&](int threadId, const auto& permutation){

            {
                std::lock_guard<std::mutex> lg(m);
                if(uniqueProcessedPermutations.count(permutation) > 0){
                    return;
                }else{
                    uniqueProcessedPermutations.insert(permutation);
                }
            }

            func(permutation);
        }
    );
}

int main(){
    std::vector<int> vector1{1,1,1,1,2,3,2,2,3,3,1};

    auto func = [](const auto& vec){return;};

    parallel_for_each_unique_permutation(vector1, func);
}

A: The permutations you have to work with are known in the field of combinatorics as multiset permutations.
They are described for example on The Combinatorial Object Server
with more detailed explanations in this paper by professor Tadao Takaoka.
You have some related Python code and some C++ code in the FXT open source library.
You might consider adding the "multiset" and "combinatorics" tags to your question.
One possibility is to borrow the (header-only) algorithmic code from the FXT library, which provides a simple generator class for those multiset permutations.
Performance level:
Using the FXT algorithm on a test vector of 15 objects, {1,1,1, 2,2,2, 3,3,3,3, 4,4,4,4,4}, one can generate all associated 12,612,600 "permutations" in less than 2 seconds on a plain vanilla Intel x86-64 machine; this is without diagnostics text I/O and without any attempt at optimization.
The algorithm generates exactly those "permutations" that are required, nothing more. So there is no longer a need to generate all 15! "raw" permutations nor to use mutual exclusion to update a shared data structure for filtering purposes.
An adaptor class for generating the permutations:
I will try below to provide code for an adaptor class, which allows your application to use the FXT algorithm while containing the dependency into a single implementation file. That way, the code will hopefully fit better into your application. Think FXT's ulong type and use of raw pointers, versus std::vector<std::size_t> in your code. Besides, FXT is a very extensive library.
Header file for the "adaptor" class:
// File:  MSetPermGen.h

#ifndef  MSET_PERM_GEN_H
#define  MSET_PERM_GEN_H

#include  <iostream>
#include  <vector>

class MSetPermGenImpl;  // from algorithmic backend

using  IntVec  = std::vector<int>;
using  SizeVec = std::vector<std::size_t>;

// Generator class for multiset permutations:

class MSetPermGen {
public:
    MSetPermGen(const IntVec& vec);

    std::size_t       getCycleLength() const;
    bool              forward(size_t incr);
    bool              next();
    const SizeVec&    getPermIndices() const;
    const IntVec&     getItems() const;
    const IntVec&     getItemValues() const;

private:
    std::size_t       cycleLength_;
    MSetPermGenImpl*  genImpl_;         // implementation generator
    IntVec            itemValues_;      // only once each
    IntVec            items_;           // copy of ctor argument
    SizeVec           freqs_;           // repetition counts
    SizeVec           state_;           // array of indices in 0..n-1
};

#endif

The class constructor takes exactly the argument type provided in your main program. Of course, the key method is next(). You can also move the automaton by several steps at once using the forward(incr)method.
Example client program:
// File:  test_main.cpp

#include  <cassert>
#include  "MSetPermGen.h"

using  std::cout;
using  std::cerr;
using  std::endl;

// utility functions:

std::vector<int>  getMSPermutation(const MSetPermGen& mspg)
{
    std::vector<int>  res;
    auto indices = mspg.getPermIndices();  // always between 0 and n-1
    auto values  = mspg.getItemValues();  // whatever the user put in

    std::size_t n = indices.size();
    assert( n == items.size() );
    res.reserve(n);

    for (std::size_t i=0; i < n; i++) {
        auto xi = indices[i];
        res.push_back(values[xi]);
    }

    return res;
}

void printPermutation(const std::vector<int>& p, std::ostream& fh)
{
    std::size_t n = p.size();

    for (size_t i=0; i < n; i++)
        fh << p[i] << " ";
    fh << '\n';
}

int main(int argc, const char* argv[])
{
    std::vector<int>  vec0{1,1, 2,2,2};                        // N=5
    std::vector<int>  vec1{1,1, 1,1, 2, 3, 2,2, 3,3, 1};       // N=11
    std::vector<int>  vec2{1,1,1, 2,2,2, 3,3,3,3, 4,4,4,4,4};  // N=15

    MSetPermGen  pg0{vec0};
    MSetPermGen  pg1{vec1};
    MSetPermGen  pg2{vec2};

    auto pg = &pg0;  // choice of 0, 1, 2 for sizing
    auto cl = pg->getCycleLength();

    auto permA = getMSPermutation(*pg);
    printPermutation(permA, cout);
    for (std::size_t pi=0; pi < (cl-1); pi++) {
        pg->next();
        auto permB = getMSPermutation(*pg);
        printPermutation(permB, cout);
    }

    return EXIT_SUCCESS;
}

Text output from the above small program:
1 1 2 2 2
1 2 1 2 2
1 2 2 1 2
1 2 2 2 1
2 1 1 2 2
2 1 2 1 2
2 1 2 2 1
2 2 1 1 2
2 2 1 2 1
2 2 2 1 1

You get only 10 items from vector {1,1, 2,2,2}, because 5! / (2! * 3!) = 120/(2*6) = 10.
The implementation file for the adaptor class, MSetPermGen.cpp, consists of two parts. The first part is FXT code with minimal adaptations. The second part is the MSetPermGen class proper.
First part of implementation file:
// File:  MSetPermGen.cpp - part 1 of 2 - FXT code

// -------------- Beginning  of header-only FXT combinatorics code -----------

 // This file is part of the FXT library.
 // Copyright (C) 2010, 2012, 2014 Joerg Arndt
 // License: GNU General Public License version 3 or later,
 // see the file COPYING.txt in the main directory.

//--  https://www.jjj.de/fxt/
//--  https://fossies.org/dox/fxt-2018.07.03/mset-perm-lex_8h_source.html

#include  <cstddef>
using ulong = std::size_t;

inline void  swap2(ulong& xa, ulong& xb)
{
    ulong  save_xb = xb;

    xb = xa;
    xa = save_xb;
}

class mset_perm_lex
 // Multiset permutations in lexicographic order, iterative algorithm.
 {
 public:
     ulong k_;    // number of different sorts of objects
     ulong *r_;   // number of elements '0' in r[0], '1' in r[1], ..., 'k-1' in r[k-1]
     ulong n_;    // number of objects
     ulong *ms_;  // multiset data in ms[0], ..., ms[n-1], sentinels at [-1] and [-2]

 private:  // have pointer data
     mset_perm_lex(const mset_perm_lex&);  // forbidden
     mset_perm_lex & operator = (const mset_perm_lex&);  // forbidden

 public:
     explicit mset_perm_lex(const ulong *r, ulong k)
     {
         k_ = k;
         r_ = new ulong[k];
         for (ulong j=0; j<k_; ++j)  r_[j] = r[j];  // get buckets

         n_ = 0;
         for (ulong j=0; j<k_; ++j)  n_ += r_[j];
         ms_ = new ulong[n_+2];
         ms_[0] = 0; ms_[1] = 1;  // sentinels:  ms[0] < ms[1]
         ms_ += 2;  // nota bene

         first();
     }

     void first()
     {
         for (ulong j=0, i=0;  j<k_;  ++j)
             for (ulong h=r_[j];  h!=0;  --h, ++i)
                 ms_[i] = j;
     }

     ~mset_perm_lex()
     {
         ms_ -= 2;
         delete [] ms_;
         delete [] r_;
     }

     const ulong * data()  const { return ms_; }

     ulong next()
     // Return position of leftmost change,
     // return n with last permutation.
     {
         // find rightmost pair with ms[i] < ms[i+1]:
         const ulong n1 = n_ - 1;
         ulong i = n1;
         do  { --i; }  while ( ms_[i] >= ms_[i+1] );  // can read sentinel
         if ( (long)i < 0 )  return n_;  // last sequence is falling seq.

         // find rightmost element ms[j] less than ms[i]:
         ulong j = n1;
         while ( ms_[i] >= ms_[j] )  { --j; }

         swap2(ms_[i], ms_[j]);

         // Here the elements ms[i+1], ..., ms[n-1] are a falling sequence.
         // Reverse order to the right:
         ulong r = n1;
         ulong s = i + 1;
         while ( r > s )  { swap2(ms_[r], ms_[s]);  --r;  ++s; }

         return i;
     }
 };

// -------------- End of header-only FXT combinatorics code -----------

Second part of the class implementation file:
// Second part of file MSetPermGen.cpp: non-FXT code

#include  <cassert>
#include  <tuple>
#include  <map>
#include  <iostream>
#include  <cstdio>

#include  "MSetPermGen.h"

using  std::cout;
using  std::cerr;
using  std::endl;

class MSetPermGenImpl {  // wrapper class
public:
    MSetPermGenImpl(const SizeVec& freqs) : fg(freqs.data(), freqs.size())
    {}
private:
    mset_perm_lex   fg;

    friend class MSetPermGen;
};

static std::size_t  fact(size_t n)
{
    std::size_t  f = 1;

    for (std::size_t i = 1; i <= n; i++)
        f = f*i;
    return f;
}

MSetPermGen::MSetPermGen(const IntVec& vec) : items_(vec)
{
    std::map<int,int>  ma;

    for (int i: vec) {
        ma[i]++;
    }
    int item, freq;
    for (const auto& p : ma) {
       std::tie(item, freq) = p;
       itemValues_.push_back(item);
       freqs_.push_back(freq);
    }
    cycleLength_ = fact(items_.size());
    for (auto i: freqs_)
        cycleLength_ /= fact(i);

    // create FXT-level generator:
    genImpl_ = new MSetPermGenImpl(freqs_);
    for (std::size_t i=0; i < items_.size(); i++)
        state_.push_back(genImpl_->fg.ms_[i]);
}

std::size_t  MSetPermGen::getCycleLength() const
{
    return cycleLength_;
}

bool  MSetPermGen::forward(size_t incr)
{
    std::size_t  n  = items_.size();
    std::size_t  rc = 0;

    // move forward state by brute force, could be improved:
    for (std::size_t i=0; i < incr; i++)
        rc = genImpl_->fg.next();

    for (std::size_t j=0; j < n; j++)
        state_[j] = genImpl_->fg.ms_[j];
    return (rc != n);
}

bool  MSetPermGen::next()
{
    return forward(1);
}

const SizeVec&  MSetPermGen::getPermIndices() const
{
    return (this->state_);
}

const IntVec&  MSetPermGen::getItems() const
{
    return (this->items_);
}

const IntVec&  MSetPermGen::getItemValues() const
{
    return (this->itemValues_);
}

Adapting the parallel application:
Regarding your multithreaded application, given that generating the "permutations" is cheap, you can afford to create one generator object per thread.
Before launching the actual computation, you forward each generator to its appropriate initial position, that is at step thread_id * (cycleLength / num_threads).
I have tried to adapt your code to this MSetPermGen class along these lines. See code below.
With 3 threads, an input vector {1,1,1, 2,2,2, 3,3,3,3, 4,4,4,4,4} of size 15 (giving 12,612,600 permutations) and all diagnostics enabled, your modified parallel program runs in less than 10 seconds; less than 2 seconds with all diagnostics switched off.
Modified parallel program:
#include  <algorithm>
#include  <thread>
#include  <vector>
#include  <atomic>
#include  <mutex>
#include  <numeric>
#include  <set>
#include  <iostream>
#include  <fstream>
#include  <sstream>
#include  <cstdlib>

#include  "MSetPermGen.h"

using  std::cout;
using  std::endl;

// debug and instrumentation:
static std::atomic<size_t>  permCounter;
static bool doManagePermCounter = true;
static bool doThreadLogfiles    = true;
static bool doLogfileHeaders    = true;

template<class Container, class Func>
void parallel_for_each_permutation(const Container& container, int numThreads, Func mfunc) {

    MSetPermGen  gen0(container);
    std::size_t totalNumPermutations = gen0.getCycleLength();
    std::size_t permShare = totalNumPermutations / numThreads;
    if ((totalNumPermutations % numThreads) != 0)
        permShare++;
    std::cout << "totalNumPermutations: " << totalNumPermutations << std::endl;

    std::vector<std::thread>  threads;

    for (int threadId = 0; threadId < numThreads; threadId++) {
        threads.emplace_back([&, threadId]() {

            // generate some per-thread logfile name
            std::ostringstream  fnss;
            fnss << "thrlog_" << threadId << ".txt";
            std::string    fileName = fnss.str();
            std::ofstream  fh(fileName);

            MSetPermGen  thrGen(container);
            const std::size_t firstPerm = permShare * threadId;
            thrGen.forward(firstPerm);

            const std::size_t last_excl = std::min(totalNumPermutations,
                                             (threadId+1) * permShare);

            if (doLogfileHeaders) {
                fh << "MSG threadId: "  << threadId << '\n';
                fh << "MSG firstPerm: " << firstPerm << '\n';
                fh << "MSG lastExcl : " << last_excl << '\n';
            }

            Container permutation(container);
            auto values      = thrGen.getItemValues();
            auto permIndices = thrGen.getPermIndices();
            auto nsz         = permIndices.size();

            std::size_t count = firstPerm;
            do {
                for (std::size_t i = 0; i < nsz; i++) {
                    permutation[i] = values[permIndices[i]];
                }

                mfunc(threadId, permutation);

                if (doThreadLogfiles) {
                    for (std::size_t i = 0; i < nsz; i++)
                        fh << permutation[i] << ' ';
                    fh << '\n';
                }
                thrGen.next();
                permIndices = thrGen.getPermIndices();
                ++count;
                if (doManagePermCounter) {
                    permCounter++;
                }
            } while (count < last_excl);

            fh.close();
        });
    }

    for(auto& thread : threads)
        thread.join();
}

template<class Container, class Func>
void parallel_for_each_unique_permutation(const Container& container, Func func) {
    constexpr int numThreads = 3;

    parallel_for_each_permutation(
        container,
        numThreads,
        [&](int threadId, const auto& permutation){
            // no longer need any mutual exclusion
            func(permutation);
        }
    );
}

int main()
{
    std::vector<int>  vector1{1,1,1,1,2,3,2,2,3,3,1};             // N=11
    std::vector<int>  vector0{1,1, 2,2,2};                        // N=5
    std::vector<int>  vector2{1,1,1, 2,2,2, 3,3,3,3, 4,4,4,4,4};  // N=15

    auto func = [](const auto& vec) { return; };

    permCounter.store(0);

    parallel_for_each_unique_permutation(vector2, func);

    auto finalPermCounter = permCounter.load();
    cout << "FinalPermCounter = " << finalPermCounter << endl;

}


text:
Q: Send timestamp array parameter to PostgreSQL function i have developed a pgplsql function to receive array of dates the return the maximum date, but its not able to call the function:
select 1, arcfm.array_max_date('{2022-02-03, 2022-06-05}'::timestamp[]) as max_date_time;

CREATE OR REPLACE FUNCTION arcfm.array_max_date(in dates_array timestamp[])
RETURNS timestamp
LANGUAGE plpgsql
AS $$
declare
max_date_time timestamp;
BEGIN
SELECT max(x) into max_date_time FROM dates_array as x;
return max_date_time;
END;
$$
;

tried calls like:
select 1, arcfm.array_max_date('{2022-02-03, 2022-06-05}'::timestamp[]) as max_date_time;
and expected the maximum date but it gives call error
SQL Error [42P01]: ERROR: relation "dates_array" does not exist
Where: PL/pgSQL function array_max_date(timestamp without time zone[]) line 5 at SQL statement

A: You can use unnest() to convert the array to a set of rows, and then use max() to get the maximum value:
select max(x)
from unnest('{2022-02-03, 2022-06-05}'::timestamp[]) as x;

A: The better answer as suggested by Fastnlight is by using built-in function called "GREATEST"
SELECT GREATEST('2022-02-03'::timestamp, '2022-06-05'::timestamp);

The explanation of Adrian Klaver fixed my function issue also:
CREATE OR REPLACE FUNCTION arcfm.array_max_date(in dates_array timestamp[])
    RETURNS timestamp
    LANGUAGE plpgsql
AS $$
    declare
        max_date_time timestamp;
    BEGIN
        SELECT max(x) into max_date_time FROM unnest(dates_array) as x;
        return max_date_time;
    END;
$$
;

select 1, arcfm.array_max_date('{2022-02-03, 2022-06-05}'::timestamp[]) as max_date_time;

redpajama_set_name: RedPajamaStackExchange


text:
Q: UUID not valid at this position (Mysql workbench) I was trying to create a table and in this I was using id attribute as UUID but it is showing error that it is not valid at this position it is expecting something else
CREATE TABLE  account (
a_id                    UUID                PRIMARY KEY,
a_hash                  VARCHAR(66)         NOT NULL,
a_email                 VARCHAR(500)        NOT NULL,
a_password              VARCHAR(60)         NOT NULL,
a_verification_key      UUID                NOT NULL,
a_disabled              BOOLEAN             DEFAULT FALSE NOT NULL,
a_verified              BOOLEAN             DEFAULT FALSE NOT NULL,
a_role                  VARCHAR(20)         NOT NULL,
a_created_at            TIMESTAMP           DEFAULT NOW() NOT NULL

);
Here a_id field is UUID type and a_verification_key is also UUID
and it is giving me error in mysql workbench

A: You can use UUID, specify columnDefinition to VARCHAR(255) or CHAR(16) or BINARY(16) using @Column, with this you can use the functionality of UUID. You may change strategy and generator as per your requirement
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "a_id", columnDefinition = "VARCHAR(255)")
private UUID a_id;

Discussion Function UUID


text:
Q: Preventing Finder from changing "Date Modified" attribute Finder has a pesky trait where sometimes it would set Date Modified to today's when browsing a really old folder.
For the time being, I am using attribute Date Modified as a quick guidance when looking for something.
To preserve Date Modified attribute, I am using sudo chflags -R uchg <folder> and sudo chflags -R schg <folder inside iCloud Drive folders.
Actual question - are there any issues/risks/problems when using sudo chflags -R schg <folder> and sudo chflags -R uchg <folder> inside iCloud Drive folder?
Ps. I realize that setting these flags will prevent me from making any edits (i.e. access will be read-only for my user and the system); that's my intention, I want to treat certain folders as true archives - i.e. no edits whatsoever even to attributes


text:
Q: Understanding differentiability in functions of two variables In functions of single variable we would say that a function $f$ is differentiable at $x=a$ if:
$\lim_{h\to 0} \frac{f(a+h) - f(a)} {h} $
Exists and equals a real number which becomes $f'(a)$ . And this leads(and it is clear how) to an equivalent definition :
There exists a function $\epsilon(h)$  that tends to $0$ as $h$ tends to $0$ and
$f(a+h) =f(a) + hf'(a) + h\epsilon(h) $.
Now in my textbook the idea of differentiability was introduced by saying that we say that $f$ is differentiable at $(a, b)$ if there exists an $\epsilon(h,k)$ that tends to $0$ as $||(h,k)||$ ($||.||$ is a defined norm on the domain) tends to $(0,0)$ such that
$f(a+h,b+k) =f(a,b) +hf'_x(a, b) +kf'_y(a, b) +||(h,k)|| \epsilon(h, k) $.
My problem is that I do understand the graphical meaning of differentiability for one variable, but for two variables does this definition cover $\mathbf only$ the existence of the partial derivatives of f at this point? What is the intuition behind this definition?

A: The idea behind is that, around your point, the function is approximately linear. Namely, if $h$ and $k$ are small increments from $(a,b)$ and we call $(x,y)=(a+h,b+k)$, then
$$
f(x,y)=f(a+h,b+k)\approx f(a,b)+Ah+Bk=f(a,b)+A(x-a)+B(y-b)
$$
and the error is much smaller that $h$ or $k$ in size. This condition forces the partial derivatives to exist, and they should be equal to $A$ and $B$ respectively.
Geometrically, we are requiring that the graph of the function had a tangent plane (or hyperplane in higher dimensions). Having partial derivatives is a weaker restriction. Differentiability requires linearity in all directions, while the mere existence of the partial derivatives means that your function is linear in one variable if you keep the other one fixed.


text:
Q: Best practice to apply bitwise AND logic on SELECT I'm trying to find the best way to apply the following logic. Our business logic requires me to insert a bunch of rows into a var table, then select all distinct records but set a condition to positive only if it matches all records with same id [So basically bitwise AND]
Hopefully my example explains that better.
DECLARE @sometable TABLE (
record_id INT NOT NULL,
some_condition BIT NOT NULL)

records in that table would match
record_id some_condition
1         1
1         0
2         0
3         0

In the above case the desired output should be
record_id some_condition
1         0
2         0
3         0

Till now how I've been doing this is like this
SELECT DISTINCT record_id  CAST(MIN(CAST(some_condition INT)) AS some_condition
FROM @sometable
GROUP BY record_id

Is there a better way to do this? I'm having to CAST the var as MIN only takes numeric types.

A: how about using a case statement?
select record_id,
min(case when some_condition=0 then 0 else 1 end) as minCond
from sometable
group by
record_id

A: Firstly, you can leave out DISTINCT, since GROUP BY already makes them distinct.  Also, you can avoid the innermost CAST if you just add 0:
SELECT record_id,  CAST(MIN(some_condition+0) as BIT) AS some_condition
FROM @sometable
GROUP BY record_id

Finally, do you really need to recast to a BIT when done?  Depending on how the query results are used, that might not be needed.


text:
Q: Running code after i perform a segue? Is there a way I can run code after performSegueWithIdentifier? So a button performs a segue to view controller 2 and in view controller 2 I want it to execute "refresh" code (populating its table view via parse.com).
Right now I have the "refresh" code in view controller 2's viewDidAppear, but changing it to perform the "refresh" code after doing the segue would reduce API requests.

A: You typically use prepareForSegue(_:sender:) to execute code before the segue is executed, or viewDidLoad() for code that you want to execute when the segue is finished.
For finer control, you could subclass UIStoryboardSegue and create a custom segue, but it doesn't sound like you need that for this issue.


text:
Q: python - vlookup in pandas applying %LIKE% I am new to Python, and I am trying to join two CSV files (delimited by ";")
CSV1
Sender;Recipient
Adam;123
Alex;234
John;123
Adam;888

CSV2
Name;Phone
Winnie;123,234,456
Celeste;777,888,999

Intended Output:
Sender;Recipient;RecipientName
Adam;123;Winnie
Alex;234;Winnie
John;123;Winnie
Adam;888;Celeste

Phone in CSV2 is separated by comma(s). So I need to do some kind of search or %LIKE% when I am matching.
I know I can use join to do a vlookup type but how can I achieve the %LIKE%?

A: *

*Use str.split to turn Phone column into lists

*Use str.len() to find the length of each of those lists.  We'll use this to explode the 'Name' column

*Push all those lists together into one.  Make sure to filter out zero length lists

*Use repeat to explode 'Name'

*Create a dictionary where keys are phone numbers and values are names

*Create a copy of d1 where we've added the new column using map and the new dictionary we made.

p = d2.Phone.str.split(',')
p = p[p.astype(bool)]
l = p.str.len()
p2 = np.concatenate(p.values).astype(int)
nm = d2.Name.repeat(l)
m = dict(zip(p2, nm))

df = d1.assign(RecipientName=d1.Recipient.map(m))
print(df)

  Sender  Recipient RecipientName
0   Adam        123        Winnie
1   Alex        234        Winnie
2   John        123        Winnie
3   Adam        888       Celeste

df.to_csv('out.csv', sep=';', header=None)

Sender;Recipient;RecipientName
Adam;123;Winnie
Alex;234;Winnie
John;123;Winnie
Adam;888;Celeste

A: Solution for map by Series:
from  itertools import chain

#split values by `,` to lists
lens = df2['Phone'].str.split(',')
#if some zero list remove it
df2 = df2.dropna(subset=['Phone'])

#explode Names by length of lists, flat values by chain.from_iterable
s = pd.Series(np.repeat(df2.Name.values, lens),
              index= list(chain.from_iterable(df2.Phone.values)))
#convert index to int for match
s.index = s.index.astype(int)
print (s)
123     Winnie
234     Winnie
456     Winnie
777    Celeste
888    Celeste
999    Celeste
dtype: object

#map values to new column
df1['RecipientName'] = df1['Recipient'].map(s)
print(df1)
  Sender  Recipient RecipientName
0   Adam        123        Winnie
1   Alex        234        Winnie
2   John        123        Winnie
3   Adam        888       Celeste

#write to csv
df.to_csv('out.csv', sep=';', header=None)

Sender;Recipient;RecipientName
Adam;123;Winnie
Alex;234;Winnie
John;123;Winnie
Adam;888;Celeste

Solution with join is similar:
df2['Phone'] = df2['Phone'].str.split(',')
df2 = df2.dropna(subset=['Phone'])

s = pd.Series(np.repeat(df2.Name.values, df2.Phone.str.len()),
              index= list(chain.from_iterable(df2.Phone.values)))
s.index = s.index.astype(int)
s.name = 'RecipientName'
print (s)

df1 = df1.join(s, on='Recipient')
print(df1)
  Sender  Recipient RecipientName
0   Adam        123        Winnie
1   Alex        234        Winnie
2   John        123        Winnie
3   Adam        888       Celeste

EDIT:
My data samples:
import pandas as pd
from pandas.compat import StringIO

temp=u"""
Sender;Recipient
Adam;123
Alex;234
John;123
Adam;888"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df1 = pd.read_csv(StringIO(temp), sep=";")
print (df1)
  Sender  Recipient
0   Adam        123
1   Alex        234
2   John        123
3   Adam        888

temp=u"""
Name;Phone
Winnie;123,234,456
Celeste;777,888,999"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df2 = pd.read_csv(StringIO(temp), sep=";")
print (df2)
      Name        Phone
0   Winnie  123,234,456
1  Celeste  777,888,999

A: Here's some pseudocode and an idea on how to do this.
I would start by parsing the CSV2 file. Skip the first line, then for the following lines parse out the name & phone, then maintain a dictionary of which name is associated with each phone number.
numbers_to_names = {}
for line in open("csv2", "r").splitlines():
    name, phone_numbers = line.split(";")
    for phone_number in phone_numbers.split(","):
        numbers_to_names[phone_number] = name

Then when going through CSV1 again skip the first line, then parse out sender and recipient and combine with dictionary results from before.
for line in open("csv1", "r").splitlines():
    sender, recipient = line.split(";")
    print "%s;%s;%s" % (sender, recipient, numbers_to_names[recipient])


text:
Q: How does Push Notifications work while in development and production mode, (pushwoosh) So i have a question to which i could not find an answer on PushWoosh API or on google.
I have integrated successfully my application to PushWoosh. For people who knows about PushWoosh you can setup the "environment" to use sandbox or production when sending the push notification.
So when i use Sandbox i can send push notifications to my device. When i choose production nothing comes up( im guessing its because i have not launched the application to the AppStore yet?)
So am i to presume that if it works on SandBox mode, i can now upload it to the appstore and switch to production mode and the push notifications should work when the app is downloadable from the appstore?
When creating the SSL Certificates i used the "Apple Push Notification service SSL (Sandbox & Production)".
Thank you for your answers..

A: You can test your production mode notifications before releasing it to appstore. Apple provides a mechanism for it. You need to build an AdHoc version of your App. If you are not familiar with Adhoc distribution please refer the below link
iPhone: Push Notification Testing on Production Certificate
There is no assurance that push notifications will work in production mode if they are working in sandbox mode, so you cannot presume any assumptions. Adhoc distribution is provided by apple to test production mode notifications. Please go through the below link which provides some helpful information.
https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/TestingYouriOSApp/TestingYouriOSApp.html
Let me know if you have any questions.


text:
Q: TypeError when adding javascript to a Freeboard widget plugin I'm making a widget plugin to display a graph from a RRD file in Freeboard (https://github.com/Freeboard/freeboard).
However, when I add the javascript for handling RRDs in the plugin, I get an exception: "Uncaught TypeError: undefined is not a function".
If I remove the line  "./plugins/thirdparty/freeboard-jsrrd/javascriptrrd-1.1.1/src/lib/javascriptrrd.wlibs.js" in the external_scripts array in the file jsrrd.plugin.js, there is no exception.
What can I do to fix this?
Source: https://bitbucket.org/niclask/freeboard-jsrrd/src
Plugin file: plugins/thirdparty/freeboard-jsrrd/jsrrd.plugin.js
Thanks!

A: The problem was missing javascripts in external_scripts. Once I added the javascripts the graph works.


text:
Q: Is using NSG on AKS advanced networking subnet supported and what are the ports needed to be open between nodes and master? What port for TCP/UDP communication needs to be open between the nodes and the master of azure kubernetes services, when the nodes are in a subnet that uses advanced networking?
For security reasons we have to use a Network Security Group on every subnet that is connected to the onpremises network via VPN in azure. This NSG has to deny every implicit traffic between machines even in the same subnet to hinder attackes from traversing between systems.
So it is the same for the azure kubernetes services with advanced networking, that uses a subnet which is connected via vnet peering.
We couldn't find an answer if it is a supported scenario to have a NSG on the subnet of the aks advanced network and what ports are needed to make it work.
We tried our default NSG which denies inter traffic between host, but this hinders us from connecting to the services and from nodes to come up without errors.

A: AKS is a managed cluster. And the managed cluster master means that you don't need to configure components like a highly available etcd store, but it also means that you can't access the cluster master directly.
When you create an AKS cluster, a cluster master is automatically created and configured. And the Azure platform configures the secure communication between the cluster master and nodes. Interaction with the cluster master occurs through Kubernetes APIs, such as kubectl or the Kubernetes dashboard.
For more details, see Kubernetes core concepts for Azure Kubernetes Service (AKS). If you need to configure the cluster master and other things all by yourself, you can deploy your own Kubernetes cluster using aks-engine.
For the security of your pods, you can use the network policy to improve it. Although it's just a preview version.
Also, it's not recommended to expose the remote connectivity to the AKS cluster nodes if you want to connect to the AKS nodes. The suggestion is that create a bastion host, or jump box, in a management virtual network. Use the bastion host to securely route traffic into your AKS cluster to remote management tasks. For more details, see Securely connect to nodes through a bastion host.
If you have more questions, please let me know. I'm glad to provide more help.


text:
Q: Using the right selector in jQuery to not need to duplicate code I have question regarding selectors in jQuery. If you look at my fiddle. I need to duplicate the same lines of jQuery for it to react to every icon. I'm sure I only need line 1-6 but instead using better selectors. And, if I would need to use the same icon-section 2 times on the same page it would interfere with each other. Does anybody have some advice?

$( ".icon:nth-child(1)" ).click(function() {
    $( ".icon" ).removeClass( "selected" );
    $( ".icon:nth-child(1)" ).toggleClass( "selected" );
    $( ".text" ).fadeOut().delay( 500 );
  $( ".text:nth-child(1)" ).fadeIn();
});
$( ".icon:nth-child(2)" ).click(function() {
    $( ".icon" ).removeClass( "selected" );
    $( ".icon:nth-child(2)" ).toggleClass( "selected" );
  $( ".text" ).fadeOut().delay( 500 );
  $( ".text:nth-child(2)" ).fadeIn();
});
$( ".icon:nth-child(3)" ).click(function() {
    $( ".icon" ).removeClass( "selected" );
    $( ".icon:nth-child(3)" ).toggleClass( "selected" );
  $( ".text" ).fadeOut().delay( 500 );
  $( ".text:nth-child(3)" ).fadeIn();
});
.icons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.icon,
.icon img {
  width: 150px;
  height: 150px;
}

.icon {
  padding: 10px;
}

.icon p {
  text-align: center;
  font-family: arial;
}

.selected {
  border-bottom: 3px solid black;
}

.text {
  font-family: arial;
  padding: 10px;
}

.hidden {
  display: none;
}

            Button 1

            Button 2

            Button 3

                    Text 1 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo tenetur quos quisquam, in totam dolorem enim nostrum nihil impedit ducimus beatae, eos obcaecati ratione voluptatum recusandae incidunt, quas labore doloremque.

                    Text 2 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo tenetur quos quisquam, in totam dolorem enim nostrum nihil impedit ducimus beatae, eos obcaecati ratione voluptatum recusandae incidunt, quas labore doloremque.

                    Text 3 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo tenetur quos quisquam, in totam dolorem enim nostrum nihil impedit ducimus beatae, eos obcaecati ratione voluptatum recusandae incidunt, quas labore doloremque.

jsFiddle - Icontoggle

A: Use $(this)!
$( ".icon" ).click(function() {
    $( this ).toggleClass( "selected" );
});

A: To make this more DRY you can relate the clicked .icon element to the .text by their index(), like this:
$(".icon").click(function() {
  $(".icon").removeClass("selected");
  $(this).toggleClass("selected");
  $(".text").fadeOut().delay(500).eq($(this).index()).fadeIn();
});

Using this method means you don't need to repeat your JS code at all, and can have an infinite number of .icon/.text element.s

$(".icon").click(function() {
  $(".icon").removeClass("selected");
  $(this).toggleClass("selected");
  $(".text").fadeOut().delay(500).eq($(this).index()).fadeIn();
});
.icons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.icon,
.icon img {
  width: 150px;
  height: 150px;
}

.icon {
  padding: 10px;
}

.icon p {
  text-align: center;
  font-family: arial;
}

.selected {
  border-bottom: 3px solid black;
}

.text {
  font-family: arial;
  padding: 10px;
}

.hidden {
  display: none;
}

        Button 1

        Button 2

        Button 3

        Text 1 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo tenetur quos quisquam, in totam dolorem enim nostrum nihil impedit ducimus beatae, eos obcaecati ratione voluptatum recusandae incidunt, quas labore doloremque.

        Text 2 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo tenetur quos quisquam, in totam dolorem enim nostrum nihil impedit ducimus beatae, eos obcaecati ratione voluptatum recusandae incidunt, quas labore doloremque.

        Text 3 - Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo tenetur quos quisquam, in totam dolorem enim nostrum nihil impedit ducimus beatae, eos obcaecati ratione voluptatum recusandae incidunt, quas labore doloremque.

A: You can use jQuery's each() method with indexing:
$( ".icon" ).each(function(index, elem){
    $(elem).on('click', function(){
        $( ".icon" ).removeClass( "selected" ).eq(index).toggleClass( "selected" );
        $( ".text" ).fadeOut().delay( 500 ).eq(index).fadeIn();
    });
});

Live jsBin here.


text:
Q: Using the loop to set locations for all posts on a single google map Firstly, hi all! I am new to worpress stackexchange.
I have been trying to build my own google map to show the location of all my posts. But I don't seem to be able to get the markers to display on the map.
Edit: I have changed the code a bit since my origional post, I am now returning data but with errors.
This is the data being returned:

Dubai

Testing the plugin even more

Sydney

Still testing the plugin

Singapore

Testing Plugin

Abu Dhabi

This is a test of the Maps

And this is the maps.js file:
var infowindow = new google.maps.InfoWindow();
var pinkmarker = new google.maps.MarkerImage('/wp-content/themes/travel-bones/library/images/pink_Marker.png', new google.maps.Size(20, 34) );
var shadow = new google.maps.MarkerImage('/wp-content/themes/travel-bones/library/images/shadow.png', new google.maps.Size(37, 34) );

function initialize() {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: new google.maps.LatLng(38.898748, -77.037684),
        navigationControl: false,
            backgroundColor:'none',
            streetViewControl: false,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    for (var i = 0; i < locations.length; i++) {
        var marker = new google.maps.Marker({
            position: locations[i].latlng,
        icon: pinkmarker,
            shadow: shadow,
        map: map
        });
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            infowindow.setContent(locations[i].info);
        infowindow.open(map, marker);
          }
        })(marker, i));
    }

}

And then this is how I am doing the query in the index.php
<?php if ( have_posts() ) : ?>

                <?php $i = 1; ?>
                <?php while ( have_posts() ) : the_post(); ?>
                    <?php if ( get_geocode_latlng($post->ID) !== '' ) : ?>
                        <div id="item<?php echo $i; ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                            <?php the_content(); ?>

                    <?php endif; ?>
                    <?php $i++; ?>
                <?php endwhile; ?>

        <?php else : ?>

Error 404 — Page not found.

        <?php endif; ?>

The query is obviously working as the results are being returned. However I am getting this error on the maps.js file:
for (var i = 0; i < locations.length; i++) {
Uncaught TypeError: Cannot read property 'length' of undefined

And this error where the queried content shows...
var locations = [

latlng : new google.maps.LatLng(25.271139, 55.30748500000004),
Uncaught ReferenceError: google is not defined
                                       },

This is the tutorial I have been following... code is modified to pull lnt/lng data from a geocoder pulgin.
http://martyspellerberg.com/2012/02/tutorial-integrating-wordpress-and-google-maps-api-v-3/

A: I  have managed to find the problem.
Basically calling the google API from the footer was causing the maps to break and not function properly.


text:
Q: Cannot enable nVidia Quadro M1000M and its proprietary drivers I have installed Ubuntu 16.04 on my Dell Precision 5510 laptop but looks like the graphics driver for its discrete nVidia Quadro M1000M is not installed/configured properly such that it can't playback a couple of 4K videos that I've downloaded at 60Hz. The built-in video player plays them more like 1 frame every 10 seconds or so.
lspci shows the following devices:
$ lspci | grep -E "VGA|3D"
00:02.0 VGA compatible controller: Intel Corporation Device 191d (rev 06)
01:00.0 3D controller: NVIDIA Corporation GM107GLM [Quadro M1000M] (rev a2)

ubuntu-drivers devices shows the following output:
$ sudo ubuntu-drivers devices
[sudo] password for behrangsa:
== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
modalias : pci:v000010DEd000013B1sv00001028sd000006E5bc03sc02i00
model    : GM107GLM [Quadro M1000M]
vendor   : NVIDIA Corporation
driver   : nvidia-361 - distro non-free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

== cpu-microcode.py ==
driver   : intel-microcode - distro non-free

I have also installed the nvidia-361 drivers:

However looks like its kernel module is not getting loaded:
$ ls -1 /lib/modules/4.4.0-22-generic/kernel/drivers/
acpi
ata
atm
auxdisplay
base
bcma
block
bluetooth
char
clk
cpufreq
crypto
dca
dma
edac
extcon
firewire
firmware
fmc
fpga
gpio
gpu
hid
hsi
hv
hwmon
hwtracing
i2c
idle
iio
infiniband
input
iommu
ipack
isdn
leds
lightnvm
macintosh
mailbox
mcb
md
media
memstick
message
mfd
misc
mmc
mtd
net
nfc
ntb
nvdimm
nvme
nvmem
parport
pci
pcmcia
phy
pinctrl
platform
power
powercap
pps
ptp
pwm
rapidio
regulator
remoteproc
rtc
scsi
spi
spmi
ssb
staging
target
thermal
thunderbolt
uio
tty
usb
uwb
vfio
vhost
video
virtio
vme
w1
watchdog
xen

The videos I have downloaded are:

*

*https://www.youtube.com/watch?v=0wCC3aLXdOw

*https://www.youtube.com/watch?v=iNJdPyoqt8U
Is there anything else I need to do in order to enable the full potential of the nVidia graphics card? Also Skylake mobile Xeon CPUs have integrated GPUs that can play 4K video at 60Hz with no problem at all. However as mentioned earlier at the moment I cannot render 4K video flicker-free and it renders more like 0.1 frames per second.


text:
Q: Determine if quadratic diophantine equation in two variables will generate perfect squares I have come across two equations with variables $x,y$
\begin{align*}
(x+ay)^2+ 4 x y\\
(x-y)^2-4 c x y
\end{align*}
where $a,c\in \mathbb{Z}_+$ are some constants.
I would like to determine the values of x,y that generate perfect squares.
I know what to do in the 1 variables situation, but I don't think this is enough: First check to see if it is a perfect square and if it is not go through procedure that has been outlined in previous posts which I will outline real quick again in the next paragraph.
So for the first equation, if we view $y$ as a constant and set equal to $d^2$, can rewrite as
(x+(a+2)y-d)(x+(a+2)y+d)=4(a+1)y^2. Then one can rewrite $4(a+1)y^2= b* \frac{(4(a+1)y^2}{b}$ for some divisor $b$ and solve: $$x=  \frac{b+\frac{(4(a+1)y^2}{b}}{2}-(a+2),\quad d=  \frac{b-\frac{(4(a+1)y^2}{b}}{2} .$$
Questions:
Do I need to do a similar procedure where I treat $x$ as a constant and repeat above for $y$ or would those be already included in the solution set above?
Even then, it just doesn't seem like this would be all the solutions though, as the outline above would implode if one wrote $y=f(x)$, and I can't quite seem to figure out what step I am missing?

A: For the equation.
$$(x+ay)^2+4xy=z^2$$
Write the solution.
$$x=(p+as)p$$
$$y=(s-p)s$$
$$z=as^2+2ps-p^2$$
For the equation.
$$(x-y)^2-4cxy=v^2$$
Write the solution.
$$x=p(p+s)$$
$$y=(p-cs)s$$
$$z=cs^2+2cps-p^2$$

A: For the system of equations .
$$\left\{\begin{aligned}&(x+ay)^2+4xy=z^2\\&(x-y)^2-4cxy=v^2\end{aligned}\right.$$
The solution can be written in this form.
$$x=(c^2+3c+2)(c^2+(2a+3)c+a^2+3a+2)$$
$$y=-(2c+a+3)(c^2+c-a-1)$$
$$z=c^4+2c^3-(6a+5)c^2-(4a^2+18a+14)c-a^3-6a^2-13a-8$$
$$v=3c^4+(4a+14)c^3+(a^2+12a+22)c^2+(a^2+8a+11)c-(a+1)^2$$


text:
Q: To Mount onedrive for business in databricks I am trying to mount a folder in one drive business in databricks community edition. I am unable to use onedrivesdk because it is deprecated.
I created a app registration, assigned read and write permissions to that and using the client id and secret.i tried to mount using api requests but it was not giving the access token.
First of all i want to know , whether it is possible to mount one drive to databricks community edition. if yes, what are the ways..?
Below is the code i used to mount one drive using api requests.

# Import the necessary libraries
import requests

# Set up the client
client_id = ""
client_secret = ""
tenant_id = ""
redirect_uri = "http://localhost:8080/"

# Get the access token
response = requests.post(
    "https://login.microsoftonline.com/{}/oauth2/token".format(tenant_id),
    data={
        "client_id": client_id,
        "client_secret": client_secret,
        "redirect_uri": redirect_uri,
        "grant_type": "client_credentials",
        "resource": "https://graph.microsoft.com"
    }
)
access_token = response.json()["access_token"]

# Mount the OneDrive folder to DBFS
folder_id = ""
mount_point = "/mnt/onedrive"
dbutils.fs.mount(
    source="graph",
    mount_point=mount_point,
    extra_configs={
        "graph.access_token": access_token,
        "graph.folder_id": folder_id
    }
)

A: No, you can't use dbutils.fs.mount with OneDrive - DBFS mounts are supported only for specific cloud storage implementations (S3, ADLS Gen2, Azure Blob Storage, ... - see docs).
If you need to access data in OneDrive, you need to use REST API directly (or find another Python library)


text:
Q: Pulling Data For A List Of URLs Using The Google Analytics Sheets Add-On I've been looking into The Google Analytics Spreadsheet Add-on, however, currently, it pulls the data for the entire account, I want to pull the data only for specific URLs (new blog posts uploaded which will be updated once a month).
I understand I could use something like "ga:pagePath=~^/blog/" however, this would only show the total number of sessions for the "/blog/" section and not for individual posts, ideally, I want the format to be like this:
enter image description here
Is this possible?

A: You may need to work around this manually to aggregate the correct data.
When it comes to seperate posts/pages, use this:
"ga:pagePath=@YourURL" =@ means contains substring.
IF blogs follow naming conventions, you can filter the different levels of pagepaths, using =@, till you find the correct URL.
I always practice building these out before in Google UA Query Builder.
https://ga-dev-tools.web.app/query-explorer/
Here's a screenshot of what I tested to find the results:
Dimensions + Metrics


text:
Q: Output of System.out.println(object) I want to know what exactly the output is when I do the following.
class Data {
  int a = 5;
}

class Main {
  public static void main(String[] args) {
    data dObj = new data();
    System.out.println(dObj);
  }
}

I know it gives something related to object as the output in my case is data@1ae73783. I guess the 1ae73783 is a hex number. I also did some work around and printed
System.out.println(dObj.hashCode());

I got the number 415360643. I got an integer value. I don't know what hashCode() returns, still out of curiosity, when I converted 1ae73783 to decimal, I got 415360643!
That's why I am curious about what exactly is this number. Is this some memory location of Java's sandbox or some other thing?

A: When you print an instance of your class, that does not override the toString method, then the toString method of Object class is used. Which prints an output in the form: -
data@1ae73783

*

*The first part of that output shows the type of the object.

*And the 2nd part is the hexadecimal representation of the hashCode
of your object.
Here's the source code of Object.toString() method, that you can find in the installation directory of your jdk, under src folder: -
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

A: The Javadoc for hashCode() and toString() in the Object class should be able to clarify this for you.

A: That code calls the default toString() implementation of the Object class, that is:
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

A: What happens is that the default toString() method of your class is getting used. This method is defined as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())

The value returned by the default hashCode() method is implementation-specific:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)


text:
Q: Problem with webflow(s) in Grails I've just come across a rather odd problem whilst testing my applications webflows.
I have two seperate webflows that are accessed once a user logs in depending on whether the user is male or female, they begin a process which sends them on a webflow.  One for males, a different one for females.
So to test my app, I login as a male user and enter the flow, thats all fine.. then either by logging out and logging in as a female (or logging in as a female user in a different browser) I then attempt to go through the female process but Bang I get an exception:
Error 500: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Servlet: grails
URI: /ACUREG/grails/applicant/ma.dispatch
Exception Message: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Caused by: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Class: ApplicantController

Now this is strange, as the reverse is also true, If I started first going through as a female, then attempt to try the Male process, the same issue occurs but this time the exception will point to the first event in the male webflow code...
Does anyone know why this may be happening? I did think its perhaps something to do with two webflows in the same controller but after seperating them into their own controllers and still seeing the same issue thats clearly not the case.
Thanks,

A: Just to provide an answer here as much as I can,  I narrowed the problem down to a method I call in the initialisation block where I call a service method that updates the properties of a command object with the values from matching property names from a domain object.
As long as the class names of the command objects are different, then there is no problem but in my case the first page of each of my webflows use the same command object class and for some reason unknown this was causing the exception.  By duplicating this particular command object and renaming one of them so that it was specific to one of the webflows, the problem disappears.
I wish I could have seen a more useful exception and indication of where the problem occurred and I may have saved a day tracking it down.
So in short, if you are using multiple webflows with command objects, be careful as they seem to be 'cached' by name somehow...

A: The problem was down to webflow events having the same name across multiple webflows.  When I renamed the events so they were all different, no more problems.


text:
Q: How to change code signing entitlements in Xcode for Watchkitapp & Extension My app compiles and archives fine, but on upload to the Apple store it fails with the following error message:

Prepared archive for uploading Upload failed  error: App Store Connect
  Operation Error ERROR ITMS-90046: "Invalid Code Signing Entitlements.
  Your application bundle's signature contains code signing entitlements
  that are not supported on iOS. Specifically, value
  'WF3BGN675V.net.brian-fitzgerald.changes' for key
  'application-identifier' in
  'Payload/I-Ching.app/Watch/watchkitapp.app/watchkitapp' is not
  supported. This value should be a string starting with your TEAMID,
  followed by a dot '.', followed by the bundle identifier."

and

error: App
  Store Connect Operation Error ERROR ITMS-90046: "Invalid Code Signing
  Entitlements. Your application bundle's signature contains code
  signing entitlements that are not supported on iOS. Specifically,
  value 'WF3BGN675V.net.brian-fitzgerald.changes' for key
  'application-identifier' in
  'Payload/I-Ching.app/Watch/watchkitapp.app/PlugIns/watchkitapp
  Extension.appex/watchkitapp Extension' is not supported. This value
  should be a string starting with your TEAMID, followed by a dot '.',
  followed by the bundle identifier."

But the string displayed IS my TeamID followed by a dot followed by the bundle identifier!!! Or is it expecting the bundleidentifier for the watchkit? Because if so it's not taking it from the info.plist file for the watchkit app, where it's assigned to net.brian-fitzgerald.changes.watchkitapp

I've spent hours trying varying everything I can in signing authorities and provisioning profiles, fiddling with the bundle id hierarchies, cleaning and rebuilding and recleaning. The only results I get are a failure to build or a successful build with this message.
I've seen many other posts about other ITMS-90046 errors but nothing involving the watchkitapp and extension not reporting the proper team & bundle syntax.
What am I missing?
UPDATE: Following @Help's advice I regenerated my entitlements files by deleting the files themselves, and the paths to them from the project plist.
The problem persists but with a different error message:

And again there's no mismatch between the plist bundle identifier and the identifier in the provisioning profile. My Entitlements-Release.plist is:
    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>WF3BGN675V.net.brian-fitzgerald.changes</string>
    <key>aps-environment</key>
    <string>production</string>
    <key>com.apple.security.application-groups</key>
    <array>
        <string>group.net.brian-fitzgerald.changes</string>
    </array>
</dict>
</plist>

A: Found it. Literally days wasted on this, I hope this saves someone else some pulled hair.
The info.plist is not the only place the Watchkit and Watchkit Extension bundle identities are assigned. There's a bundle identifier key in Build Settings for the watchkit app and watchkit extension targets: no matter what you put in your info.plist, these are the ones that the provisioning profile looks at for a match:

Either those keys are new in Xcode 11 or they were always mis-set in my app. If the latter, I suspect the behaviour described here in the release notes for 11 was the culprit:

Xcode removes some entries from the Info.plist file of a product at
  build time if the entries are not appropriate for the platform being
  built for, which is useful for targets which are configured to build
  for multiple platforms. This behavior can be disabled by setting the
  build setting DISABLE_INFOPLIST_PLATFORM_PROCESSING to YES, in which
  case the target must assume the responsibility of managing these
  entries appropriately. (47797497)

To be clear, I did not set that key, but by setting the bundle identifier in the Watchkit to
net.brian-fitzgerald.changes.watchkitapp

and in the extension to
net.brian-fitzgerald.changes.watchkitapp.watchkitextension

I was able to assign the provisioning profiles with those identities to the targets and build and upload normally.
I have never been so happy to see the big green check mark for a successful upload. I thought my app was toast. If my analysis is correct, I hope Apple documents this one in the next release notes. I can't be the only one who will face this, and the log trail is pure misdirect.


text:
Q: Registering all changes (delete or select) inside a div I realize this question is highly specific but was hoping to get some help with my code. I want to track the contents of a droppable div, where some of the blocks have selects inside of them [TTEST and CHG] and blocks can also be deleted using a button.

I tried adding an event listener but you need to drag in a new block in order for the select to update and deleting a block doesn't trigger the change in agg_output either. Can someone help to make my MutationObserver do what I anticipate it to: Whenever the user drags in a block, changes the block order, deletes a block, OR changes the selected dropdown, the agg_output should reflect that - and deleting a block only sometimes changes the agg_output

$(function() {
  $("#sortable_agg").sortable();
  $("#sortable_agg").disableSelection();
});

// remove the item from the list
$("#d_agg").on('click', '.delete', function() {
  $(this).parent().remove();
});

// get the length every select in the droppable div
// create unique ids for each
function getNewId(type) {
  var newId;
  newId = $('#droppable').find('select').length
  return type + (newId + 1);
}

$(function() {
  $(".blocks").draggable();
  $('#droppable_blocks').droppable({
    accept: ".block",
    drop: function(event, ui) {
      var draggableId = ui.draggable.attr("id");
      var newid = getNewId(draggableId);

      $(this).append(`

        ${newid.replace(/[0-9]/g, '').toUpperCase()}
        <button class="delete">Delete</button>

`)
    }
  }).sortable({
    revert: false
  })
})

$(function() {
  $(".draggable_agg").draggable();
  $("#droppable_agg").droppable({
    accept: ".agg",
    drop: function(event, ui) {
      var draggableId = ui.draggable.attr("id");
      var newid = getNewId(draggableId);
      if (draggableId.includes("ttest")) {
        $(this).append(`

                        T-TEST
                        <select id="${newid}">
                        <option value="week1" selected>Week 1</option>
                        <option value="week2">Week 2</option>
                        <option value="week3">Week 3</option>
                        <option value="week4">Week 4</option></select>
                        <button class="delete">Delete</button>

`)
      } else if (draggableId.includes("chg")) {
        $(this).append(`

                        CHG
                        <select id="${newid}">
                        <option value="week1" selected>Week 1</option>
                        <option value="week2">Week 2</option>
                        <option value="week3">Week 3</option>
                        <option value="week4">Week 4</option></select>
                        <button class="delete">Delete</button>

`)
      } else {
        $(this).append(`

        ${newid.replace(/[0-9]/g, '').toUpperCase()}
        <button class="delete">Delete</button>

`)
      }
    }
  }).sortable({
    revert: false
  })
});

var target = document.querySelector('#droppable_agg')
var observer = new MutationObserver(function(mutations) {
  var str = "";
  $('#droppable_agg label').each(function() {
    const txt = $(this).text()
    const val = $(this).parent().find("select").children("option:selected").val()
    str += "
" + txt + (val ? ": " + val : "") + "
";
  })
  let str_to_table = '
' + str + '
'
  document.getElementById("agg_output").innerHTML = str_to_table;
})

// configuration of the observer:
var config = {
  attributes: true,
  childList: true,
  characterData: true
};
// pass in the target node, as well as the observer options
observer.observe(target, config);

var selected_option = $('#RECIPE').children("option:selected").val()
console.log(selected_option)

$("#RECIPE").bind("change", function(event, ui) {
  var publisher = $("#RECIPE").val();
  if (publisher === "MEAN") {
    document.getElementById("droppable_agg").innerHTML = "";
    $("#droppable_agg").append($("

MEAN<button class='delete'>Delete</button>

FREQ<button class='delete'>Delete</button>

"));
  } else {
    document.getElementById("droppable_agg").innerHTML = "";
  }
});
.wrapper {
  width: 1000px;
  clear: both;
}

.left {
  width: 50px;
  float: left;
  margin-right: 10px;
}

.left-drop {
  width: 400px;
  float: left;
}

.right-drop {
  width: 400px;
  float: left;
}

.right {
  width: 50px;
  float: left;
  margin-left: 10px;
}

#agg_output {
  width: 200px;
  float: left;
  margin-left: 10px;
  color: green;
}

#sortable_agg,
#sortable1,
#blocks,
#block {
  list-style-type: none;
  margin: 0;
  padding-bottom: 2px;
}

.droppable_blocks li {
  padding-top: 3px;
  padding-bottom: 7px;
}

ul {
  list-style: none;
  padding-left: 0;
}

li {
  list-style-type: none;
  padding-bottom: 2px;
}

#sortable_agg li,
#blocks li,
#block li,
.droppable_blocks li {
  border: 1px solid lightgray;
  margin-bottom: 2px;
}

#sortable_agg:hover,
#blocks li:hover {
  cursor: grab;
}

#sortable_agg .ui-sortable-helper:hover,
#blocks .ui-sortable-helper:hover {
  background-color: #ddd;
  border-color: black;
}

#sortable_agg .ui-sortable-helper:hover,
#blocks .ui-sortable-helper:hover {
  cursor: grabbing;
}

.droppable_agg {
  border: 2px dashed #466683;
  padding: 1em;
  min-height: 200px;
}

#droppable_agg.ui-droppable-hover {
  background: #bad4ed;
}

#droppable_blocks.ui-droppable-hover {
  background: #bad4ed;
}

#droppable_agg select {
  margin: 5px;
}

.drop_area {
  border: 1px solid lightgray;
  padding: 3px;
  margin-bottom: 3px;
  width: 100%;
  height: 35px;
}

.delete {
  background: none;
  border: 0px;
  color: #888;
  font-size: 15px;
  width: 60px;
  margin: 0px 0 0;
  font-family: Lato, sans-serif;
  cursor: pointer;
  float: right;
  display: inline-block;
}

button:hover {
  color: #CF2323;
}

<select id="RECIPE">
  <option id="none">NONE</option>
  <option id="mean">MEAN</option>
</select>

    Drop Here

    Stats

T-Test

CHG

Mean

Freq

Again thanks for any help - if useful code is also here
(https://codepen.io/mayagans/pen/RwNeezw)


text:
Q: How is question voting intended on meta? Can Meta really replace UserVoice? On Stack Overflow and Server Fault, question voting (in my opinion) relates to the relevance of a question, as in, "Will anyone else struggle with this? Have I struggled with this?". However, on meta, I feel that it can also mean "Is this a good idea?".
In questions like this one, I think those are at odds with one another as I feel the question is one that others may well want the answer to although the idea is not a good one (in my opinion).
If Meta is to replace User Voice, do we need a second "Good Idea" voting mechanism? Thoughts?
Update
This is intended to discuss voting on Questions as opposed to the answers to questions. It has been proposed that Meta replace UserVoice as the way ideas/bugs etc. are suggested for the SO-family of sites. I feel that unless the question voting is standardised, this may not be feasible.

A: I have approached voting (as far as how to receive upvotes) as this:
If you say something that someone else agrees with or likes, they will upvote (or at least not down vote)
If you say something that someone disagrees with or finds is inappropriate for meta, they will downvote.

A: I was working on the assumption that voting on questions was read as one of:

*

*I'm having this problem too

*I think this would be a good feature to implement

and that voting on answers was basically the same as on SO/SF:

*

*This answer provides useful information

Now whether that's answering a question on how something works, or suggesting a mechanism for implementing a feature is, by and large, immaterial.

A: On questions labeled "feature-request" or that are suggesting a feature, I believe voting should display your interest in the feature. Additionally, an answer can be provided to express any additional thoughts you have on the topic that might be meaningful to others considering the feature.
For most other questions (how does feature x work? is this a bug? why did this happen?), I would treat voting similar to how you stated voting on SO and SF. Is the question well stated? Is it potentially helpful to others? etc.

A: I think Meta is good and necessary to answer questions that concern the Stackoverflow-Trilogy of Q&A Systems. But this is no replacement for UserVoice:

*

*There is no way to indicate just how bad you want a feature except posting obnoxious "I want that feature too" answers / comments, since you have only one vote.

*The worst problem: People tend to post "Mee too" answers instead
of voting a feature-request question up, or vote on the answers
instead of the question. (See, for instance, this question.)
For example, there can be many upvotes on a particular answer that
descripes a feature, but almost no upvotes on the question that
poses the problem. So the votes on the feature-request question do
not carry much meaning.

*It might become clear to frequent users when a vote means "I want
that feature" and when it just means "Well said", but it is not clear
to casual users. On UserVoice it was clear.

*There is no clear way to distinguish between actual questions, feature-requests and bug-reports. (That might change, though, if the Meta FAQ would define
tags "bug" and "feature-request" for this purposes.)
Conclusion: I think it would be better to keep UserVoice, or it would
be necessary to introduce a second voting mechanism like the one on
UserVoice.

A: I think Meta SO is much better than User Voice. I had asked for comments to allow some simple markdown on User Voice, and nothing ever came of it. The same thing was asked for on Meta SO, and it got implemented in less than a week.

A: Depends on the question. Some of them are a call for suggestions where we vote on our favorites. Some of them are questions about how SO works where we can actually answer, so you vote on the one that best answers the question (Jeff usually wins). Some of them are suggestions where we discuss what the heck should be done and we vote on the best argument.
This is an answer.
P.S.-All links at random from the top of the front page...so as you can see, there are plenty of all of them.

A: I vote based on whether I like your avatar.


text:
Q: Why a customization returns the same instance when applied on two different properties? I'm encountering this strange behavior on AutoFixture 3.50.7 and 4.0 (Nunit 3.7) :
When I generate an object containing two properties of the same type using the vanilla Fixture object, the test passes.
When I apply this (admittedly dummy) customization, the test fails. The generated lists are in fact the same instance.
What is happening ?
[TestFixture]
public class Test
{
    [Test]
    public void Succeeds()
    {
        var fixture = new Fixture();

        var container = fixture.Create<Container>();

        ReferenceEquals(container.Content1.Strings, container.Content2.Strings).Should().BeFalse();
    }

    [Test]
    public void Fails()
    {
        var fixture = new Fixture().Customize(new TestContentCustomization());

        var container = fixture.Create<Container>();

        ReferenceEquals(container.Content1.Strings, container.Content2.Strings).Should().BeFalse();
    }
}

public class TestContentCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customize<Content>(c => c
            .With(x => x.Strings, new List<string>()));
    }
}

public class Container
{
    public Content Content1 { get; set; }
    public Content Content2 { get; set; }
}

public class Content
{
    public IList<string> Strings { get; set; }
}

The test also fails if I ask AutoFixture to generate fixture.CreateMany<string>(3).ToList() instead of new List<string>() but of course, this time the list contains 3 different strings.

A: The Customize<T> API may be confusing, which is all my fault, but the delegates inside only run once, when you're done defining the customization. I understand why using delegates looks like deferred execution, but it isn't; it's a DSL. This sometimes causes confusion, which is an indication that it should have been designed differently, but now, ten years later, this is the API we have.
The customization in the OP is equivalent to doing this:
public void Customize(IFixture fixture)
{
    var strings = new List<string>();
    fixture.Customize<Content>(c => c
        .With(x => x.Strings, strings));
}

The Customize(IFixture) method only runs once per fixture. Notice that the arguments to With are made up of a lambda expression, and an object. The second argument is just an object, and since C# is eagerly evaluated, even if you put a method call there, that method call evaluates before With is called.
What this customization does, then, is to create an empty list of strings (or, if you use CreateMany, a populated list of strings), and register Content such that, every time a Content object is created, its Strings property is assigned that particular object.
To work around the problem, you could do something like this:
public void Customize(IFixture fixture)
{
    fixture.Customize<Content>(c => c
        .Without(x => x.Strings)
        .Do(x =>
        {
            x.Strings = fixture.CreateMany<string>().ToList();
        }));
}

The Do method gives you true deferred execution, but (IIRC) the order in which it executes isn't strictly defined, so you should also use .Without(x => x.Strings) to ensure that AutoFixture doesn't overwrite the effects of the Do block.
This passes both tests.
All that said, you should avoid writable collection properties:

DO NOT provide settable collection properties.

If you follow the official Microsoft design guidelines, AutoFixture tends to work better for you.


text:
Q: Add the "one question per post" rule to the Help center I just asked a user to separate his two (otherwise good) questions (real-world use) into two separate questions (stack-exchange use). That is, he was doing a single task, and was wondering about two different aspects of it.
This rule can seem arbitrary to users, for whom it is natural to ask for all the help they need with a single task in a single "package". So I am always careful to explain some of the reasoning behind it when I do it. This explaining has some downsides: 1) it takes time, 2) it doesn't look as "official" when it is just a comment, 3) users couldn't have known about it even if they wanted.
My suggestion is to expand the text in https://cooking.stackexchange.com/help/how-to-ask with a heading of "only one problem per question" and explain a bit of the background. This is a low-friction solution (adding some more relevant text to an existing help page), can be linked when needed, and addresses the other concerns too.

A: From what I have seen different sites have different tolerance levels to the asking of multiple questions in a question so a network-wide change to the help may not be desired by all communities, irrespective of whether I think it should be (which I do).
As an alternative to placing this information on the help/how-to-ask page which is not accessible for moderators to edit, you could do as we do at GIS Stack Exchange and:

*

*use the help/on-topic page (which is accessible for moderators to edit) to provide a link to a How to frame a good question? Q&A where the most upvoted and accepted answer mentions near its start:

the all important single question [you could embellish this to say much more.]

*reinforce it with Tour wording (which moderators can also edit) of:

Your most important question is important to us
Asking one, and only one, important question within your Question
  helps attract prompt and clear Answers.
Your other questions are just as easy to research/ask separately!

I actually think having this in the Tour is what really says that "one question per question" is one of the first things that we want new users to learn about focussed Q&A.


text:
Q: the print of getAbsolutePath in Java My development environment: Mac + IntelliJ Idea.
I'm practicing the File class in Java.
public class FileDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("/Users/Samuel/IdeaProjects/JavaFundamentals/src/aa/bb/test.txt");
        file.createNewFile();
        System.out.println(file.getAbsolutePath());
    }

}

the result is /Users/Samuel/IdeaProjects/JavaFundamentals/src/aa/bb/test.txt
It's OK.But after I changed the path,the print became strange.
public class FileDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("test.txt"); //notice this line
        file.createNewFile();
        System.out.println(file.getAbsolutePath());
    }

}

the print is /Users/Samuel/IdeaProjects/test.txt
I'm confused of the path.

A: Because "test.txt" is a relative path and the file will be created relative to the program's working directory (in this case /Users/Samuel/IdeaProjects/).

A: In the first case you have provided the full path in your initialization. So it is printing the full path. In the second case, you are using relative paths. The base path for that is home directory of your project.

A: 1) When you provide the full path in File class constructor while creating the File object then it will create the file on mentioned path.
2) But In case you are not providing the full path then it will create the File on the same path where your .class file is. It is relative path.

A: Your project folder is the main folder for the File class. This is where the File class starts from. If you want a lower folder you need te specify your path or you can use: "new File("../");
The main reason why it is in the folder "IdealProjects" is, because this is the start path of your project.


text:
Q: Add control variable to $_REQUEST in wordpress, php I would like to pass a variable between pages. This is a control variable for the whole site, lets call it season. This variable has a default value of the current season(custom variable in admin), and can be changed through a link. ( Some archive like url: ...?season=1)
I would like this to be carried throughout the site, if set. So for example the link to page 1 would change from ...?pageid=1 to ...?pageid=1&season=1 . For all the links. Basically I whant this season to be the control variable on what content I display in each page.
How can this be done most simply in wordpress?
I also tried cookies and session, but had no success (to store this variable). What is the correct code in doing something like "Whatever the next page will be, pass this variable to it, so it will be readable in $_REQUEST"?
Thanks,
Sziro
Edit:
<?php
function get_season_ID()
{
    if (array_key_exists('cat', $_REQUEST))
    {
        $c= $_REQUEST['cat'];
        //I whant to pass $c to the next page whatever that is.
        return $_REQUEST['cat'];
    }
    else
    {
        return get_custom('current_season_category_id');
    }
}
?>

A: Why do you need the variable to be available in the $_REQUEST?
If you're setting the variable in the admin, I assume that means you're saving it in the wp_options table. If it's saved in the wp_options table, you can retrieve it using get_option('season').


text:
Q: How do I put my packages into Dropbox I don't want to necessarily put my packages in Mathematica's $UserBaseDirectory, which is on my local hard drive.  Can I somehow tell Mathematica to look for packages in other directories (like DropBox)?
Basically, I have two computers running Mathematica -- one at home, and one at work, and would like to be able to work on editing/running my packages on both computers.

A: Another solution would be to create a symbolic link if you are working on Linux or Mac OS X. I don't know how to do this in windows. In any case, for this example I put the MATLink package in my dropbox folder. The location is the following:
/Users/jmlopez/dropbox/MATLink

To be able to use I need to put a shortcut to it
macbook-pro:~ jmlopez$ ln -s /Users/jmlopez/dropbox/MATLink /Users/jmlopez/Library/Mathematica/Applications/MATLink

Now I have two ways of accessing MATLink, One from the Dropbox folder and one from the hidden directory $UserBaseDirectory. Notice the dropbox icon.

I only provided this answer since I did not see anyone commenting on it. My preference would also be to modify the Kernel/init.m file in the $UserBaseDirectory as I would modify my bashrc file.

A: The easiest way is to modify $Path to include the directory you placed your packages into. Suppose your packages directory is in the Dropbox\Documents\myPackages folder inside your home directory; then you can add it to your path like this:
AppendTo[$Path, ToFileName[{$HomeDirectory, "Dropbox", "Documents", "myPackages"}]]

(EDIT: amended according to advice by Steve Luttrell)
To make this change permanent, you can add this line to your init.m file.
Each system (home and work PC) will have a custom line of this sort in its init.m file that will tell Mathematica where to look for your packages.
Please note that since you are appending the new directory at the end of the path, system directories will have the precedence over custom ones. Just in case you decide to have the same names for different packages.
If you want your packages to have the precedence, you have to change the order your directory appears in your $Path either by prepending it or by placing it at a custom position.
And now, for something extreme...
If you really want to have Mathematica look elsewhere for all its files, you might want to fiddle with $UserBaseDirectory . I have no experience with that, but the documentation says that "the value of $UserBaseDirectory can be specified by setting the operating system environment variable MATHEMATICA_USERBASE when the Mathematica kernel is launched. It cannot be reset from inside the kernel". I guess that by copying the actual userbase directory to your new Dropbox location and then by specifying MATHEMATICA_USERBASE accordingly in your OS environmental variables, you can get Mathematica to work directly with files in the Dropbox folder. But this is something you can do only on machines where you are an administrator, and it looks kinda risky...

A: I assume this would also serve the purpose?
Get[FindFile["Dropbox\\yourpackage.m"]]


text:
Q: Search Lucene Index I am using Lucene.Net Version 2.3.2.1. When I call index() method, it will index the document in C:\Index. But when i call SearchLucene() method, nothing is coming out.
Here is my index() and SearchLucene() methods :
public void Index(string strHash, string filePath, string encryptedPath, string password, string fileName)
{
    string indexFileLocation = @"C:\Index";
    Lucene.Net.Store.Directory dir =
        Lucene.Net.Store.FSDirectory.GetDirectory(indexFileLocation, false);

    //create an analyzer to process the text
    Lucene.Net.Analysis.Analyzer analyzer = new
    Lucene.Net.Analysis.Standard.StandardAnalyzer();

    //create the index writer with the directory and analyzer defined.
    Lucene.Net.Index.IndexWriter indexWriter = new
    Lucene.Net.Index.IndexWriter(dir, analyzer);/*true to create a new index*/

    //create a document, add in a single field
    Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();

    doc.Add(new Field("keywordHash", strHash, Field.Store.YES, Field.Index.TOKENIZED));
    doc.Add(new Field("keywordPath", filePath, Field.Store.YES, Field.Index.NO));
    doc.Add(new Field("keywordEncPath", encryptedPath, Field.Store.YES, Field.Index.TOKENIZED));
    doc.Add(new Field("keywordPassword", password, Field.Store.YES, Field.Index.TOKENIZED));
    //doc.Add(new Field("keywordEncryptedFile", encryptedFile, Field.Store.YES, Field.Index.ANALYZED));
    doc.Add(new Field("keywordFileName", fileName, Field.Store.YES, Field.Index.NO));

    //write the document to the index
    indexWriter.AddDocument(doc);

    //optimize and close the writer
    indexWriter.Optimize();
    indexWriter.Close();

}

public void LuceneSearch()
{
    HashAlg hashAlg = new HashAlg();
    string keywordLower = tbSearchEnc.Text.ToLower();
    string keywordHash;

    if (rbMD5Search.Checked == true)
    {
        keywordHash = hashAlg.GenerateHashMD5(keywordLower);
    }
    else
    {
        keywordHash = hashAlg.GenerateHashSHA1(keywordLower);
    }

    string indexFileLocation = @"C:\Index";
    //Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.GetDirectory(indexFileLocation, false);
    //Lucene.Net.Analysis.Analyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer();
    Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(indexFileLocation);
    //create an index searcher that will perform the search
    //Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir);

    //build a query object
    //Query query = new TermQuery(new Term("keywordHash", keywordHash));
    Lucene.Net.Index.Term searchTerm = new Lucene.Net.Index.Term("keywordHash", keywordHash);
    Lucene.Net.Search.Query query = new Lucene.Net.Search.TermQuery(searchTerm);

    //execute the query
    Lucene.Net.Search.Hits hits = searcher.Search(query);
    int result = hits.Length();
    //iterate over the results.
    for (int i = 0; i < result; i++)
    {
        Document doc = hits.Doc(i);
        string hashValue = doc.Get("keywordHash");
        Console.WriteLine(hashValue);
        string path = doc.Get("keywordPath");
        Console.WriteLine(path);
        string encPath = doc.Get("keywordEncPath");
        Console.WriteLine(encPath);
        string fileName = doc.Get("keywordFileName");
        Console.WriteLine(fileName);

        listBoxSearch.Items.Add(encPath);
        Console.WriteLine(hashValue + " " + path + " " + encPath + " " + fileName);

    }
}

A: I think you need to call IndexWriter.Commit(), and you probably shouldn't bother with the Optimize() method unless you have some special requirement.


text:
Q: Cassandra - How to check table data is consistent at a given point in time? How to find out when a Cassandra table becomes "eventually consistent"? Is there a definitive way to determine this at a given point in time? Preferably programatically through the Datastax driver API? I checked out the responses to the following related questions but there does not seem to be anything more concrete than "check the nodetool netstats output"

*

*Methods to Verify Cassandra Node Sync

*how do i know if nodetool repair is finished

A: If your system is always online doing operations then it may never become full consistent at single point of time untill you are on Consistency level "ALL".
Repairs process logs error in log file if it does not get reply from other replica nodes cause they were down/timeout etc.
you can check the logs if no error WRT AntiEntropy/stream it means your system is almost consistence.


text:
Q: Scrape a web and get a value that changes with a javascript funtion I'm trying to log in and scrape a value from this page: https://adf.ly, specifically the amount of views my links have. I have achieved to login and get to the page where the value I want appears, but the problem is that this value isn't loaded with the page, it is loaded later using a javascript function. The code I have used is the following one:
 <?php
    function getViewsAdfly(){
        $cookiePath = './cookieAnuncios.txt';
        $url = "https://login.adf.ly/login";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept-Language: es-es,en"));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiePath);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiePath);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);

        $token = urlencode(getMatchToken($result));
        $email = urlencode("my email");
        $password = urlencode("my password");
        $parametrosPost = "token=" . $token . "&bmlUrl=&bmlType=&bmlDomain=&bmlFolder=&dest=&response=&challenge=&email=" . $email . "&password=" . $password;

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $parametrosPost);
        curl_exec($ch);

        $urlViews = "https://adf. ly/publisher";

        curl_setopt($ch, CURLOPT_URL, $urlViews);
        curl_setopt($ch, CURLOPT_POST, 0);
        $resultViews = curl_exec($ch);
        curl_close($ch);

        return getMatchViewsAdfly($resultViews);
    }

    function getMatchToken($result){
        preg_match_all("(<input type=\"hidden\" name=\"token\" id=\"token\" value=\"(.*)\" />)siU", $result, $matchesToken, PREG_PATTERN_ORDER);
        return $matchesToken[1][0];
    }

    function getMatchViewsAdfly($result){
        preg_match_all("(
(.*)
)siU", $result, $matchesViews, PREG_PATTERN_ORDER);
        return $matchesViews[1][0];
    }
 ?>

If I use this code, the page shows a message saying "There has been a problem while fetching the stats. Please refresh the page and try again." and the

 which contains the data I want to scrape only shows "loading...". I think that the javascript method which charges the real number on the  cointainer isn't running correctly. Do I have to add any curl setopt which is missing so that the javascript runs? How can I manage to get the real data I want to scrape after it gets loaded on the container?
EDIT:
The javascript saves the data on s[0]. Any way I can get what is stored there?
$(document).ready(function() {
                $('#edit_link').dialog({
                    autoOpen: false,
                    height: AdFly.awesomeBrowser() ? 420 : 450,
                    width: AdFly.awesomeBrowser() ? 550 : 580,
                    modal: true,
                    closeOnEscape: false,
                    resizable: false
                });

                $('#edit_advert_type').chosen();

                $('#charts-tabs, #links-tabs').easytabs({animate: false, updateHash: false, tabs: "nav > ul > li"});

                $('#charts-tabs')
                        .bind('easytabs:after', function (event, $clicked, $targetPanel, settings) {
                            PublisherIndex.updateCountries();
                            $('ul.earnings').addClass('displayNone');
                            if($targetPanel.selector == '#charts-tab-4'){
                                $('ul.earnings.popads').removeClass('displayNone');
                            }else{
                                $('ul.earnings.simplelinks').removeClass('displayNone');
                            }
                        });

                $('#report_date').chosen();
                $('#report_date').change(function() {
                    $('.timePicker').removeClass('current');
                    $(this).parent().addClass('current');
                    PublisherIndex.renderStats();
                    PublisherIndex.updateLinks();
                });

                $('.timePicker').click(function() {
                            if ($(this).parent().attr('class') == 'all_time') {
                        alert("Sorry all time stats are currently disabled.");
                        return;
                    }

                    $('.timePicker').removeClass('current');
                    $('#report_date').parent().removeClass('current');
                    $(this).addClass('current');
                    PublisherIndex.renderStats();
                    PublisherIndex.updateLinks();
                    PublisherIndex.renderSummary();
                    return false;
                });

                $('#findlink').keypress(function(event) {
                    var keycode = (event.keyCode ? event.keyCode : event.which);
                    if (keycode == '13') {
                        PublisherIndex.updateLinks();
                        $('#search_clear').show();
                    }
                });

                $('#links-tabs').bind('easytabs:after', function(event, $clicked, $targetPanel, settings) {
                    PublisherIndex.updateLinks();
                });

                PublisherIndex.getAnnouncements();
                //PublisherIndex.renderSummary();
                PublisherIndex.renderStats();
                PublisherIndex.renderLinks();

                $('.monthlyEarningsSummarySelector').click(function() {
                    $('.monthlyEarningsSummarySelector').removeClass('current');
                    $(this).addClass('current');
                    PublisherIndex.renderStats();
                    PublisherIndex.renderSummary();
                    return false;
                });
            });

            $(document).ready(function() {
                // Little hack for getting the URL Groups.
                $('#edit_group').html($('section.shorten select[name="group"]').html());
                $('#edit_group').chosen();
            });

            var PublisherIndex = {
                countriesDt: null,
                countriesLength: null,
                referralsDt: null,
                earningsChart: null,
                graphData: null,
                popupsChart: null,
                popupGraphData: null,
                earningsSummary: null,
                tokenCSRF: null,
                linkId: null,
                updateCountries: function() {
                    var oTable = $('#charts-tab-2').find('table').dataTable();
                    var table_height = 419;
                    var num_rows = this.countriesLength;
                    var row_height = $('section.dashboard section.charts table tr').outerHeight();
                    if(num_rows<10){
                        num_rows = 10;
                    }else if(num_rows>20){
                        num_rows=20;
                    }
                    var required_height = parseInt(table_height) + (parseInt(num_rows)-10)*parseInt(row_height);
                    $('section.dashboard section.charts nav.menu').css('height', parseInt(required_height));
                    $('section.dashboard section.charts .data .panels').css('height', parseInt(required_height)+8);
                    var oSettings = oTable.fnSettings();
                    oSettings._iDisplayLength = num_rows;
                    oTable.fnDraw();
                },
                getAnnouncements: function() {
                    ApiCaller.getAnnouncements(AdFly.USER_TYPE.PUBLISHER, $('#announcements'), false);
                },
                renderSummary: function() {
                    $('ul.earnings:not(.totals)').css('visibility','visible');
                    $t = $('.timePicker.current, #reportDateWrapper.current');
                    var key = null;
                    var copy = null;
                    key = $("#report_date").val();
                    var i = 1;
                    copy = $('.chzn-container-single .chzn-single span').eq(3).text();
                    copy = copy.substring(0, copy.length - 5);
                    var views = 0;
                    var earnings = 0;
                    var referrals = 0;
                    var total = 0;
                    $.each(this.graph.data,function(i,day){
                        views+=parseFloat(day.views);
                        earnings+=parseFloat(day.earnings);
                    });
                }
            }

Thank you in advance.

A: Curl doesn't execute JS. You have two options:

*

*Use some technique which executes the JS. That's hard in PHP and you should not try it. (If you want to do it, then you'll need a JS engine in PHP, like V8). Try to use instead PhantomJS. You could create a web-service which runs the JS code server-side (Node.js) and fetch then the data with PHP via an API.

*Get the data the same way as the JS functions gets it. There are only two options:

*

*The data is being loaded after the page was delivered. Then they must use a HTTP request. Find this request and imitate it.

*The data is written down somewhere on the delivered page, but has not yet been shown. Maybe it's stored in a JS variable, which the function calls. (I mean JS code which has been constructed server-side and includes the variable already)
Good luck!


text:
Q: three js projection problems I have a very strange problem.
I create a scene with three js and i want to project a cylinder vertex on floor of the scene and build path of it. So, when i add a cylinder, move and rotate him and then project his on a floor, the vertex, what i clone of the cylinder located at the old place, before tranforms.
Where is my mistake?
function drawCircle(r,seg,color,pos,mesh){

var geometry = new THREE.CylinderGeometry(r,r,100,seg);

var material = new THREE.MeshBasicMaterial( { color: color, wireframe: true, transparent: true } );
mesh2 = new THREE.Mesh( geometry, material );
mesh2.position = pos;
mesh2.rotation.x = Math.PI/2;
scene.add(mesh2);

var lineGeometry = new THREE.Geometry();

for (var i=0; i < (mesh2.geometry.vertices.length/2)-1; i++)
{
    var origin = mesh2.geometry.vertices[i].clone();
    var proj   = projectOntoMesh( origin, mesh );
    lineGeometry.vertices.push( proj );
}

lineGeometry.computeLineDistances();
var lineMaterial = new THREE.LineBasicMaterial( { color: color } );
var line = new THREE.Line( lineGeometry, lineMaterial );
scene.add(line);
scene.remove(mesh2);
//scene.remove(sphere);
}

function projectOntoMesh(point, mesh)

{

var origin = point.clone();
var direction = point.clone();
//direction.multiplyScalar(-1);
direction.y = -direction.y*25;
//direction.x = -direction.x;

//var direction = point.clone().multiplyScalar(-1);
var ray = new THREE.Raycaster( origin, direction.normalize() );
var intersection = ray.intersectObject( mesh );
if ( intersection.length > 0 )
    return intersection[ 0 ].point;
else
// console.log( "No intersection?" );
    return null;
}

Sorry for my English...


text:
Q: Copy image file from server to disk in PHP I have a js script that saves an image as .jpg in a specific folder on the server:
$data = substr($_POST['imageData'], strpos($_POST['imageData'], ",") + 1);
$decodedData = base64_decode($data);
$fp = fopen("imgdownload/cc.jpg", 'wb');
fwrite($fp, $decodedData);
fclose($fp);

The next step would be for the user to save it on his/her disk, the best would be to open a dialog box "save as" and choose the name and location, but just forcing download to a set location would be a dream.
I've tried:
$file = 'imgdownload/cc.jpg';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: image/jpg');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

And other things without success. What am I doing wrong and how to do it right?
EDIT - this is my JS:
savePicture: function() {
    $(this.el).find('canvas').attr('id', 'myCanvas');
    var data = document.getElementById("myCanvas").toDataURL();
    $.post("api/process.php", {
        imageData: data
    }, function(data) {
        //window.location = data;
    });
},

A: You cannot trigger a download in response to a background AJAX request. You'll have to direct the main browser to the URL where the download occurs. E.g., in your AJAX callback:
window.location = '/download.php';

That means you'll need to store the file server-side in the AJAX upload request to then have it available for download in the separate following request to download.php somewhere.