text:
Q: ggplot2 - geom_line of cumulative counts of factor levels I want to plot the cumulative counts of level OK of factor X (*), over time (column Date). I am not sure what is the best strategy, whether or not I should create a new data frame with a summary column, or if there is a ggplot2 way of doing this.
Sample data
DF <- data.frame(
  Date = as.Date(c("2018-01-01", "2018-01-01", "2018-02-01", "2018-03-01", "2018-03-01", "2018-04-01") ),
  X = factor(rep("OK", 6), levels = c("OK", "NOK")),
  Group = factor(c(rep("A", 4), "B", "B"))
)
DF <- rbind(DF, list(as.Date("2018-02-01"), factor("NOK"), "A"))

From similar questions I tried this:
ggplot(DF, aes(Date, col = Group)) + geom_line(stat='bin')

Using stat='count' (as the answer to this question) is even worse:
ggplot(DF, aes(Date, col = Group)) + geom_line(stat='count')

which shows the counts for factor levels (*), but not the accumulation over time.
Desperate measure - count with table
I tried creating a new data frame with counts using table like this:
cum <- as.data.frame(table(DF$Date, DF$Group))
ggplot(cum, aes(Var1, cumsum(Freq), col = Var2, group = Var2)) +
  geom_line()

Is there a way to do this with ggplot2? Do I need to create a new column with cumsum? If so, how should I cumsum the factor levels, by date?
(*) Obs: I could just filter the data frame to use only the intended levels with DF[X == "OK"], but I am sure someone can find a smarter solution.

A: One option using dplyr and ggplot2 can be as:
library(dplyr)
library(ggplot2)

DF %>% group_by(Group) %>%
       arrange(Date) %>%
       mutate(Value = cumsum(X=="OK")) %>%
      ggplot(aes(Date, y=Value, group = Group, col = Group)) + geom_line()


text:
Q: Redirect non .onion to https but keep .onion as http? I am adding a .onion address to my site and need to redirect regular traffic to https and .onion traffic to keep as http. I've got:
if ($scheme != "https") {
  if ($host !~* "\.onion$") { # error occurs here
    return 301 https://$host$request_uri;
  }
}

I get the following error:
nginx: [emerg] "if" directive is not allowed here in nginx.conf:22

redpajama_set_name: RedPajamaStackExchange


text:
Q: Don't know how to manage in laravel this database reality I have this tables:
 *admins*      *places*       *grants*
 id_admin      id_place       id_grant

Each Admin has 0-N Place. Each Place has 0-N Grant. So we have:
*admin_place*   *grant_place*
 id_admin        id_place
 id_place        id_grant
                 id_grant_place(this one has an autoincremental id)

Now what I want to do is that, each Admin could have 0-N of those grant_place. So I have a table:
*admin_grant_place*
 id_admin
 id_grant_place

How do I express this in my Laravel app?
Thank you,

A: Your question is not very clear but a good readthrough of the Eloquent relationships documentation should have you moving in the right direction
Read this https://laravel.com/docs/5.2/eloquent-relationships


text:
Q: XNA new Texture2D retains old data I have an odd problem that I believe my relative lack of knowledge of the XNA framework prohibits me from fixing.
Basically I have a Texture2D reference that is set to a new instance of Texture2D. During runtime some of its pixels are set and this all works nicely as its drawn in the gameloop.
The odd thing is, if I set the reference to null, (it will only draw if not null) it as expected does not draw.
Later on, I set the reference to a new Texture2D and it starts drawing it to screen. The issue is it holds all the data of the original Texture2D object.
EDIT
Sorry I wasnt clear before.
What I have is something like this...
private Texture2D WorkingTexture {get; set; }

private void Update()
{
 if(some input)
 {
  this.WorkingTexture = null;
 }

 if(some other input)
 {
  this.WorkingTexture = new Texture2D(this.GraphicsDevice, 500, 500, true, SurfaceFormat.Color);

  this.WorkingTexture.SetData<Color>(0, new Rectangle((int)vector2.X, (int)vector2.Y, 4, 4), colors, 0, 16);

  }
}

private void Draw()
{
 if (this.WorkingTexture != null)
 {
    spritebatch.draw(this.WorkingTexture,.....);
 }
}

SECOND EDIT
I have also set a for loop and manually set every pixel of the texture to a color after it is created. this works yet it still shows pixels as the colors i set them previously. This is very odd.

Please disregard this thread. The issue was very embarrassingly my own doing. I had some code that buffered up pixels to be changed and yes... you guessed it I wasn't clearing it and it was doing the work all over again on the new texture instance.
very embarrassed....

A: Without having much detail to go on, it sounds like you are trying to load the Texture2D with the changes that you made earlier.  Since you set it to null, when you reload the Texture2D, it will be back to the original.  You'll need to save the changes you make to the pixels for later use if you want to use it again.  Hope this helps!

A: So you've set up a texture like this
Texture2D texture = Content.Load<Texture2D>("texture_name");

and then you apply a new reference it like so
texture = Content.Load<Texture2D>("other_texture_name");

right?
Thats not how it's supposed to be. You have to set up your GraphicsDevice to use a specific Texture. With the BasicEffect class, this would be something like this:
BasicEffect effect = new BasicEffect(GraphicsDevice);
effect.Texture = texture;
effect.CurrentTechnique.Passes[0].Apply();

A: How do you create the textures? If you load them from a resource (texture = Content.Load("texture_name")) the problem you describe sounds like a bug in your logic: your program is not doing what you think it's doing. Trace, debug...
If you're creating brand new textures (texture = new Texture2D(...)) it's possible (not verified) that the new texture is not initialized and its memory space is being retrieved from some kind of memory pool, so retrieving the recently marked to dispose texture data. Try to initialize your texture data as soon as you create it setting it to all-black, for example.


text:
Q: Excel VBA: Check all check boxes on Web Page I'm trying to check all the checkboxes available on a webpage via VBA since the name convention doesnt appear to be one in which I can be selective.  However I cannot seem to get anything to work. I can login to the website and navigate to the section of the website I want but cannot cross this hurdle.  Any help would be greatly appreciate.  Below is the source code from the webpage.

        <input type="checkbox"
            value="154232"
            class="product-Conventional product-item"
            data-authorized-remittance-types="ActualActual "
            />30-Year Fixed Rate - 110k Max Loan Amount

VBA I attempted to write (edited)... code I'm using presently:
Public Sub TestIE()
Dim IE As Object
Dim aNodeList As Object, i As Long

' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")

' You can uncoment Next line To see form results
IE.Visible = False

' Send the form data To URL As POST binary request
IE.Navigate "https://"

' Statusbar
Application.StatusBar = "Page is loading. Please wait..."

' Wait while IE loading...
Do While IE.Busy
    Application.Wait DateAdd("s", 1, Now)
Loop

IE.Visible = True

Set aNodeList = IE.document.querySelectorAll("input[type=checkbox]")
If aNodeList Is Nothing Then Exit Sub
For i = 0 To aNodeList.Length
aNodeList.Item(i).Checked = True
Next i
End Sub

A: You can try to get a nodeList of the checkboxes with:
IE.document.querySelectorAll("input[type=checkbox]")

You can traverse the nodeList along its .Length property.
E.g.
Dim aNodeList As Object, i As Long
Set aNodeList = IE.document.querySelectorAll("input[type=checkbox]")
If aNodeList Is Nothing Then Exit Sub
For i = 0 To aNodeList.Length -1
    On Error Resume Next
    aNodeList.item(i).Checked  = True
    On Error GoTo 0
Next i


text:
Q: tSQLt - How does AssertEqualsTable work? tSQLt has a command called AssertEqualsTable that tests whether contents of 2 tables match.
I would like to understand how the logic works, does it use the first column as a JOIN between the 2 tables, to then test whether the rest of the columns for that row (join) match?

A: AssertEqualsTable compares the whole row - i.e. all columns.  For example if the expected table has one row of four columns ('A', 'B', 'C', 'D') and actual also has one row ('A', 'B', 'C', 'E'), the result returned by AssertEqualsTable will show two rows - the ABCD row expected not found plus the ABCE row returned but NOT expected.
There is is no guarantee that the expected and actual tables in every single test that anyone might want to write would even have a unique key so the comparison has to be based on the whole row.


text:
Q: fetching from twitter Api Please i need help on how to fetch data from twitter api for a week.
i'm using nodeJs to write the code and it doesn't seem to work well.
I'm using the twit module in nodeJs btw.
var today = new Date();
 var day = today.getDate();
 var month = today.getMonth() + 1; //January is 0!
 var year = today.getFullYear();

let months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

 for (let i = 0; i < 7; i++) {
     if (day > 0) {
         day--;
     }
     if (day == 0) {
         month = month - 1;
         day = months[month - 1];
     }
     console.log(day, month, year);
 }
    let params = {
                   q: `to:${firstBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
                   count: 5000,
                   language: 'en',
                   entities: false
               };
               let param = {
                   q: `to:${secondBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
                   count: 5000,
                   language: 'en',
                   entities: false
               };

               t.get('search/tweets', params, dataGotten);

A: Assuming all your setup is done correctly:
const Twit = require('twit')

const T = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
});

I would try this:
t.get('search/tweets', params, function(err, data) {
  console.log(data);
});

By the way, params is optional argument, so first of all try how it works without them:
t.get('search/tweets', function(err, data) {
  console.log(data);
});


text:
Q: Uninstall silverlight in C# programmatically I want to Uninstall silverlight in C# programmatically. can I get help regarding this. I need it for my project.

A: You can programmatically uninstall any program, if it was installed via a Windows installer, using the Windows Installer API http://msdn.microsoft.com/en-us/library/aa367449.aspx
More information here too: http://msdn.microsoft.com/en-us/library/aa367449.aspx


text:
Q: What happens when a blob is created in git? Git stores files as blobs, and then uses a SHA-1 checksum as a key to find each specific blob amongst the others, similar to a filename identifying a file.
So how does this dark magic work? That is, How does one start with a text file and end up with a blob? Is a blob created by dereferencing the memory memory address of the file or something?

A: There's very little actual magic in Git.  The one bit that is pretty magic is (are?) the various Secure Hash Algorithm (SHA) checksum designs, Git's use of these checksums, and how they form a Merkle Tree, but this is more "math magic" than anything else.
I think you're really asking "how does Git come up with the hash ID", and the answer to that one is simple:

*

*Find the size of the file, in bytes.  Print this in decimal, e.g., 123.

*Put the printed size in decimal after the word blob and a space.  Append an ASCII NUL character, b'\0' in Python for instance.  Hash the prefix and the data, and the result is the blob's hash ID:
$ python3
...
>>> data = b"some file data\n"
>>> prefix = "blob {}\0".format(len(data)).encode("utf-8")
>>> import hashlib
>>> h = hashlib.sha1()
>>> h.update(prefix)
>>> h.update(data)
>>> h.hexdigest()
'a831035a26dd2f75c2dd622c70ee22a10ee74a65'

We can check by using Git's object hasher:
$ echo 'some file data' | git hash-object -t blob --stdin
a831035a26dd2f75c2dd622c70ee22a10ee74a65

The hashes match, so this is the blob hash for any file that consists solely of the 15-byte line "some file data" as terminated by a newline.  Note that it is the content that determine the hash ID: the file's name here is irrelevant.  (This means the file's name must be, and is, stored elsewhere—in Git, in one or more tree objects.)
(Note that SHA-1 is no longer considered cryptographically secure.  Git is slowly being migrated to other hash algorithms, but there is no rush here.  See How does the newly found SHA-1 collision affect Git?)


text:
Q: Efficient 2D FFT of fixed length real input data in C/C++ I'm developing an algorithm that calls several times to a FFT function. I have several time constraints (real-time desired) so I need to minimize the time expended in every FFT call.
I'm working with OpenCV library and I have already implemented my code with two different approaches:

*

*Using FFTW library. Data/memory management + FFT(8ms) = 14ms (in mean, FFT_MEASURE flag).

*Using OpenCV fft function. Data/memory management + FFT (21ms) = 23ms (in mean).

As my input data is always fixed as a real image of 512x512 pixels, do you think if I implement myself the FFT algorithm based in the mathematical definition of DFT, storing the sine/cosine tables can I achieve better performance or the FFTW library is really very optimized? Any better ideas?
All ideas and suggestions will be really appreciated. By now, I don't consider paralellization or GPU implementation.
Thank you
Update:
System: Intel Xeon 5130 2.0GHz CPU in Windows 7, Visual Studio 10.0 and FFTW 3.3.3 (compiled following instructions in the site), OpenCV 2.4.3.
Code example for FFT call with FFTW (input: OpenCV Mat CV_32F (1 channel, float type),  output OpenCV Mat CV_32FC2 (2 channels, float type):
float           *im_data;

fftwf_complex    *data_in;
fftwf_complex    *fft;

fftwf_plan       plan_f;

int             i, j, k;

int height=I.rows;
int width=I.cols;
int N=height*width;

float* outdata = new float[2*N];
im_data = ( float* ) I.data;

data_in = ( fftwf_complex* )fftwf_malloc( sizeof( fftwf_complex ) * N );
fft     = ( fftwf_complex* )fftwf_malloc( sizeof( fftwf_complex ) * N );

plan_f = fftwf_plan_dft_2d( height , width , data_in , fft ,  FFTW_FORWARD ,  FFTW_MEASURE );

for(int i = 0,k=0; i < height; ++i) {
    float* row = I.ptr<float>(i);
    for(int j = 0; j < width; j++) {
        data_in[k][0]=(float)row[j];
        data_in[k][1] =(float)0.0;
        k++;
    }
}

fftwf_execute( plan_f );

int width2=2*width;
// writing output matrix: RealFFT[0],ImaginaryFFT[0],RealFFT[1],ImaginaryFFT[1],...
for( i = 0, k = 0 ; i < height ; i++ ) {
    for( j = 0 ; j < width2 ; j++ ) {

        outdata[i * width2 + j] = ( float )fft[k][0];
        outdata[i * width2 + j+1] = ( float )fft[k][1];
        j++;
        k++;
    }
}

Mat fft_I(height,width,CV_32FC2,outdata);

fftwf_destroy_plan( plan_f );
fftwf_free( data_in );
fftwf_free( fft );

return fft_I;

A: Your FFT time with FFTW seems very high. To get the best of out FFTW with fixed size FFTs you should generate a plan using the FFTW_PATIENT flag and then ideally save the generated "wisdom" for subsequent re-use. You can generate wisdom either from your own code or using the fftw-wisdom tool.

A: The FFT from the Intel Math Kernel Library (separate from the Intel compiler) is faster than FFTW most of the time.  I don't know if it will be enough of an improvement in your case to justify the price though.
I will agree with the others that rolling your own FFT is probably not a good use of your time (unless you are wanting to learn how to do it).  The available FFT implementations (FFTW, MKL) have been so finely tuned over many years.  I'm not saying that you can't do better, but it would probably be a lot of work and time for marginal gains.

A: Believe me fftw is realy very optimized, there is very small chance, that you can do it better.
Which compiler you have used for compiling fftw? Sometimes compiler from Intel gives better perfomance than gcc


text:
Q: Parsing custom data packets in an object oriented manner I am currently developing some software in C++ where I am sending and receiving custom data packets. I want to parse and manage these packets in a well structured manner. Obviously I am first receiving the header and after that the body of the data. The main problem is that I don't like creating a Packet-Object with only the header information and later on adding the body data. What is an elegant way of parsing and storing custom data packets?
Here is a rough sketch of what such a custom data packet could look like:
+-------+---------+---------+----------+------+
| Magic | Command | Options | Bodysize | Body |
+-------+---------+---------+----------+------+

(Lets assume Magic is 4 bytes, Command 1 byte, Options 2 bytes, Bodysize 4 bytes and the body itself is variable in length.)
How would I parse this without using any third party libraries?
Normally I'd say something like this could be done to store packet data:
#include <array>

class Packet {
public:

    explicit Packet(std::array<char, 10> headerbytes);

    void set_body(std::vector<char> data);
    std::vector<char> get_body();

    int8_t get_command();

    int16_t get_options();

    bool is_valid();

private:

    bool valid;

    int8_t _command;

    int16_t _options;

    int32_t body_size;

    std::vector<char> _data;

};

The problem is that I provide the header-information first and than add the body data in a hacky way later on. The packet object has a point of time where it is accessible in an incomplete state.
I first receive the header and after the header was received another receive call is made to read the body.
Would it make sense to have a parser instance that populates information into the packet object only make it accessible once it holds all needed information? Would it make sense to have a separate class for the header and the body? What would be the best design choice?
I am developing with C++ and for the sending and receiving of data over sockets the boost library is used.

A: If you don't want to tie the data reading into one complete constructor (for understandable reasons of separation of concerns), this is a good application for non-polymorphic inheritance:
struct Header {
  static constexpr SIZE=10;
  Header(std::array<char,SIZE>);

  std::int8_t get_command() const {return command;}
  std::int16_t get_options() const {return options;}
  std::int32_t body_size() const {return length;}

private:
  std::int8_t command;
  std::int16_t options;
  std::int32_t length;
};

struct Packet : private Header {
  using Body=std::vector<char>;
  Packet(const Header &h,Body b) : Header(h),body(std::move(b))
  {if(body.size()!=body_size()) throw …;}

  using Header::get_command;
  using Header::get_options;
  const Body& get_body() const {return body;}

private:
  Body body;
};

// For some suitable Stream class:
Header read1(Stream &s)
{return {s.read<Header::SIZE>()};}
Packet read2(const Header &h,Stream &s)
{return {h,s.read(h.body_size())};}
Packet read(Stream &s)
{return read2(read1(s),s);}

Note that the private inheritance prevents undefined behavior from deleting a Packet via a Header*, as well as the surely-unintended
const Packet p=read(s);
const Packet q=read2(p,s);   // same header?!

Composition would of course work as well, but might result in more adapter code in a full implementation.
If you were really optimizing, you could make a HeaderOnly without the body size and derive Header and Packet from that.

A: For this case I would use the pipeline design pattern creating 3 packet processor classes:

*

*Command (handles magic bytes too)

*Options

*Body (handles body size too)

all derived from one base class.
typedef unsigned char byte;

namespace Packet
{
    namespace Processor
    {
        namespace Field
        {
            class Item
            {
            public:
                /// Returns true when the field was fully processed, false otherwise.
                virtual bool operator () (const byte*& begin, const byte* const end) = 0;
            };

            class Command: public Item
            {
            public:
                virtual bool operator () (const byte*& begin, const byte* const end);
            };

            class Options: public Item
            {
            public:
                virtual bool operator () (const byte*& begin, const byte* const end);
            };

            class Body: public Item
            {
            public:
                virtual bool operator () (const byte*& begin, const byte* const end);
            };
        }

        class Manager
        {
        public:
            /// Called every time new data is received
            void operator () (const byte* begin, const byte* const end)
            {
                while((*fields[index])(begin, end))
                {
                    incrementIndex();
                }
            }

        protected:
            void incrementIndex();

            Field::Command command;
            Field::Options options;
            Field::Body body;
            Field::Item* const fields[3] = { &command, &options, &body };
            byte index;
        };
    }
}

A: You can use exceptions to prevent creation of incomplete packet objects.
I'd use char pointers instead of vectors for performance.
// not intended to be inherited
class Packet final {
public:
    Packet(const char* data, unsigned int data_len) {
        if(data_len < header_len) {
            throw std::invalid_argument("data too small");
        }

        const char* dataIter = data;

        if(!check_validity(dataIter)) {
            throw std::invalid_argument("invalid magic word");
        }
        dataIter += sizeof(magic);
        memcpy(&command, dataIter, sizeof(command)); // can use cast & assignment, too
        dataIter += sizeof(command);
        memcpy(&options, dataIter, sizeof(options)); // can use cast & assignment, too
        dataIter += sizeof(options);
        memcpy(&body_size, dataIter, sizeof(body_size)); // can use cast & assignment, too
        dataIter += sizeof(body_size);

        if( data_len < body_size+header_len) {
            throw std::invalid_argument("data body too small");
        }

        body = new char[body_size];
        memcpy(body, dataIter, body_size);
    }

    ~Packet() {
        delete[] body;
    }

    int8_t get_command() const {
        return command;
    }

    int16_t get_options() const {
        return options;
    }

    int32_t get_body_size() const {
        return body_size;
    }

    const char* get_body() const {
        return body;
    }

private:
    // assumes len enough, may add param in_len for robustness
    static bool check_validity(const char* in_magic) {
        return ( 0 == memcmp(magic, in_magic, sizeof(magic)) );
    }

    constexpr static char magic[] = {'a','b','c','d'};
    int8_t command;
    int16_t options;
    int32_t body_size;
    char* body;

    constexpr static unsigned int header_len = sizeof(magic) + sizeof(command)
            + sizeof(options) + sizeof(body_size);
};

Note: this is my first post in SO, so please let me know if something's wrong with the post, thanks.

A: I'm guessing you are trying Object-oriented networking. If so, the best solution for such parsing would be Flatbuffers or Cap'n Proto C++ code generator. By defining a schema, you will get state machine code that will parse the packets in an efficient and safe way.


text:
Q: Main difference between session and user scope custom dimension in google analytics I am understanding the use of user and session scope custom dimension. But still not getting the main difference between them.
Both are maintaining the values of dimensions in their sessions.Then what's the major difference between them. Any clear example for this?

A: Like you've understood, session scoped custom dimensions persists throughout the session. But user-scoped custom dimensions persists with the user. A user can have multiple sessions and the user-scoped custom dimension will be set for those sessions as well without purposely setting them with code. It will only be gone if the GA cookie is erased or something overwrites it.


text:
Q: PhoneGap Camera API for Android - Uncaught Exception I am trying to run the Camera API using Phone gap in Android, and i am running in all sort of issues.
I just copied phonegap camera example.
I am getting the following error
07-12 18:18:00.706: E/Web Console(17837): Uncaught TypeError: Cannot read property 'SAVEDPHOTOALBUM' of undefined at file:///android_asset/www/index.html:98

07-12 18:17:59.456: E/Web Console(17837): Uncaught ReferenceError: Camera is not defined at file:///android_asset/www/index.html:67

I tried all the other destination type. It dint work
destinationType: destinationType.FILE_URI
destinationType: Camera.DestinationType.FILE_URI
destinationType: destinationType.DATA_URL

Also i added the permission for Camera and hardware camera permission. But still it failed
Here is the following
<!DOCTYPE html>

<title>Capture Photo</title>

<button onclick="capturePhoto();">Capture Photo</button>

<button onclick="capturePhotoEdit();">Capture Editable Photo</button>

<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button>

<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button>

A: Ensure you are including the correct (latest) cordova file in your HTML.
I had the same problem and I was including
cordova-1.8.0.js

rather than
cordova-2.4.0.js

A: You can try this for

    Capturing Photo using phonegap

<button onclick="capturePhoto();">Capture Photo</button>

<button onclick="capturePhotoEdit();">Capture Editable Photo</button>

<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button>

<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button>

A: I had the same problem I solved it on three steps
The javascript include
I used cordova.js ONLY and removed any phonegap.js

Installing the plugin(s)
You must install the camera plugin using command line; xml only doesn't work
cordova plugin add org.apache.cordova.camera

Use right android-package
In your xml you may are using org.apache.cordova.CameraLauncher it is wrong and will give you  NullPointer exception.
The right package could be included like that
<feature name="Camera">
    <param name="ios-package" value="CDVCamera" />
    <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />
</feature>

Give them a try!
Thanks :)

A: 2.0.0.js this may solve your problem
you code is right only check for these cordova-2.0.0.js files only

A: Just adding

in my html solved it for me!
And also I had , so removed it and kept only .

A: I had the same problem.
You are using pictureSource.PHOTOLIBRARY and pictureSource.SAVEDPHOTOALBUM directly in the code.
The problem is that the html is loaded before the javascript and then you are trying to reach pictureSource. But has not been specified yet.
You have to use this when the app is fully loaded (eg. use jQuery event in documents.ready or some alternative in javascript)


text:
Q: Contacting developer of QGIS plugin? I want to give feedback to the developer of a non-core QGIS plugin.
(Numerical Vertex Edit by Cedric Moeri, who seems to have no webpage for his plugins)
I joined OSGeo Wiki but hardly know my way around it, or whether that is a good place to start.

A: There is a plugin page at http://plugins.qgis.org/plugins/numericalVertexEdit/
That provides link to bug reporting and other tools (via SourceForge and Trac). For example:
http://sourceforge.net/apps/trac/geoing/report/1
There is a way to send messages direct to a user via SourceForge, but please consider whether that is really appropriate. If in any doubt, a bug report or feature suggestion is probably more appropriate.


text:
Q: 401 for PostRequest with HttpURLConnection UPDATE
My problem turned out to be due to some super-class weirdness. However, the urlEncode in this example is wrong. In this case it was also unnecessary. If needed it should be done by each key and value without encoding & or =.
Other than that, this code is correct.

The (scala) code below fails because the server does not seem to receive the body.
The warning on the server log is:

WARNING *** OAuthTokenProcessor caught a OAuthRequestProblemException with message OAuthProblemException{error='invalid_request', description='Missing grant_type parameter value', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}

I am certain that the params are correct. The url is correct, The headers are correct
(This call already works in Postman and Python)
Any hints deeply appreciated!
private def doPostRequest(): Unit ={
  try {

    val connectionforPost = (new URL(url)).openConnection.asInstanceOf[HttpURLConnection]

    val params = "grant_type=password&client_id=xxxx&client_secret=seccret&username=admin&password=xxxx"
    val encodedString = URLEncoder.encode(params,"UTF-8")
    import java.nio.charset.StandardCharsets
    val postData = encodedString.getBytes(StandardCharsets.UTF_8)

    val contentlength = Integer.toString(encodedString.length)

    connectionforPost.setConnectTimeout(50000)
    connectionforPost.setReadTimeout(50000)
    connectionforPost.setRequestMethod("POST")
    connectionforPost.setDoOutput(true)
    connectionforPost.setDoInput(true)
    connectionforPost.setInstanceFollowRedirects(false)
    connectionforPost.setRequestProperty("User-agent", "test bot")
    connectionforPost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
    connectionforPost.setRequestProperty("Accept", "*/*")
    connectionforPost.setRequestProperty("Connection", "keep-alive")
    connectionforPost.setRequestProperty("Content-Length", contentlength)
    connectionforPost.setRequestProperty("Accept-Encoding", "gzip, deflate")
    connectionforPost.setUseCaches(false)

    import java.io.DataOutputStream

    val wr = new DataOutputStream(connectionforPost.getOutputStream)
    wr.write(postData)
    if (wr != null) wr.close()

  } catch{
    case e:Exception => logger.error(e.getMessage,e)
      throw e
  }
}

A: It appears that the server complains that you are not logged in. You get an authentication problem exception. How it usually works is that you send a request to the server to login with the user name and password. If the server authenticates you (recognizes your user name and password as valid ones) it sends you a response with an authentication token in the headers. You may see those 2 headers in your response to successful login:
 access-control-expose-headers=[Authorization], Authorization=[Bearer ....]

This means that in all your subsequent requests you will need to add a header "Authorization" that will hold the value "Bearer ....". Then the server will recognize this request as coming from an authenticated user.
Also, I suggest that you may use a 3d party HTTP client. Some well-known clients are Appache HTTP client and OK HTTP client. I use my own Http client that I wrote. It is also available as part of a MgntUtils Open Source Library. Here is the link to Maven artifacts and it is also available on Github with source code and JavaDoc. And here is a javadoc page for HttpClient. Here is the code sample on how you may obtain the token and use it:
        try {
        HttpClient loginClient = new HttpClient();
        loginClient.setConnectionUrl("http://your_url/login");
        loginClient.setRequestProperty("accept", "application/json;charset=UTF-8");
        loginClient.setContentType("application/json");
        String result = loginClient.sendHttpRequest(HttpMethod.POST, "{ \"username\": \"your_user_name\", \"password\": \"Your_password\"}");
        System.out.println(result);
        System.out.println("HTTP " + loginClient.getLastResponseCode() + " " + loginClient.getLastResponseMessage());
        System.out.println("Response headers: " + loginClient.getLastResponseHeaders());
        String accessControlExposeHeader = loginClient.getLastResponseHeader("access-control-expose-headers").get(0);
        String accessKey = loginClient.getLastResponseHeader(accessControlExposeHeader).get(0);
        HttpClient workingClient = new HttpClient();
        workingClient.setRequestProperty("accept", "application/json;charset=UTF-8");
        workingClient.setContentType("application/json");
        workingClient.setRequestProperty(accessControlExposeHeader, accessKey);
        workingClient.setConnectionUrl("http://yourUrl/yourPath");
        System.out.println(workingClient.sendHttpRequest(HttpMethod.GET));
    } catch (IOException e) {
        System.out.println(TextUtils.getStacktrace(e));
    }


text:
Q: Parsing XML where Parent/Child have same tag I'm working with the popshops api & parsing the XML in beautiful soup.
The data has four levels of categories.
(i.e Furniture is a sub-category of Home & Garden, Baby Nursery Furniture is a sub-category of Furniture)
How can I differentiate the 4 levels of categories when everything has the same tag 'category'.
<category id="16000" name="Home & Garden">
 <categories>
  <category id="16669" name="Furniture">
   <categories>
    <category id="17135" name="Baby Nursery Furniture">
     <categories>
      <category id="17146" name="Baby Beddings & Blankets" leaf="true"/>

A: As the Beautiful Soup documentation highlights, you could directly reference their attribute values instead of element or tag name:
soup.findAll(id="16000")

OR
soup.findAll(name="Home & Garden")

A: Generally, there are many ways you can differentiate the same tag using BeautifulSoup (I don't know if you have specific definition for "differentiate" here). One possible way would be differentiating by the hierarchy/structure. For example, to get only the forth level depth <category>s :
subSubSubCategory = soup.select("category category category category");

Specific for the forth level case, you can also get them by evaluating attribute leaf="true" :
subSubSubCategory = soup.select("category[leaf='true']");

For reference : BeautifulSoup > CSS Selector
Side note : you may want to consider using lxml directly if all you want to parse is a perfect valid XML.


text:
Q: How to make my PostGIS vector layer in QGIS visible? I have loaded a shp file (simple polygon with one entry) into PostgreSQL 9.3 (with extention PostGIS v2.1.3).  I now want to load this layer into QGIS (v2.2.0 Valmeira) via the "load Postgis layer) command.  The connection is OK and the layer is transfered to QGIS without a problem.  I can see the table attributes in QGIS and the "Zoomin to the layer" fct works (the function zooms in with the correct center point and scale), but the layer is invisible!  Regardless of the symbology attributes that I use, I cannot see the layer.
I have also made a view of the table and loaded it into QGIS (specifying my coord syst - 4269 - and a int4 primary key) and I have the same problem.  Any idea of what the problem is?

A: I've not got a straight answer for you but some thoughts - apologies if they're too obvious.
When you right click on the layer name and select the "Show Feature Count" box does it return the number you expected?
When you click on the layer in the Add PostGIS Layer screen, does the geometry column, data type, SRID projection and spatial type (Point, Linestring, etc) match what you expect?
If you click on the "!" messages button in the very bottom right of the QGIS screen does it show any unexpected errors relating to the layer?
Apologies if this is too obvious but is the Render box at the bottom of the screen checked?


text:
Q: How to convert an Arraylist(object) to an Arraylist(String) so I can use the .add method I'm trying to write a snippet of code that allows me to read through a text file and then returns that said list. However, when I try to add the next line of my text file there is an error that constantly switches my .add to an .addAll and then tries to revert back to .add. I assume this is because my ArrayList is not a string, so how would I convert my ArrayList so it's contents can be read and added?
private ArrayList<Patron> patronList = new ArrayList<Patron>();

private ArrayList<Patron> readPatrons(String filename) {
        ArrayList<Patron> lines = new ArrayList<>();
        Scanner s = null;
        File infile = new File(filename);
        try{
            s = new Scanner(infile);
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }
        while(s.hasNext())
            lines.add(s.next()); // Error here.
        return lines;

A: you can create a Patron object and a constructor in it to be better...for example
public class Patron{
   String name;
    public patron(String name){
      this.name=name;
  }
}

then while taking input you can do something like this
String S=s.next();
lines.add(new Patron(S));//or you can directly do lnes.add(new Patron(scan.next()))

A: This code   lines.add(s.next());
lines is an arraylist of Patron object, so you can add Patron object in it.
s.next() is going to give you a string. so that's why an error.
Create a Patron object and then add to lines

A: s.next()

returns a String, not a Patron. If your Patron class had a constructor that takes a String to create a Patron instance you would have to do something like
lines.add(new Patron(s.next()));


text:
Q: How to disconnect from multiple connected ble devices in Flutter app? I am currently connected to multiple ble devices. Now, I'd like to disconnect from them but I can't.
Here's the code for connecting:
for (String deviceId in deviceIdList) {
  try {
     await Provider.of<BleDeviceConnector>(context, listen: false)
     .connectAndLoad(
     deviceId: deviceId, custom: custom, index: index);
   } catch (e) {
   print(e);
 }
}

// In separate file...

class BleDeviceConnector extends ReactiveState<ConnectionStateUpdate> {
  BleDeviceConnector({
    required FlutterReactiveBle ble,
    required Function(String message) logMessage,
  })   : _ble = ble,
        _logMessage = logMessage;

  final FlutterReactiveBle _ble;
  final void Function(String message) _logMessage;

  @override
  Stream<ConnectionStateUpdate> get state => _deviceConnectionController.stream;

  final _deviceConnectionController = StreamController<ConnectionStateUpdate>();

  late StreamSubscription<ConnectionStateUpdate> _connection;

  Future<void> connectAndLoad(
      {required String deviceId,
      required CustomModel custom,
      required int index}) async {
    _connection = _ble.connectToDevice(id: deviceId).listen((update) async {
      _deviceConnectionController.add(update);
      if (update.connectionState == DeviceConnectionState.connected) {
        await custom.loadCustomStuff();
      }
    }, onError: (e) {
      print('Connecting to device $deviceId resulted in error $e');
    });
  }

  Future<void> disconnect(String deviceId) async {
    try {
      print('disconnecting from device: $deviceId');
      _logMessage('disconnecting from device: $deviceId');
      await _connection.cancel();
    } on Exception catch (e, _) {
      print("Error disconnecting from a device: $e");
      _logMessage("Error disconnecting from a device: $e");
    } finally {
      // Since [_connection] subscription is terminated, the "disconnected" state cannot be received and propagated
      _deviceConnectionController.add(
        ConnectionStateUpdate(
          deviceId: deviceId,
          connectionState: DeviceConnectionState.disconnected,
          failure: null,
        ),
      );
      print("Disconnected from $deviceId");
    }
  }

  Future<void> dispose() async {
    await _deviceConnectionController.close();
  }

This results in connecting to all the devices in deviceList, and loading info.
However, when I then try to disconnect from all of connected devices, it only successfully disconnects from the last one that was written to.
Here's what I'm trying:
for (String deviceId in deviceIdList) {
  await Provider.of<BleDeviceConnector>(context, listen: false).disconnect(deviceId);
}

When I reached out to the package author (package: flutter_reactive_ble), he said:
"you can create a class that will hold all subscriptions and then you can loop through them and cancel them one by one in order to disconnect"
When I ran this by the discord, the thought was that I should make a list instead of a class (which seemed more along the lines of what I was thinking). Either way, I tried adding the _connection StreamSubscription to a list, but it doesn't even end up getting added to the list (for some reason).
They also mentioned to try and make another _connection variable since that appears to be the only one.
My understanding was that I would get a new instance every time I make a call to **connectAndLoad(...).
Any help would REALLY be appreciated.
Thanks!


text:
Q: How to get coordinates correctly from django to leaflet with geojson I loaded some Shapefile multipolygons into Geodjango to show them as a layer on a Leaflet map. But on the website, no layer appears, just the map itself.
The geometry data are stored in the Geodjango database like so:
from django.contrib.gis.db import models

class wgo(models.Model):
    (some more variables)
    poly = models.MultiPolygonField(srid=4326)

I pass the multipolygons with geojson and serialize like so:
wcrds = wgo.objects.filter(id=wid)
gridone = serialize('geojson', wcrds.all())

return render(request, 'result.html', {'gridone': gridone})

And when I inspect the page I can see that the geojson data indeed makes it to the html:
var Hlayer = new L.GeoJSON(

    {"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"wijkcode": "WK036356", "wijknaam": "Middenmeer", "poly": "SRID=4326;MULTIPOLYGON (((4.93714288723798 52.3576900936898, 4.93742729807085 52.3577390397678,)))", "pk": "909"}, "geometry": null}]}
    , {
        style: Hstyle
    }
);

var mymap = L.map('mapid').setView([52.3701, 4.8967], 13);

var OpenStreetMap_Mapnik = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '© OpenStreetMap contributors'
}).addTo(mymap);

(I took out most of the coordinates for brevity's sake). It looks like geojson did not pick up on the fact that the poly variable is the one with the geometry.
I see geojson coordinates with square brackets around them on example sites, as opposed to the round ones on mine.
I imported the shapefile directly via Geodjango's Layer Mapping, following the Geodjango tutorial. Also, I viewed and manipulated this Shapefile with ogrinfo, ogr2ogr and, in Python, GDAL osgeo without any problems.
Any idea how I might get Geodjango and geojson to pass the coordinates in the right format to Leaflet? Thank you in advance.

A: My mistake here. When serializing geojson, you should obviously tell it which variable contains geometry. Instead of
gridone = serialize('geojson', wcrds.all())

Made it:
gridone = serialize('geojson', wcrds.all(), geometry_field='poly')

And it works. Read the docs, as they say...


text:
Q: In Sybase SUP, do you have suggestions for non-example startup? All,
Maybe I'm thinking too much about this.  All of the examples I have seen seem to cover starting a (iOS) native App from the AppDelegate.  I'm not excited about this, but I can't get around it so that it feels more comfortable.  Are you doing something different, and how?
Thanks.

A: You can simply move the processing of initializing the SUP connection from the AppDelegate's applicationDidFinishLaunching method to the viewDidLoad method of your main view controller class.
You would also need to move the NotificationCenter handler methods to your main view controller class.


text:
Q: Q: Dict comprehension on a dictionary of pandas dataframes, with a function with multiple outputs I have a dictionary containing pandas dataframes with corresponding keys:
import pandas as pd
df_dict = pd.read_excel('/directory/data.xlsx', sheet_name=None)

Where the keys are the sheet names of an excel file.
Is it possible to use dict comprehension to create two new dictionaries of pandas dataframes by using a function with two outputs? :
def somefunction(df):
    #Does something
    df1 = df.apply(lambda x: x*2)
    df2 = df.apply(lambda x: x*4)
    return df1, df2

df_dict1, df_dict2 = {key: somefunction(df) for (key, df) in df_dict.items()}
#Does not work..

I know it's possible with the zip(*) keyword when using a list, but it doesn't seem to work with dictionaries
df_dict1, df_dict2 = zip(*{key: somefunction(df) for (key, df) in df_dict.items()})
#Does not work either

Both return
too many values to unpack (expected 2)

A: You cannot zip dictionnaries, but you can zip their items and build dictionaries back from the item lists. Here you could do:
[dict(t) for t in zip(*(tuple((key,v)  for v in somefunction(val))
                        for key,val in df_dict.items()))]

A: Your dictionary comprehension doesn't look right. I think you're trying to do the following:
def somefunction(df):
    #Does something
    df1 = df.apply(lambda x: x*2)
    df2 = df.apply(lambda x: x*4)
    return [df1, df2]

processed_dicts = [list(zip([key]*2, somefunction(df))) for (key, df) in df_dict.items()]
df_dict1 = dict([x[0] for x in processed_dicts])
df_dict2 = dict([x[1] for x in processed_dicts])


text:
Q: Help selecting rechargeable batteries for 3W 1A handheld lantern Salutes. I want to build a handheld lantern with a 3W 3V LED and the best I have is a 9V battery and I don't want to buy dozens of 1,5V, 9V batteries nor use a car battery (for a handheld lantern). Despite the LED asking for 3V which I could adjust for, the real problem is the 1A I should feed the LED with, which would blackout common batteries in seconds due to their Maximum Continuous Discharge Current property, according to this basic battery guide. I confirm that with a misconnection I once made and this site that once told me 9V batteries have a nominal current ourput around 12mA, although I know one of mine can stand stable providing 80mA.
According to that same second site, looks like I should use around 9 "D-batteries" to stay in a safe zone, but I wanted to know how many times I could force the reccommended current ("Corrente recomendada (mA)", in the referred website) while maintaining a basically stable discharge.
I'm new to bulk converters and I thought maybe I could lower a 9V battery voltage and increase the Maximum Continuous Discharge Current of the battery, but bulks also dissipate power and the idea seems awkward, it seems better to use lower voltage batteries instead (but expensive).
I could of course limit the current to 0,5 or 0,75A to ease the design, but I actually wanted to use two diodes instead of "half". So am I forced to opt for a wired power source?

A: Lithium or the much safer LiFePO4 would be appropriate here, certainly not non-rechargeable D cells. There are larger cells than 18650 ... a couple of 32650 cells might be more appropriate.
1 LiFePO4 cell (3.2V) covers a range of 3.6V (very briefly), 3.3 to 3.1 (most of the discharge time) ad can be used down to 2.5 but there's no point going below 2.8V. Unfortunately this probably crosses the voltage range of your LED so you either need a buck-boost converter, or (probably better) 2 cells in series and a buck converter.


text:
Q: General error: 1205 Lock wait timeout exceeded; try restarting transaction I am developing an app with Laravel + MySQL for online exam assessment. A lot of users submit their response at the same time (within the span for few mins) so there is heavy load on the database server.
I am getting several General error: 1205 Lock wait timeout exceeded; try restarting transaction during many concurrent submissions.
I enabled slow query log and saw following entries in my log
update `form_responses` set `photo_url` = 'https://example.com/ae252b371effc7cb11dbcbbb18602026.jpg', `form_responses`.`updated_at` = '2020-09-26 11:39:17' where `id` = 32407;

As per my understanding, this is just a simple row update with a primary column being queried (means indexing should work).
But what I can't wrap my head around is - why Innodb is not using row level locking and provide a lock on this particular row. Is there some specific Innodb value I should increase this in case?

A: InnoDB is using row level locking.
Problem is, the application or the ORM are using it the wrong way, not giving MySQL sufficient information on what is to be done, resulting in a deadlock.
The easiest - not, I hasten to say, the most efficient! - way to overcome this problem is probably to resort to advisory locking if you find out that the updates all happen in the same small set of methods.
Note that it is not at all a given that your deadlock is in that table; you should run SHOW ENGINE INNODB STATUS to see what the last detected deadlock was. For instance you'll find:
LATEST DETECTED DEADLOCK
------------------------
200915 11:31:03
*** (1) TRANSACTION:
TRANSACTION 22B8A76B9, ACTIVE 0 sec starting index read
mysql tables in use 3, locked 3
LOCK WAIT 4 lock struct(s), heap size 1248, 4 row lock(s)
MySQL thread id 11161737, OS thread handle 0x7fd06d708700, query id ... UPDATE table SET ... WHERE Dat_UsrId = '11254' && Dat_CreUte='...' && Dat_Tip = 'C'

*** (2) TRANSACTION:
TRANSACTION 22B8A76B4, ACTIVE 0 sec fetching rows
mysql tables in use 3, locked 3
2616 lock struct(s), heap size 244152, 7262 row lock(s)
MySQL thread id 11161676, OS thread handle 0x7fd06ca97700, query id ... UPDATE table SET ... WHERE ...

*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 866959 page no 46 n bits 1616 index `NewIndex2` of table `schema`.`table` trx id 22B8A76B4 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 866959 page no 68831 n bits 72 index `PRIMARY` of table `schema`.`table` trx id 22B8A76B4 lock_mode X locks rec but not gap waiting
Record lock, heap no 5 PHYSICAL RECORD: n_fields 18; compact format; info bits 0

*** WE ROLL BACK TRANSACTION (1)
------------

Notice that here the logical error is in transaction TWO's query. This is a very strong hint:
2616 lock struct(s), heap size 244152, 7262 row lock(s)

...the WHERE needs to lock 7262 rows (!), which from the application logic's point of view is completely nonsensical (see also this for an explanation of "gapping").
Otherwise, you can resort to explicit transactions plus table level locking with LOCK TABLE form_responses WRITE.
The most efficient way to do it is to have all involved methods to enter an explicit transaction:
SET autocommit = 0;
UPDATE form_responses ... WHERE id = ...;
COMMIT WORK;


text:
Q: How to make WordPress keep me signed in? When I log in to my WordPress blog, there's a checkbox that says Remember me.  But whether or not I check this, if I come back in a day or two I have to log in again, so it doesn't appear that this checkbox does anything.  (My Google account, by contrast, hasn't ever once asked me to re-login on this computer, for more than a year now.)
How do I make WP actually remember me?

A: The cookies are set to expire two weeks from the time they are created. From the codex
The expiration period is set in wp-includes/pluggable.php as shown below:
$expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );

You can use the auth_cookie_expiration filter to change this value.

A: Does it require you to type your user name when you come back in a few days? If you have to type that, then yes - something is wrong with your cookies perhaps.
If it fills in your user name only, its working as intended. Remember me shouldn't maintain the logged in session indefinitely, only remember the user's name last used. Password will still be required.


text:
Q: Mysql, delete unexisting entries Let's imagine he have two tables
--
-- Table structure for table `user`
--

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `phoneID` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

--
-- Table structure for table `phone`
--

CREATE TABLE IF NOT EXISTS `phone` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userID` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

So now I need create such query - I need delete all phone-entries from phone table where userID not exist (means user was deleted from user table and there is no such userID) using only one query.
My thoughts: we can use innerJoin to select all equal entries and then somehow we need delete others from phone table.
Please help with it.
WBR

A: You're on the right track. But what you need is a query that does an "anti-join", to get all rows from phone that don't have a matching row in user.
Write the query first:
SELECT p.*
  FROM `phone` p
  LEFT
  JOIN `user` u
    ON u.id = p.userID
 WHERE u.id IS NULL

Notice that this does a left join, so it's saying "get me ALL rows from phone, along with any matching rows from user". The trick to the anti-join is the WHERE clause, which says, "eliminate all the rows where we found a match". So what we are left with is rows from phone that didn't have a matching row in user.
After you verify this is the set of rows you want to delete, and then just change the SELECT keyword to DELETE:
-- SELECT p.*
DELETE p.*
  FROM `phone` p
  LEFT
  JOIN `user` u
    ON u.id = p.userID
 WHERE u.id IS NULL

http://dev.mysql.com/doc/refman/5.5/en/delete.html

BTW: It's a bit unusual to have foreign key columns in each table referring to the other. There's no "rule" against it, but it's usually not required to satisfy a requirement that can be met by having a foreign key in just one table or the other. There are some corner cases where we'd need foreign keys pointing in both directions, but this a rare exception.

A: delete phone where userid not in (select user_id from user);

BTW, PhoneID should not be a field in the user table.


text:
Q: Detect mouse over nsbezierpath I'm a starting developer and I have this single window Mac application with a custom view inside. Inside that custom ceix I have defined multiple nsbezierpath.
Each nsbezierpath represents a region of my map so they are not rectangular at all.
What I would like to have is a way to detect when my mouse enter a nsbezierpath so that I could display the name of the region over which the mouse is hovering.
I can't seem to find where to start, any ideas ?
Thanks for looking into my problem

A: Set up a tracking area to detect mouse movement (NSTrackingArea). Be sure that the mouse location is in the view coordinate system, then use the location in a call to containsPoint: on each bezier path to determine which ones the mouse is over.


text:
Q: What is the formula and the name of the mathematical-phenomenon seen at the ending of "Around the World in Eighty Days"? Spoiler in brief for those who don't know the ending yet:
At the end, Phileas Fogg alongside with his companions realize that they have arrived back to London a day earlier than expected due fact the party did travel eastward.
Each time they crossed the known time-zone(s), they adjusted their (pocket-)clocks an hour backwards (sans Passepartout. depending on the adaptation / source), which each time roughly gave them an extra hour to win the wager (the details regarding to "won" amount of time differs a bit in each adaptation of the novel).

----------
That famous ending should be a quite simple one.
But how about something a bit more modern with essentially same result, only the whole process lasts over an year (using a real, up-to-date-calendar will help during "perceiving"-phase:

- You're being paid exactly every-fourth-full-week on Friday (E.G. during 2015 first on February 27th, then on March 27th, then on April 24th, and so worth).

+ On those paydays, you also start paying your apartment-rent upfront (E.G. on the payday of February 2015, you're paying the rent of March 2015, and so forth).

-> By continuing paying the rent like this for roughly 12-months (less even, to be precise), you will end up into a situation in which you're paying the upcoming rent over a month before hand (E.G. on February 2016, you're already paying the rent of April 2016).

For the sake of information-sharing alongside providing yet even more material to help with "perceiving"-phase, here is a link to an example "payday-model" from real-life:
Labour Market Subsidy in Finland

As the title of this question hints, I am indeed looking a term / name for "mathematical-phenomenon" alongside a simple as possible formula for simple people.
---------
---------

A: Loosely, I would call this "phase shift".
Suppose we have two periodic phenomena of different frequencies or equivalently different periods. If both start at the same time, "in phase", then after some time the two cycles will be significant out of sync, "out of phase".
Eventually the two will be close to or exactly back in phase in as much as the two phenomena begin their cycles at the same time. But the number of periods that has elapsed is not the same for the two.
In physics, this behavior receives a lot of quantitative attention as many physical systems are modeled as the superposition of waves with different periods.

A: The International Date line; if they adjusted their watches by an hour each time, and did not adjust by an entire day in mid- Pacific, that explains it.
http://en.wikipedia.org/wiki/International_Date_Line
http://en.wikipedia.org/wiki/International_Date_Line#Around_the_World_in_Eighty_Days


text:
Q: Class method calls run fine first time, but very slow after exiting activity and trying to run the computation second time OK, so here's the problem:
I'm making a game with randomly generated terrain. The terrain is generated once and saved to disk/SD card. It does this quite nicely :)
To do this, I run a SplashScreenActivity which runs my opening splashscreen, the world creation or the world loading, depending on how it is started.
The actual procedural generation is done using 4D Simplex Noise using a class written by Stefan Gustavson and ptimised by Peter Eastman (and optimised and speeded up by at least 50% by myself, pulling variables out and making them static ... but the problem I'm about to describe happened before those changes).
Basically I use their noise function to fill tiles with noise. In my world creation loop I loop through all the tiles and per tile I run through all the pixels, calling the SimplexNoise4D.noise(x,y,z,w) function of the class to fill each pixel (I'm planning on sending a xyzw-per-pixel collection to the class so it can run the method on that for faster access).
Anyway, this all works great. But when I exit my game activity and return to the main menu, if I try to run the world creation again, accessing the SimplexNoise class methods (the .noise method and the internal methods it uses) is SLOW!!!
The only way to get the calls to run at normal speed is to exit the whole application (kill it using a task manager) and restart the application. Then, the first time I run it, tile creation is as fast as it should be.
Using debugging/method profilling ect, it seems the calls to the .noise method and it's calls to the dot methods take a huge amount of time the second time I try to run the whole world creation thing.
So, again, The first time I loop through and access using SimplexNoise.noise(xyzw), it runs fine. Accessing it for all pixels in all the tiles a second time however (after being ingame), and all method calls to the class take FOREVER.
Does anyone know why this happens and how I can stop it from happening?
-EDIT-
Just to clear things up, the application works like this:
mainmenuActivity ->chooseWorldSizeActivity->Splashscreen which creates world with a lot of calls to SimplexNoise.noise(xywz)->exit splashscreen->start game Activity.
This works fine and at speed.
If, however, I then quit the gameActivity (which goes to main menu), then ->selectWordlSizeActivity->splashscreenActivity, now the calls to SimplexNoise.noise(xyzw) take forever to complete.
If I stop the whole application (using a atskkiller), then world creation takes the normal time to run again. And I can't really find out why!
-/EDIT-
The calling loop (in the doInBackground() of an ASyncTask) just is:
for(loop over rows of tiles)
    for(loop over column tiles)
        for(each pixel)
             create x, y, z, w;
             SimplexNoise.noise(xyzw);

The Simplex Noise class looks like this:
`
public final class SimplexNoise4D {  // Simplex noise in 2D, 3D and 4D
  private static final Grad grad3[] = {new Grad(1,1,0),new Grad(-1,1,0),new Grad(1,-1,0),new Grad(-1,-1,0),
                                 new Grad(1,0,1),new Grad(-1,0,1),new Grad(1,0,-1),new Grad(-1,0,-1),
                                 new Grad(0,1,1),new Grad(0,-1,1),new Grad(0,1,-1),new Grad(0,-1,-1)};

  private static final Grad grad4[]= {new Grad(0,1,1,1),new Grad(0,1,1,-1),new Grad(0,1,-1,1),new Grad(0,1,-1,-1),
                   new Grad(0,-1,1,1),new Grad(0,-1,1,-1),new Grad(0,-1,-1,1),new Grad(0,-1,-1,-1),
                   new Grad(1,0,1,1),new Grad(1,0,1,-1),new Grad(1,0,-1,1),new Grad(1,0,-1,-1),
                   new Grad(-1,0,1,1),new Grad(-1,0,1,-1),new Grad(-1,0,-1,1),new Grad(-1,0,-1,-1),
                   new Grad(1,1,0,1),new Grad(1,1,0,-1),new Grad(1,-1,0,1),new Grad(1,-1,0,-1),
                   new Grad(-1,1,0,1),new Grad(-1,1,0,-1),new Grad(-1,-1,0,1),new Grad(-1,-1,0,-1),
                   new Grad(1,1,1,0),new Grad(1,1,-1,0),new Grad(1,-1,1,0),new Grad(1,-1,-1,0),
                   new Grad(-1,1,1,0),new Grad(-1,1,-1,0),new Grad(-1,-1,1,0),new Grad(-1,-1,-1,0)};

  private static final short p[] = {151,160,137,91,90,15,
  131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
  190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
  88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
  77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
  102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
  135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
  5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
  223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
  129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
  251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
  49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
  138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180};
  // To remove the need for index wrapping, double the permutation table length
  private static short perm[] = new short[512];
  private static short permMod12[] = new short[512];
  static {
    for(int i=0; i<512; i++)
    {
      perm[i]=p[i & 255];
      permMod12[i] = (short)(perm[i] % 12);
    }
  }

  // Skewing and unskewing factors for 2, 3, and 4 dimensions
  private static final double F2 = 0.5*(Math.sqrt(3.0)-1.0);
  private static final double G2 = (3.0-Math.sqrt(3.0))/6.0;
  private static final double F3 = 1.0/3.0;
  private static final double G3 = 1.0/6.0;
  private static final double F4 = (Math.sqrt(5.0)-1.0)/4.0;
  private static final double G4 = (5.0-Math.sqrt(5.0))/20.0;

  // This method is a *lot* faster than using (int)Math.floor(x)
  private static int fastfloor(double x) {
    int xi = (int)x;
    return x<xi ? xi-1 : xi;
  }

  private static double dot(Grad g, double x, double y) {
    return g.x*x + g.y*y; }

  private static double dot(Grad g, double x, double y, double z) {
    return g.x*x + g.y*y + g.z*z; }

  private static double dot(Grad g, double x, double y, double z, double w) {
    return g.x*x + g.y*y + g.z*z + g.w*w; }

  private static double n0, n1, n2, n3, n4; // Noise contributions from the five corners
  private static double s;// Factor for 4D skewing
  private static int i;
  private static int j;
  private static int k;
  private static int l;
  private static double t; // Factor for 4D unskewing
  private static double X0; // Unskew the cell origin back to (x,y,z,w) space
  private static double Y0;
  private static double Z0;
  private static double W0;
  private static double x0;  // The x,y,z,w distances from the cell origin
  private static double y0;
  private static double z0;
  private static double w0;
  private static int rankx;
  private static int ranky;
  private static int rankz;
  private static int rankw;
  private static int i1, j1, k1, l1; // The integer offsets for the second simplex corner
  private static int i2, j2, k2, l2; // The integer offsets for the third simplex corner
  private static int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner
  private static double x1; // Offsets for second corner in (x,y,z,w) coords
  private static double y1;
  private static double z1;
  private static double w1;
  private static double x2; // Offsets for third corner in (x,y,z,w) coords
  private static double y2;
  private static double z2;
  private static double w2;
  private static double x3; // Offsets for fourth corner in (x,y,z,w) coords
  private static double y3;
  private static double z3;
  private static double w3;
  private static double x4; // Offsets for last corner in (x,y,z,w) coords
  private static double y4;
  private static double z4;
  private static double w4;
  // Work out the hashed gradient indices of the five simplex corners
  private static int ii;
  private static int jj;
  private static int kk;
  private static int ll;
  private static int gi0;
  private static int gi1;
  private static int gi2;
  private static int gi3;
  private static int gi4;

  private static double t0;
  private static double t1;
  private static double t2;
  private static double t3;
  private static double t4;

  // 4D simplex noise, better simplex rank ordering method 2012-03-09
  public static double noise(double x, double y, double z, double w) {

    ////double n0, n1, n2, n3, n4; // Noise contributions from the five corners
    // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
    ////double s = (x + y + z + w) * F4; // Factor for 4D skewing
    s = (x + y + z + w) * F4; // Factor for 4D skewing
    /*int i = fastfloor(x + s);
    int j = fastfloor(y + s);
    int k = fastfloor(z + s);
    int l = fastfloor(w + s);
    double t = (i + j + k + l) * G4; // Factor for 4D unskewing
    double X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
    double Y0 = j - t;
    double Z0 = k - t;
    double W0 = l - t;
    double x0 = x - X0;  // The x,y,z,w distances from the cell origin
    double y0 = y - Y0;
    double z0 = z - Z0;
    double w0 = w - W0;*/
    i = fastfloor(x + s);
    j = fastfloor(y + s);
    k = fastfloor(z + s);
    l = fastfloor(w + s);
    t = (i + j + k + l) * G4; // Factor for 4D unskewing
    X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
    Y0 = j - t;
    Z0 = k - t;
    W0 = l - t;
    x0 = x - X0;  // The x,y,z,w distances from the cell origin
    y0 = y - Y0;
    z0 = z - Z0;
    w0 = w - W0;
    // For the 4D case, the simplex is a 4D shape I won't even try to describe.
    // To find out which of the 24 possible simplices we're in, we need to
    // determine the magnitude ordering of x0, y0, z0 and w0.
    // Six pair-wise comparisons are performed between each possible pair
    // of the four coordinates, and the results are used to rank the numbers.
    /*int rankx = 0;
      int ranky = 0;
      int rankz = 0;
      int rankw = 0;
      if(x0 > y0) rankx++; else ranky++;
      if(x0 > z0) rankx++; else rankz++;
      if(x0 > w0) rankx++; else rankw++;
      if(y0 > z0) ranky++; else rankz++;
      if(y0 > w0) ranky++; else rankw++;
      if(z0 > w0) rankz++; else rankw++;
      int i1, j1, k1, l1; // The integer offsets for the second simplex corner
      int i2, j2, k2, l2; // The integer offsets for the third simplex corner
      int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner*/
    rankx = 0;
    ranky = 0;
    rankz = 0;
    rankw = 0;
    if(x0 > y0) rankx++; else ranky++;
    if(x0 > z0) rankx++; else rankz++;
    if(x0 > w0) rankx++; else rankw++;
    if(y0 > z0) ranky++; else rankz++;
    if(y0 > w0) ranky++; else rankw++;
    if(z0 > w0) rankz++; else rankw++;
    // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
    // Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
    // impossible. Only the 24 indices which have non-zero entries make any sense.
    // We use a thresholding to set the coordinates in turn from the largest magnitude.
    // Rank 3 denotes the largest coordinate.
    i1 = rankx >= 3 ? 1 : 0;
    j1 = ranky >= 3 ? 1 : 0;
    k1 = rankz >= 3 ? 1 : 0;
    l1 = rankw >= 3 ? 1 : 0;
    // Rank 2 denotes the second largest coordinate.
    i2 = rankx >= 2 ? 1 : 0;
    j2 = ranky >= 2 ? 1 : 0;
    k2 = rankz >= 2 ? 1 : 0;
    l2 = rankw >= 2 ? 1 : 0;
    // Rank 1 denotes the second smallest coordinate.
    i3 = rankx >= 1 ? 1 : 0;
    j3 = ranky >= 1 ? 1 : 0;
    k3 = rankz >= 1 ? 1 : 0;
    l3 = rankw >= 1 ? 1 : 0;
    // The fifth corner has all coordinate offsets = 1, so no need to compute that.
    /*double x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
    double y1 = y0 - j1 + G4;
    double z1 = z0 - k1 + G4;
    double w1 = w0 - l1 + G4;
    double x2 = x0 - i2 + 2.0*G4; // Offsets for third corner in (x,y,z,w) coords
    double y2 = y0 - j2 + 2.0*G4;
    double z2 = z0 - k2 + 2.0*G4;
    double w2 = w0 - l2 + 2.0*G4;
    double x3 = x0 - i3 + 3.0*G4; // Offsets for fourth corner in (x,y,z,w) coords
    double y3 = y0 - j3 + 3.0*G4;
    double z3 = z0 - k3 + 3.0*G4;
    double w3 = w0 - l3 + 3.0*G4;
    double x4 = x0 - 1.0 + 4.0*G4; // Offsets for last corner in (x,y,z,w) coords
    double y4 = y0 - 1.0 + 4.0*G4;
    double z4 = z0 - 1.0 + 4.0*G4;
    double w4 = w0 - 1.0 + 4.0*G4;
    // Work out the hashed gradient indices of the five simplex corners
    int ii = i & 255;
    int jj = j & 255;
    int kk = k & 255;
    int ll = l & 255;
    int gi0 = perm[ii+perm[jj+perm[kk+perm[ll]]]] % 32;
    int gi1 = perm[ii+i1+perm[jj+j1+perm[kk+k1+perm[ll+l1]]]] % 32;
    int gi2 = perm[ii+i2+perm[jj+j2+perm[kk+k2+perm[ll+l2]]]] % 32;
    int gi3 = perm[ii+i3+perm[jj+j3+perm[kk+k3+perm[ll+l3]]]] % 32;
    int gi4 = perm[ii+1+perm[jj+1+perm[kk+1+perm[ll+1]]]] % 32;*/
    x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
    y1 = y0 - j1 + G4;
    z1 = z0 - k1 + G4;
    w1 = w0 - l1 + G4;
    x2 = x0 - i2 + 2.0*G4; // Offsets for third corner in (x,y,z,w) coords
    y2 = y0 - j2 + 2.0*G4;
    z2 = z0 - k2 + 2.0*G4;
    w2 = w0 - l2 + 2.0*G4;
    x3 = x0 - i3 + 3.0*G4; // Offsets for fourth corner in (x,y,z,w) coords
    y3 = y0 - j3 + 3.0*G4;
    z3 = z0 - k3 + 3.0*G4;
    w3 = w0 - l3 + 3.0*G4;
    x4 = x0 - 1.0 + 4.0*G4; // Offsets for last corner in (x,y,z,w) coords
    y4 = y0 - 1.0 + 4.0*G4;
    z4 = z0 - 1.0 + 4.0*G4;
    w4 = w0 - 1.0 + 4.0*G4;
    // Work out the hashed gradient indices of the five simplex corners
    ii = i & 255;
    jj = j & 255;
    kk = k & 255;
    ll = l & 255;
    gi0 = perm[ii+perm[jj+perm[kk+perm[ll]]]] % 32;
    gi1 = perm[ii+i1+perm[jj+j1+perm[kk+k1+perm[ll+l1]]]] % 32;
    gi2 = perm[ii+i2+perm[jj+j2+perm[kk+k2+perm[ll+l2]]]] % 32;
    gi3 = perm[ii+i3+perm[jj+j3+perm[kk+k3+perm[ll+l3]]]] % 32;
    gi4 = perm[ii+1+perm[jj+1+perm[kk+1+perm[ll+1]]]] % 32;

    // Calculate the contribution from the five corners
    /*double t0 = 0.6 - x0*x0 - y0*y0 - z0*z0 - w0*w0;
    if(t0<0) n0 = 0.0;
    else {
      t0 *= t0;
      n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0);
    }
   double t1 = 0.6 - x1*x1 - y1*y1 - z1*z1 - w1*w1;
    if(t1<0) n1 = 0.0;
    else {
      t1 *= t1;
      n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1);
    }
   double t2 = 0.6 - x2*x2 - y2*y2 - z2*z2 - w2*w2;
    if(t2<0) n2 = 0.0;
    else {
      t2 *= t2;
      n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2);
    }
   double t3 = 0.6 - x3*x3 - y3*y3 - z3*z3 - w3*w3;
    if(t3<0) n3 = 0.0;
    else {
      t3 *= t3;
      n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3);
    }
   double t4 = 0.6 - x4*x4 - y4*y4 - z4*z4 - w4*w4;
    if(t4<0) n4 = 0.0;
    else {
      t4 *= t4;
      n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4);
    }*/
    t0 = 0.6 - x0*x0 - y0*y0 - z0*z0 - w0*w0;
    if(t0<0) n0 = 0.0;
    else {
      t0 *= t0;
      n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0);
    }
   t1 = 0.6 - x1*x1 - y1*y1 - z1*z1 - w1*w1;
    if(t1<0) n1 = 0.0;
    else {
      t1 *= t1;
      n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1);
    }
   t2 = 0.6 - x2*x2 - y2*y2 - z2*z2 - w2*w2;
    if(t2<0) n2 = 0.0;
    else {
      t2 *= t2;
      n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2);
    }
   t3 = 0.6 - x3*x3 - y3*y3 - z3*z3 - w3*w3;
    if(t3<0) n3 = 0.0;
    else {
      t3 *= t3;
      n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3);
    }
   t4 = 0.6 - x4*x4 - y4*y4 - z4*z4 - w4*w4;
    if(t4<0) n4 = 0.0;
    else {
      t4 *= t4;
      n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4);
    }
    // Sum up and scale the result to cover the range [-1,1]
    return 27.0 * (n0 + n1 + n2 + n3 + n4);
  }

  // Inner class to speed up gradient computations
  // (array access is a lot slower than member access)
  private static class Grad
  {
    double x, y, z, w;

    Grad(double x, double y, double z)
    {
      this.x = x;
      this.y = y;
      this.z = z;
    }

    Grad(double x, double y, double z, double w)
    {
      this.x = x;
      this.y = y;
      this.z = z;
      this.w = w;
    }
  }
}

`


text:
Q: Shortcode Output on Top of the Posts I'm using this code to create shortcode. when I Place shortcode in page, that appear at the top of content.
<?php function SkypeChat(){ ?>

<?php } add_shortcode( 'SkypeButton', 'SkypeChat' ); ?>

I already tried return method but still same output.

A: Your function prints the content to the screen instead of returning it. So when the shortcode is called, which happens while the page content is being built in a filterable variable, your function gets called and prints the content before the rest of the page content is rendered.
If you modify your function like this, you should have better results:
<?php function SkypeChat() {
    return <<

An even better approach would be to just include the div using your shortcode, and enqueue the JavaScript using the wp_enqueue_scripts action hook.


text:
Q: Issue with authentication with a laravel spa, it will not always be logged in and ads incorrect cookies Working on a laravel 8 SPA with Vue and Sanctum. As a newbie with laravel I run into a issue.
I would guess that the issue is with the laravel session cookies as sanctum seems the keep on working but I could be wrong.
How I reproduce the problem:

*

*When I login it works, sanctum token is generated, CXRF works, laravel auth works and when I
refresh the page it still keeps working. Still on the admin page.

*When I hit the logout button it will delete all auth cookies and vuex values and I get redirected to the login page. This looks good

*I want to login back but at this point it will throw an POST http://localhost:3000/auth/login 419 (unknown status)
3a. To prevent this I refresh the page first, I hit the login button and I am back on the admin page.

*When I do the tirst 3 steps there's a chance that the authencation stops working and I will be redirected to the login page when I refresh the page.
What I have seen is that I have 4 cookies present when all is working propper.

*

*appname_session (this the session?)

*CXRF_token

*io (not sure what this does)

*random value

But I have seen is that it will add a 5th(or sometimes even more) cookie with a session value and this will lead to a logout and a invalid session(laravel side)
I have 4 routes, (web & api not in use for now)
If I need to post any files here let me know as I dont know what I need to post here
config/auth.php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
       // 'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],

    'admin' => [
       // 'driver' => 'token',
        'provider' => 'users',
    ],

    'auth' => [
        'driver' => 'session',
        'provider' => 'users',
        'hash' => false,
    ],
],

routes/auth.php
Route::group(['middleware' => 'auth:sanctum'], function () {
    Route::post('logout', [LoginController::class, 'logout']);
});

loginController.php
class LoginController extends Controller
{
    use AuthenticatesUsers;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function validator(array $data)
    {
        //validation rules
    }

    public function login(Request $request)
    {
        if ($this->validator($request->all())->fails()) {
            $errors = $this->validator($request->all())->errors()->getMessages();
            $clientErrors = [];

            foreach ($errors as $key => $value) {
                $clientErrors[$key] = $value[0];
            }

            return $this->sendError( 'Validation error', $clientErrors, 201);
        } else {

            $credentials = [
                'email' => $request->email,
                'password' => $request->password,
            ];

            if (auth()->attempt($credentials)) {

                $user = User::where('email', $request->email)->first();

                $token = $user->createToken('auth_token')->plainTextToken;

                $response = [
                        // data
                ];

                return $this->sendResponse( 'Login successfully', $response, 200);
            } else {
                $msg = 'Invalid login';
                $clientErrors = [
                    // errors
                ];
            }

            return $this->sendError( $msg, $clientErrors, 201);
        }
    }

    public function logout(Request $request)
    {
        if (!empty($request->user())) {
            AuthController::removeToken($request);
            $request->session()->invalidate();
            $request->session()->regenerateToken();
           // Session::flush();
        }
    }
}


text:
Q: Filter Nested array Python I have an output array like this after using "json.dumps(response.json(), indent=4"
{
    "totalCount": 8,
    "hasMore": false,
    "firstIndex": 0,
    "list": [
        {
            "id": "7d5bb8asdfasdfasfdasdfasdfasdf",
            "name": "Corporate",
            "domainType": "AAAAAAAA",
            "description": "",
            "createdBy": "admin",
            "createDatetime": "2020/06/04 17:40:22",
            "parentDomainId": "8b208asdfasdfasdfasdfasdfas",
            "zoneCount": 2,
            "subDomainCount": 1,
            "administratorCount": 0,
            "apCount": 0,
            "zeroTouchStatus": true
        },

Now when I try to filter it as follows
print(results['name']) or print(results['list'][0]['name'])
I keep getting this error message:
TypeError: string indices must be integers
This starts with a dict {}, then ther are lists [] of dict {} in here.  Based on that it should work.  Appreciate any guidance.  Thank you.

A: It is clear by your data you posted that it is still in text format JSON. Convert to a python dict using json.loads()
result = json.loads(response.json())
print(results['name'])
print(results['list'][0]['name'])

A: The problem is json.dumps(response.json()). The return of this statement is a str so you cannot get items using [] notation. You can convert back it to a dict.


text:
Q: Regex to replace a string not within quotes (single or double) I have a input string

this or "that or" or 'this or that'

that should be translated to

this || "that or" || "this or that"

So the attempt is to look for an occurence of a string ( or ) within a string and replace it with another string ( || ). I have tried the following code
Pattern.compile("( or )(?:('.*?'|\".*?\"|\\S+)\\1.)*?").matcher("this or \"that or\" or 'this or that'").replaceAll(" || ")

The output is

this || "that or" || 'this || that'

The problem being that string within the single quote was also replaced.
As for the code, the style is just for an example. I would compile the pattern and reuse it when I get this to work.

A: Try this regex: -
"or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)"

It matches or which is followed by any characters followed by a certain number of pairs of " or ', followed by a any characters till the end.
String str = "this or \"that or\" or 'this or that'";
str = str.replaceAll("or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)", "||");
System.out.println(str);

Output : -
this || "that or" || 'this or that'

The above regex will also replace or, if you have a mismatch of " and '.
For e.g: -
"this or \"that or\" or \"this or that'"

It will replace or for the above strings also. If you want it not to replace in the above case, you can change the regex to: -
str = str.replaceAll("or(?=(?:[^\"']*(\"|\')[^\"']*\\1)*[^\"']*$)", "||");


text: Q: How to add overlay on the webrtc using frozen mountain icelink in iOS app I am developing a video streaming iOS app using Frozen mountain icelink library , How can I add overlays to the screen which will be broadcasted to all other peers which are connected to the same session  (i.e overlay should be reflected in realtime)


text:
Q: Many-To-One selection While programming at work, a friend presented me a very interesting case:
There is a table with wildcard values, such as "test". This register is able to find words containing 'test' in them, as it does not matter what comes before or after the word.
There is another table which holds registers with the desired text, such as 'this is a test' for example.
The regular access preference would be from the wildcard table to the text table, but this is not possible in my friend's scenario.
He actually came with a solution, but it doesn't feel it is as good as it could be.
His idea was to select every wildcard register and every text needed. Then, he would delete from the wild card table every register which did not have a matching target in the text table, as it is already correct and containing only pertinent values.
In ABAP this could be written as:
data:
     wa_wildcard   type          string,
     t_wildcards   type table of string,
     t_texts       type table of string,
     wa_text       type          string,
     lv_index      type          sy-tabix,
     lv_found      type          c.

select * from zt_texts into table t_texts. "Retrieves desired texts.
check sy-subrc is initial.

select * from zt_wildcards into table t_wildcards. "Retrieves all widlcards.
check sy-subrc is initial.

loop at t_wildcards into wa_wildcard. "Checks every Wildcard
  move lv_index to sy-tabix. "Stores the iteration index for Wildcard table.

  loop at t_texts into wa_text. "Checks if the actual wildcard matches any text retrieved.
    if wa_text cp wa_wildcard-value. "If text contain parts of the wildcard string, it matches
      move 'X' to lv_found. "Found a match, may exit the loop!
      exit.
    endif.
  endloop.

  if lv_found ne 'X'.
    delete t_wildcards index lv_index. "removes the wildcard if no match was found.
  endif.
endloop.

Since this is done in ABAP, i thought there would be a select statement capable of doing this validation process directly into the database, for the wildcard table may be too big to select everything, iterate, and process.
EDIT: The general Idea is to use the text to find appropriate wildcards for it, without testing every single wildcard with every single text. I would like to know if this is possible to be implemented in any solution, be it database-oriented, i.e in a select statement or in pure code.

A: This could be a better method depending on how many entries you expect to select.  It requires as many database accesses for ZTEXT as there are entries in ZWILDCARD, but if that's a small number, this will reduce the load.
select * from zwildcard into t_wildcards.

loop at t_wildcards into  wa_wildcard.
  select * from ztext appending table t_texts
    where value LIKE wa_wildcard.
  if sy-subrc is not initial.
    delete t_wildcards index sy-index.
  endif.
endloop.

This is assuming ZWILDCARD has a list of entries with SQL wildcards (% and _, not * and +) on either side.  If not, you'd need to add the necessary formatting at the beginning of the loop.
Also, if you only cared about t_wildcard and not t_text, the database access could be a select single, further reducing the load.


text:
Q: Problem navigating back from a fragment with a toolbar search view in my app I'm navigating from fragment A to fragment B via toolbar icon, but fragment B is having a toolbar search view and navigate up is not working. On the other app fragments navigating up is possible. What I'm missing?
I tried every post i found about the search view back button, but all it done is to collapse the search view, and what i want is to navigate to previous fragment.


text:
Q: How to plot in excel based on complex cell result In an excel spreadsheet I built a model where if I input a value in A1, I get a result in A2 and A3 that are of high interest to me.
To get the A2 and A3 results, I can't just have a formula in A2 and A3 that does the work. Because I don't use macro (I'm on Mac), I need to do some intermediary computation in other cells in order to get the end result.
So the question is : Can I somehow plot the result of A2 and A3 by A1 (X-axis)?
Or said in a different fashion, if I have a range of different value for A1 (say 1000 values). How can I compute the corresponding result A2 and A3 without having to duplicate 1000x the work I've done once?
The intermediary computation is complex to duplicate because it involves working on array and ranges which have values depending on A1. So if I wanted to get 1000 corresponding values the old fashion way, I would have to duplicate and have thousands of different arrays.... Does that make sense?
Edit:
In this example I want to plot B23 and B24 against different value of B21. Value of B21 would vary between 0 to 10 000 000 by interval of 1000.
https://drive.google.com/open?id=0BwXw25bqBHKxX3ByZG9yR2RpMEU
So to plot this, I guess the first thing to do would be to get column with all the value of B21 that I want. This is easy.
The thing I'm struggling with is how to get the 10 000 corresponding value of B23 and B24.

A: Use a Data Table (Data Tab of Ribbon/What If Analysis/Data Table...).
This feature (and it needs some practice to use it successfully) allows you to generate multiple results.
Data Tables come in two variants: one-variable and two-variable. The former allows you to see the effect of changing the value in a single input cell on an output cell - multiple versions of the input cell are defined and the Data Table provides the corresponding output cell values. The latter shows the effect on an output cell of changes to a pair of input cells.
You want to see the effect of changing B21 on B23 and B24 so you will need to use a one-variable Data Table twice: once to show the effect of changing B21 on B23 and once to show the effect of changing B21 on B24. Ensure that you use the same range of changing values for B21 in both Data Tables. Use the columns from the two Data Tables for plotting your chart.
There are plenty of tutorials, etc on Data Tables, just put Excel Data Table into a search engine.


text:
Q: Roles of parentheses in SQL Server SELECT queries? The following query returns no result and no error on SQL Server 2008 (tested on SP1), you can run it against any database, even master:
WITH computed_table (id) AS
(
    SELECT id FROM this_table_does_not_exist
)
(SELECT * FROM computed_table)
UNION
(SELECT * FROM another_table_that_does_not_exists)

On SQL Server 2005, you get an error because the tables do not exist.
You get also get an error if you remove some parentheses:
WITH computed_table (id) AS
(
    SELECT id FROM this_table_does_not_exist
)
SELECT * FROM computed_table
UNION
(SELECT * FROM another_table_that_does_not_exists)

The same kind of problems appears with real tables: on some occasions, the query does not return any result, and if you make some some slight changes, like removing a space or a carriage return, it works again...
I think that there may be a problem in the query, because the SELECT enclosed in parentheses may be interpreted as an expression instead of a subquery, as in this page. But that should at least return an error.
Am I missing something?
Edit 26/06/2010: I ran some profiling sessions, with the following results.
For the query above, the sequence of events is:

*

*Exception (Error: 208, invalid object name)

*SQL:BatchStarting

*SQL:StmtStarting

*SQL:BatchCompleted

For the query without parentheses:

*

*Exception (Error: 208)

*SQL:BatchStarting

*SQL:StmtStarting

*Exception (Error: 208)

*User Error Message (Invalid object name 'this_table_does_not _exist')

*SQL:BatchCompleted

For a working query:

*

*SQL:BatchStarting

*SQL:StmtStarting

*Showplan All

*SQL:StmtCompleted

*SQL:BatchCompleted

I also ran one of the queries with real tables that's causing me the same issue. The sequence of events is:

*

*SQL:BatchStarting

*SQL:StmtStarting

*SQL:BatchCompleted

No early "Exception" => the tables exist.
No "SQL:StmtCompleted" => it means that an error occured, I could not see any other reason why this event would not be raised.
No "Showplan All" => it means that the error occurs before (or when) the execution plan is computed. It may be caused by the combination of cte and parentheses.
I will raise the issue with Microsoft support next week.

A: So, I simplified the sql just a bit, as per my earlier comment on the original question.
WITH computed_tabled AS
(
    SELECT id FROM this_table_does_not_existd
)
(SELECT id FROM computed_tabled)

This seems to give us the same behavior.  Then I ran a trace.  Event classes :

*

*SQL:Batch Starting

*SQL:Batch Completed

*SQL:StmtStarting

*SQL:StmtCompleted

*Showplan All

*Showplan XML

What I caught was unexpected:

*

*SQL:BatchStarting

*SQL:StmtStarting

*SQL:BatchCompleted

Note: no SQL:StmtCompleted, no plans.  So, next, I go back to the capture settings, and add in every single Event Class under Errors and Warnings.  ReRun the query, and what do you know?  First caught event is:
Error: 208, Severity: 16, State: 1

Guess what 208 is?  But, the client never sees the error.
What I think is happening is that the code in the DBMS is saying - hey, they didn't ask us to return anything or do anything, so why bother?  Let's free up some resources for someone more demanding.
So I tried this piece of code:
--asdfasdf
( SELECT 1 )

Which totally blew my theory away.  The parenthesis were NOT being interpreted as an expression.  Instead, they were being interpreted as a fully query ( which is to say, the client is asking for something to be returned ) and returned a recordset with 1 column and 1 row.  But no plan - probably b/c no plan was needed, as no db objects involved.
So, to mess with my mind some more I tried this:
declare @id as integer;
;
WITH computed_table AS
(
    SELECT id FROM this_table_does_not_exist
)
select @id = (SELECT id FROM computed_table)

Which, much like removing the parenthesis, produces a User Error Message.
I say, you're not missing anything.  I think this is an MS SQL Server bug.  It certainly seems related to the cte and the parenthesis.  I tried googling for mention of it, but didn't find anything.  This will give me something to talk about at the next local PASS meeting.  Sorry all I have to add to the situation is confusion. If I learn something, I'll be sure and post it here!

Update : 2010-06-26 10:09 CST
I went to Microsoft Connect in an attempt to find this listed as an issue. I was unable to find something around cte 208 or cte invalid object.  Honestly, I don't know of another bug listing site for sql server which one could check.  I also tried searching Microsoft Support and, again, Google.

A: From the microsoft doc https://learn.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql?view=sql-server-ver15, it looks like select with parentheses is only a special case in union parser. I doubt you can use it as a regular select.


text:
Q: MYSQL: inserting error MYSQL Problem inserting Certain type of Text
when i try to insert this for example:
INSERT INTO `Attacks_key`
  (`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`)
    VALUES
  ('111', 'REQUEST', ' mysql_real_escape ', '222', 'xss, csrf, id, rfe, lfi');

its inserted But when I try to insert this :
INSERT INTO `Attacks_key`
 (`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`)
   VALUES
 ('111', 'REQUEST', 'mysql_real_escape_string($_POST['username']); ', '222', 'xss, csrf, id, rfe, lfi');

MYSQL display this message :
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'username']); ', '222', 'xss, csrf, id, rfe, lfi')' at line 1
and this is my php code
$user="root";
$password="*";
$database="*";
mysql_connect(localhost,$user,$password);
@mysql_select_db($database) or die( "Unable to select database");
$sql = "SELECT `Key_id` FROM `Event` ORDER BY `Key_id` DESC LIMIT 1";
$result =mysql_query($sql);
$row = mysql_fetch_assoc($result);
$EventKey= $row['Key_id'];
$query="INSERT INTO `PHPLOGS`.`Attacks_key` (`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`) VALUES ('$EventKey', '$getname', '$getvalue', '$getimpec', '$gettags');";
mysql_query($query);
mysql_close();

and the input 'mysql_real_escape_string($_POST['username']);  from the user
Can someone help
thanks

A: Try
$query = sprintf("INSERT INTO Attacks_key (Event_Key ,Variable ,Value ,Impact ,Tags) VALUES ('111', 'REQUEST', '%s', '222', 'xss, csrf, id, rfe, lfi');",
            mysql_real_escape_string($_POST['username']));
There's a conflict of ' in that part of the statement with 'username'
Have a look at mysql_real_escape_string

A: If you're inserting mysql_real_escape_string($_POST['username']); literally, then escape the single quotes.
INSERT INTO `Attacks_key`
 (`Event_Key` ,`Variable` ,`Value` ,`Impact` ,`Tags`)
   VALUES
 ('111', 'REQUEST', 'mysql_real_escape_string($_POST[\'username\']); ', '222', 'xss, csrf, id, rfe, lfi');

A: As you should really really switch to PDO instead of the deprecated mysql_ functions you could use PDO::quote

PDO::quote() places quotes around the input string (if required) and
  escapes special characters within the input string, using a quoting
  style appropriate to the underlying driver.

However, the preferred way of doing queries is by using prepared queries, and in that case you wouldn't have the quote escaping problem anyways.  Again quoting from the php manual page for PDO:;quote

If you are using this function to build SQL statements, you are
  strongly recommended to use PDO::prepare() to prepare SQL statements
  with bound parameters instead of using PDO::quote() to interpolate
  user input into an SQL statement. Prepared statements with bound
  parameters are not only more portable, more convenient, immune to SQL
  injection, but are often much faster to execute than interpolated
  queries, as both the server and client side can cache a compiled form
  of the query.

If for whatever reason PDO isn't an option, there's mysqli_real_escape_string with a similar functionalty.


text:
Q: Regex to find missing ConfigureAwait I have a specific pattern that I want to search for in Visual Studio.
Basically, I want to search for lines that contains await, but are missing ConfigureAwait at the end of the statement.
I have some patterns that works in regex-testers such as regex101.com, but I can't get these patterns to work in Visual Studio search. For example, the pattern (?s)^(.)*(await)((?!ConfigureAwait).)*(.)?(;).
What I am doing wrong?
Edit - I want to find lines in my project such as
await DoSomeCoolThings(x, y); (i.e. missing the ConfigureAwait(...).)
but I don't want to get a match for lines such as:
await DoSomeCoolThings(x, y).ConfigureAwait(false);

A: If the order of await and ConfigureAwait does not matter, then you can use
(?=.*\bawait\b)(?!.*\bConfigureAwait\b)

otherwise, if you consider that ConfigureAwait should come after await, you can use
(?=.*\bawait\b(?!.*\bConfigureAwait\b))

Efficient Solution
(?=\bawait\b(?!.*\bConfigureAwait\b))

A: To match these lines with await but without ConfigureAwait after it, you can use a  simpler negative lookahead based regex:
.*\bawait\b(?!.*\bConfigureAwait\b).*

The pattern matches any non-newline symbols (.*) followed with a whole word await (as \b are word boundaries) and then a check is performed to make sure there is no whole word ConfigureAwait somewhere after await (with a lookahead (?!.*\bConfigureAwait\b)), and then the rest of line is matched with .*.

Since await is usually close to the left side of the string, best is to use a lazy dot matching at the beginning:
.*?\bawait\b(?!.*\bConfigureAwait\b).*

A: I do not think we should be constrained to a single line, as more complicated statements can be split up into multiple lines. Also, the solution should preferably be fast.
To that effect, we can either use the Resharper plugin "ConfigureAwait Checker", or the following regex:
\bawait\b(?![^;]*ConfigureAwait)[^;]*;

The idea is to find the word "await", and then read the entire statement until its semicolon ;, matching only if the word "ConfigureAwait" is missing in that text. More specifically:

*

*\bawait\b: Whole word "await".

*(?!...): Negative lookahead that we will use to exclude matches that already have ConfigureAwait.

*

*[^;]*ConfigureAwait: The word "ConfigureAwait", preceded by any number of characters that are not the semicolon.

*[^;]*: Any number of characters that are not the semicolon.

*The semicolon.

I got a few minor false positives where the statement contains a query string (with a semicolon) or a lambda (with a semicolon). They were so easily ignored that I did not find it worthwhile to further complicate the regex.