text:
Q: install and enabling vim-youcompleteme on Ubuntu 14.10 I did follow instructions for installing vim-youcompleteme.
I searched for similar questions and answers, but still not helping me.
I have clean install of Ubuntu 14.10. Then I installed vim 7.4, vim-youcompleteme and vim-addon-manager. Then run vam install youcompleteme. It was successful.
But, I still dont see the auto completion popup when I edit cpp, or c code.
There is another way of installing youcompleteme using Vundu and doing ./install.sh with parameters, also changes .vimrc.
Since I am using vim-youcompleteme package, I assume these steps already done during installation of vim-youcomplateme package from Ubuntu.
Could someone shed light on this area, please?
Thanks


text:
Q: Prove that $ B_{n}(x)=\sum^{\infty}_{k=0} \dfrac{(-1)^k}{k!(n+k)!} \left(\dfrac{x}{2}\right)^{n+2k}$ converges uniformly. Let $n\geq 0,$ be a fixed. The Bessel function of order $n$ is the function defined by
\begin{align} B_{n}(x):=\sum^{\infty}_{k=0} \dfrac{(-1)^k}{k!(n+k)!} \left(\dfrac{x}{2}\right)^{n+2k} .\end{align}
I want to prove that $B_{n}(x)$ converges uniformly on any closed interval $[a,b]\subseteq \Bbb{R}.$
MY WORK
Let $[a,b]\subseteq \Bbb{R}$ be arbitrary, $x\in [a,b]$ and $n\in \Bbb{N}$ be fixed. Then,
\begin{align} \left| \dfrac{(-1)^k}{k!(n+k)!} \left(\dfrac{x}{2}\right)^{n+2k}\right|\leq  \left( \dfrac{\left|  x\right|} {2}\right)^{n+2k}\leq   \left(\dfrac{c}{2}\right)^{n+2k}.\end{align}
where $c=\max\{|a|,|b|\}.$ Now,
\begin{align} \sum^{\infty}_{k=0} \left(\dfrac{c}{2}\right)^{n+2k} =\left(\dfrac{c}{2}\right)^{n}\sum^{\infty}_{k=0} \left(\dfrac{c}{2}\right)^{2k} =\left(\dfrac{c}{2}\right)^{n} \left(\dfrac{4}{4-c^2}\right)<\infty,\;\;\text{where}\;\;c<2.\end{align}
Hence,
\begin{align} B_{n}(x):=\sum^{\infty}_{k=0} \dfrac{(-1)^k}{k!(n+k)!} \left(\dfrac{x}{2}\right)^{n+2k} .\end{align}
converges uniformly on $[a,b]\subseteq \Bbb{R}$ with $c<2.$
QUESTION:
The question asks for a proof for any closed interval of $ \Bbb{R}.$ With what I have, it only works when $c<2.$ What happens when $c\geq 2$? Or I'm I missing something in the proof?

A: No, your proof surely does not work for all intervals $[a,b]$ of $\mathbb R$. It only works for those intervals $[a,b]$ such that $\lvert a\rvert,\lvert b\rvert<2$.

A: Happy New Year! Credits to Jakobian
\begin{align} \left| \dfrac{(-1)^k}{k!(n+k)!} \left(\dfrac{x}{2}\right)^{n+2k}\right|\leq  \dfrac{1} {k!}\left( \dfrac{\left|  x\right|} {2}\right)^{n+2k}\leq   \dfrac{1} {k!}\left(\dfrac{c}{2}\right)^{n+2k}.\end{align}
Since,
\begin{align} \lim\limits_{k\to\infty}\left|\dfrac{k!} {(k+1)!}\left(\dfrac{c}{2}\right)^{n+2k+2} \left(\dfrac{2}{c}\right)^{n+2k} \right|&=\lim\limits_{k\to\infty}\left|\dfrac{1} {(k+1)}\left(\dfrac{c}{2}\right)^{2}  \right|\\&=\dfrac{c^2}{4}\lim\limits_{k\to\infty}\dfrac{1} {(k+1)} \\&=0<1\end{align}
Thus, $\sum^{\infty}_{k=0}    \dfrac{1} {k!}\left(\dfrac{c}{2}\right)^{n+2k}$ converges by D'Alembert's Ratio test and so,
\begin{align} B_{n}(x):=\sum^{\infty}_{k=0} \dfrac{(-1)^k}{k!(n+k)!} \left(\dfrac{x}{2}\right)^{n+2k} .\end{align}
converges uniformly on any $[a,b]\subseteq \Bbb{R}$

redpajama_set_name: RedPajamaStackExchange


text:
Q: onclick function requires double click because of class assignment delay The title says it all. I got a list of LI elements. When clicked on navigation the active li gets a class 'current' but this takes a second.
But when I use my code I need to click on the nav then the li opens and I need to click again to make the code register.
The place of the videos cannot be hardcoded! It needs to be dynamic.
(function($) {
$(document).ready(function(){
  $('video').each(function() {
      $(this).get(0).pause();
  });
  $('.slides').children('li').addClass('test');
});

$(document).on('click','span',function(){

    if ( $('li').hasClass('current') ) {
      $('li.test').find('video').each(function() {
          $(this).get(0).pause();
      });
      $('li.current.test').find('video').each(function() {
          $(this).get(0).play();
      });

    }
});
})(jQuery);

http://codepen.io/hennysmafter/pen/aNrVKG?editors=1010
Unfortunately I won't be available for the next hour or so but will be back after that! Everyone thank you for helping.

A: I found what is causing the issue :
You are playing the elements whose parent has ".current" class when a span is clicked.
But when you click an element, it et the ".show" class, and the previously selected span get the ".hide" class AND keeps the ".current" class, until the animation is finished (then the ".show" & ".hide" class are removed and the ".current" class switch elements).
One solution is changing the selectors like this :
$(document).on('click','span',function(){
      console.log('the if is running');
      $('.current, .hide').find('video').each(function() {
          $(this).get(0).pause();
      });
      $('.show').find('video').each(function() {
          $(this).get(0).play();
      });

});

By doing this, whenever a span is clicked, you pause the element whose parents have the ".hide" class, and play the ones whose parents have the ".show" class.
Another solution should be creating an event when a class is applied (See jQuery - Fire event if CSS class changed).


text:
Q: BroadcastReceiver for when sent SMS messages are deleted? Is there a broadcast event for when the user deletes everything inside the phone's sent SMS folder? I need to be able to trigger an action when the user clears her sent box.
If not the entire sent box, at least the messages individually--that is, do something when this particular sent message has been deleted.

A: I had to change my approach to this problem in my app and no longer need a listener for when SMS messages are deleted, but it might help to:

*

*Create a ContentObserver that listens to the Uri content:\\sms.

*Do something from the ContentObserver when onChange() is executed. For example, you might want to traverse all the messages in the inbox (via Cursor) and check which messages are missing. That of course requires you to have an archive of messages that were present in a previous check.


text:
Q: changing App_Start to AppStart I have set up a new MVC 4 web application. I am currently running source code anaylsis against the project and getting the following error:
CA1707  Identifiers should not contain underscores

The reason for this is because of the namespace "App_Start" due to the App_Start folder name. Are there any issues with renaming the folder to "AppStart"? This will mean all my rules are passed.

A: I would suppress that rule for that particular namespace rather than rename it. Create a GlobalSuppressions.cs file in your web project root, and add this:
using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("Microsoft.Naming",
                           "CA1707:IdentifiersShouldNotContainUnderscores",
                           Scope = "namespace",
                           Target = "<namespace>.App_Start",
                           Justification = "This is an infrastructure namespace")]


text:
Q: как обрезать текст в одну строку? подскажите пожалуйста, как вывести только первую строку и остальной текст скрыть многоточием но при этом не ограничивать фиксированной шириной, а использовать 100% от ширины блока?
overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: block;
  max-width: 444px; // такой вариант не подходит, так как на телефоне блок тенется и получается что обрезаем текст по середине

A:

div {
  width: 250px
}

p {
font-size: 0px;
padding-right: 10px;
position: relative;
}

p:after {
  content: '...';
  font-size: 24px;
  position: absolute;
  right: 0;
  bottom: 0;
}

p:first-line {
  font-size: 24px;

  }

b h bh bh d dsfh dfh df hdfkh kfdhhhhfd fhd fd fdhb fd hfdh bfd hbfdbh vfbhj jhbjh b jhb jhbhbf hjzf dz zzbz bhj zbhjzhjbzhjbfdzhjb hjb bhj fvbhjf jhb jhb jhbfz jhbf bjh zhjz z dz dfz hdhjbhjbfjhzhjb hjb zbhjhjbz hjbhjb hjb bh jb hjhbj hbjhbjhbjbzz df bh f z z z    hbj     bhf bhjzfhbjvhjbfvhhbjvfd  b

A: То что закоменчено может вам понадобиться, если захотите троеточие после 2 строк или трех и т.д.

.text-wrapper {
  width: 100%;
  border: 1px solid #000;
  display: block;
  box-sizing: border-box;
}
p {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  // white-space: initial;
  // display: -webkit-box;
  // -webkit-box-orient: vertical;
  // -webkit-line-clamp: 2;
}

Lorem Ipsum - это текст-"рыба", часто используемый в печати и вэб-дизайне. Lorem Ipsum является стандартной "рыбой" для текстов на латинице с начала XVI века. В то время некий безымянный печатник создал большую коллекцию размеров и форм шрифтов, используя Lorem Ipsum для распечатки образцов.


text:
Q: Getting empty answer when I should get nothing I'm working on a C# program that uses a SQL Server Compact database. I have a query where I want to select the highest number in a specific field that looks like this:
SELECT MAX(nr2) FROM TABLE WHERE nr1 = '10'

This works as inteneded when there is a row where nr1 is 10. But I would expect to not get an answer when that row doesn't exist, but instead I get an empty field. So in my C# code I have:
text = result[0].ToString();

When I get a value from my SQL query the string contains a number and when the specified row doesn't exist I get an empty string.
This isn't really a big problem but I would be able to do the following check:
if (result.Count > 0)

Instead of:
if (result[0].ToString() == "")

which I have to do at the moment since count is always larger than 0.

A: Talk about using a sledgehammer to crack a nut, but...
I don't test it with C# code, but in SQL Server Management Studio, if you run...
SELECT MAX(nr2) FROM TABLE WHERE nr1 = '10' HAVING MAX(nr2) IS NOT NULL

, the result is an empty collection, not a collection with one null (or empty) element.
NOTE: My answer is based on this SO Answer. It seems that MAX and COUNT SQL functions returns always a single row collection.

A: That SQL statement will always return a result... if the base query returns no result then the value of max() is null !
if you are using ADO.NEt, you could use ExecuteScalar, here an example :
private int GetIDNum()
{
    SqlConnection connection = new SqlConnection("connectionstring");
    using(SqlCommand command = new SqlCommand("SELECT MAX(nr2) FROM TABLE WHERE nr1 = '10'", connection))
    {
        try
        {
            connection.Open();

            object result = command.ExecuteScalar();

            if( result != null && result != DBNull.Value )
            {
                return Convert.ToInt32( result );
            }
            else
            {
                return 0;
            }
        }
        finally
        {
            connection.Close();
        }
    }
}


text:
Q: How can i fix Inline Assembly in Code blocks? What did i did wrong?
**#include <stdio.h>
#include <stdlib.h>
int x,y,vysled=0;
int main()
{
    asm(".intel_syntax noprefix \n"
       "mov eax,_x              \n"
       "add eax,_y              \n"
       "mov _vysled,eax         \n"
       ".att_syntax             \n");
    printf("%d + %d = %d",x,y,vysled);
    return 0;
}**

building log prints Undefined reference to _x,_y.


text:
Q: Implement const and non-const coeffs() operator for a concatenation of Eigen::Vectors? I am working on a project where I need to combine two Eigen-types and "mimic" them as to behave like one single Eigen type. In particular, there is a requirement for having a class holding two distinct Eigen vectors as member variables, like the one below.
The catch is, when being passed to an algorithm, this class must behave like a single Eigen-object, which means that I need to mimic some of Eigens API.
Due to memory requirements, it is not a solution to simply copy the two Eigen vectors into a larger Eigen-type and work with that one instead.
For many Eigen matrix methods this combined class is easily realizable, but I am missing a solution for how to realize the const- and non-const getters for the individual coefficients, returned by reference.
In the end, I would like the following to be feasible:
class Combined{
public:
 Combined(const Eigen::Vector3d a, const Eigen::Vector3d b): vec1_(a), vec2_(b){}

 const Eigen::Vector6d& coeffs() const {
    // how to implement this?
 }

 Eigen::Vector6d& coeffs() {
    // how to implement this?
 }

 // some other member functions not related to Eigen...
 // ...

private:
  Eigen::Vector3d vec1_;
  Eigen::Vector3d vec2_;
};

int main(){

 Eigen::Vector3d a = Eigen::Vector3d::Random();
 Eigen::Vector3d b = Eigen::Vector3d::Random();

 Combined t (a, b);

 // the const getters should exist:
 Eigen::Vector6d r;
 r= t.coeffs();

 // the non-const getters should allow modification:
 t.coeffs()(0) = 0; // assign some value.

 return 0;
}

Any ideas about how to achieve such an implementation would be highly appreciated!


text:
Q: How to use custom HTTP methods in Paw? I can't find way to perform some types of requests (like REPORT and PROPFIND, that used in webDav protocol). In general, how can I send a request with an arbitrary method name?

A: Go to menu Requests > Set Custom HTTP Method (or press ⌥⌘M) and enter whichever method you need.


text:
Q: If string contains text from list, write matched text to cell I'm working on a large Google spreadsheet with key phrases, strings of text, in column A. I want to search column A based on a list of keywords that live in another sheet. When a keyword matches a word in a string in column A, I want to print that word in an adjacent cell to column A.
Here's a simple spreadsheet to work with that I think demonstrates what I'm trying to do.
https://docs.google.com/spreadsheets/d/1tNcroABVP0UdP4CiJldxLZgdrJF33TYT4mL1DZJfD1Q/edit?usp=sharing

A:
I want to print that word in an adjacent cell to column A

=ARRAYFORMULA(IFNA(REGEXEXTRACT(A2:A, LOWER(TEXTJOIN("|", 1, 'KEYWORD LIST'!A2:A)))))

A: Try with this (put at B2):
=arrayformula(if(ISNUMBER(find(
        transpose({'KEYWORD LIST'!$A$2:$A$6}),A2:A6)),
        transpose({'KEYWORD LIST'!$A$2:$A$6}),""))


text:
Q: ExtJS Content sliding/scrolling like Sencha Touch (ExtJS Drag Scroll) How can I achieve effect of sliding/scrolling content of Ext.panel.Panel/Ext.view.View or any other container like in mobile applications or Sencha Touch?
Something like drag scroll with a mouse (like PDF documents).
Can someone give me any hint, code snippet, or just tell me where to start?
Best regards

A: RahulSingla integrated iScroll with extjs to achieve this functionality here. It's with extjs3 however. As of today, I need this same thing in extjs4 for a grid panel. So I will try something along these lines but with extjs scroll methods instead of iScroll. I'll update if I get anything working.
UPDATE:
Done. (for what I needed) It turns out to be pretty straightforward to add drag scrolling from a listener on the grid panel, wasn't much coding needed:
listeners: {
    'itemmousedown': function(view, rec, item, idx, event) {

        var startX = event.getX();
        var startY = event.getY();

        var grid = view.up('gridpanel');
        var div = grid.getEl();
        var body = Ext.getBody();

        body.setStyle('cursor','-moz-grabbing'); //doesn't work in 4.0.7+

        div.on('mousemove', function(e) {
            x = e.getX(), y = e.getY()
            grid.scrollByDeltaX(startX - x);
            grid.scrollByDeltaY(startY - y);
            startX = x
            startY = y
        });

        body.on('mouseup', function(e){
            body.setStyle('cursor','default'); //doesn't work in 4.0.7+
            div.removeAllListeners();
            body.removeAllListeners();
        });

        body.on('mouseleave', function(e, tgt){
            body.setStyle('cursor','default'); //doesn't work in 4.0.7+
            div.removeAllListeners();
            body.removeAllListeners();
        });
    }
}

I've only tested this on FF because that is all we use on our intranet. I'm not sure if IE has the mousemove event .getX() or .getY() functions so that might need to be tweaked.
For other panels (something other than a grid panel) you could probably just replace the itemmousedown listener with just a mousedown listener to have the same functionality.


text:
Q: Add role numbers in table dynamically using angular js I have created one simple table,for this table am getting data from controller.Here I am trying to add S.no , But I don't know how to do it.
For now am just displaying {{x.id}} as s.no from backend,I dont want to display {{x.id}} as serial number but I need to pass it inside update method.
Can anyone teach me how to add serial numbers in angular?
HTML:

                            S.No
                            Role Name
                            Action

                            {{x.Id}}

                                {{x.name}}
                                <input type="text" ng-show="editMode" ng-model="x.name" />

SCRIPT:

A: Easiest Solution:
You can simply add {{$index}} in your td element to do this.

                    {{$index + 1}}

                        {{x.name}}
                        <input type="text" ng-show="editMode" ng-model="x.name" />

Alternative Solution:
Or you can push a serial no key into your array likewise.
$http.post("/Admin/getRolesList")
.then(function (response) {
 $scope.roleList = response.data;
 for(var i=0;i<$scope.roleList.length;i++)
  $scope.roleList[i].serialNo = i+1;
            });

And populate it in the UI like

                            {{x.serialNo}}

                                {{x.name}}
                                <input type="text" ng-show="editMode" ng-model="x.name" />


text:
Q: Why does this AES encryption on an iPad and decryption in PHP fail? I have an iPad application that transmits encrypted information to a PHP-based website, but I'm having difficulties in properly decrypting this information.  I use the following code for the PHP-side decryption:
//Decryption function

function mc_decrypt($decrypt, $key, $iv)
{
    $decoded = base64_decode($decrypt);
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
    mcrypt_generic_init($td, $key, $iv);
    $decrypted = mdecrypt_generic($td, $decoded);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return trim($decrypted);
}

and this Objective-C code in my iPad application:
#import <CommonCrypto/CommonCryptor.h>

@implementation NSData (AES256)

- (NSData *)AES256EncryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

- (NSData *)AES256DecryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                     keyPtr, kCCKeySizeAES256,
                                     NULL /* initialization vector (optional) */,
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesDecrypted);

    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

@end

Why am I seeing data corruption when trying to decrypt data encoded on the iPad and decrypted on the PHP side?

A: Check the key that you're using. In PHP the MCRYPT_RIJNDAEL_128 _256 etc constants do not represent the key strength, but rather the block size being used.
To get 128-bit encryption with PHP you want to use a key that is 16 bytes long. For 256 you need 32 bytes and so on and so forth.
Both you PHP and C code look correct to me. Make sure the key is being used correctly in both cases.
As another thought. It looks like you're using PKCS#7 padding in C. I don't believe PHP is designed to work with that padding by default. If memory serves me, I believe the Mcrypt functions use null padding.
Lastly check your initialization vector in PHP. I noticed you're not using one in your C code which means you should not be accepting an $iv variable in PHP. That should be passed as NULL into the mcrypt functions (but this is highly discouraged).
What you should do instead is randomize an IV in your C code (where the data is being encrypted) and then send the IV along with the encrypted data. You can detect the size of the IV for the algorithm being used and split it off the front of the encrypted data to then use to populate your PHP side of things. This further secures your encryption for you.

A: please refere to this discussion for better usage AES encrypt/decrypt
AES with CommonCrypto uses too much memory - Objective-C


text:
Q: How to find the error returned by read()? I am reading data sent by the parent process using pipe.
Parent process close the read end and write data on the write end of pipe. Similarly, child closes write end and read data from read end.
But in my case, read returned the "-1" which is error value.
How should I find that, which error(like EAGAIN, EBADF, EIO ) has been occurred in read call?
Thanks

A:
How should i found that, which error(like EAGAIN, EBADF, EIO ) has
  been occurred in read call?

Print errno. An even better option is to do a perror, right after the call.
if (read(...) < 0)
    perror("read");

Or use strerror if you need to get the message yourself:
printf("%s\n", strerror(errno));

Note you'll need to #include <errno.h> if you use errno directly.

A: If you use linux the following code will print a related error message as a string:
printf("%s", strerror(errno));

A: A non-portable glibc extension, try simply:  printf( "%m" );

(Glibc extension; supported by uClibc and musl.)  Print output of strerror(errno).  No argument is required.


text:
Q: error while saving large matrix using scipy.io.savemat i want to save a large matrix of 20Gb in matlab(.mat) format using scipy.io.savemat function.While i am saving at that time it gives me error as follow:
error is:
scipy.io.savemat matrix too large to save with Matlab 5 format
My code is
 scipy.io.savemat('output.mat',mdict={'data':data})

I hope experts may give some suggestion to overcome the above problem.Thanks in advance.

A: Yes, I agree with @hpaulj. I think there is no other way than saving it in smaller chunks than 20GB... Is that at all possible for you? Maybe you can orient your solution on the layout of your data-structure, i.e. if it's a 3-dimensional matrix saving slices along the 3rd axis.


text:
Q: No symbolication for crash files with Xcode 7.3.1 I am not getting a symbolicated crash file using Xcode 7.3.1. My current version of the app never has symbols, however an older version of the app seems OK and the crash file is symbolicated.
I have tried to manually re-symbolicate by dragging it onto a device as described in this SO answer.
I tried to manually use the symbolicatecrash utility as described by this SO Answer.
I have confirmed that the dSYM file exists in the archive and am using it in both of the above manual attempts to rebuild the symbols. Any idea what I have missed?

A: Some of the crash files we received from our customers are corrupt. Using Apple's instructions Getting Crash Logs Directly From a Device Without Xcode, the customer copied the crash log and pasted it into email.
Something along the way corrupted the crash file though, injecting \n characters in somewhat random spots. We manually fixed the corrupted crash file by comparing it to an example from our system and symbolication worked.
Note the incorrect new line characters in the corrupted examples below:
Corrupt:
Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0:
0   libsystem_kernel.dylib
0x0000000185535188 0x185534000 + 4488
1   libsystem_kernel.dylib
0x0000000185534ff8 0x185534000 + 4088
2   CoreFoundation
0x00000001865325d0 0x186455000 + 906704

Should be:
Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0:
0   libsystem_kernel.dylib          0x0000000185535188 0x185534000 + 4488
1   libsystem_kernel.dylib          0x0000000185534ff8 0x185534000 + 4088
2   CoreFoundation                  0x00000001865325d0 0x186455000 + 906704

Corrupt:
Thread 12 crashed with ARM Thread State (64-bit):
    x0: 0x0000000109020010  x1: 0x0000000109020020  x2: 0x0000000104f5c000  x3:
0xffffffffffff63ff
    x4: 0x0000000000000001  x5: 0x0000000000000001  x6: 0x0000000108f84010  x7:
0x0000000000000000
    x8: 0x0000200000000000  x9: 0x0000000000000000  x10: 0x0000000000000002  x11:
0x0000000174c4bb28

Should be:
Thread 12 crashed with ARM Thread State (64-bit):
    x0: 0x0000000109020010  x1: 0x0000000109020020  x2: 0x0000000104f5c000  x3: 0xffffffffffff63ff
    x4: 0x0000000000000001  x5: 0x0000000000000001  x6: 0x0000000108f84010  x7: 0x0000000000000000
    x8: 0x0000200000000000  x9: 0x0000000000000000  x10: 0x0000000000000002  x11: 0x0000000174c4bb28

Corrupt:
Binary Images:
0x100910000 - 0x10093ffff dyld arm64  <f54ed85a94253887886a8028e20ed8ba> /usr/lib/dyld
0x188638000 - 0x188639fff libSystem.B.dylib arm64  <1b4d75209f4a37969a9575de48d48668>
/usr/lib/libSystem.B.dylib
0x18863a000 - 0x18868ffff libc++.1.dylib arm64  <b2db8b1d09283b7bafe1b2933adc5dfd>
/usr/lib/libc++.1.dylib

Should be:
Binary Images:
0x100910000 - 0x10093ffff dyld arm64  <f54ed85a94253887886a8028e20ed8ba> /usr/lib/dyld
0x188638000 - 0x188639fff libSystem.B.dylib arm64  <1b4d75209f4a37969a9575de48d48668> /usr/lib/libSystem.B.dylib
0x18863a000 - 0x18868ffff libc++.1.dylib arm64  <b2db8b1d09283b7bafe1b2933adc5dfd> /usr/lib/libc++.1.dylib


text:
Q: Add new variable to data object in cds toolbox I'd like to compute the daily climatology and standard deviation of a variable (in this case pressure on two levels).
I'm able to do this, but currently can't create a single data object which I can download as a netcdf.
My code currently outputs a data object area_ave_c which is the climatology, and area_ave_s which has the standard deviations.
I can get the function to return either one of these objects, but ideally I would like to merge them and return one data object (downloaded as a netcdf) which contains both variables.
import cdstoolbox as ct

@ct.application(title='Retrieve Data')
@ct.output.download()

def retrieve_sample_data():
    data = ct.catalogue.retrieve(
        'reanalysis-era5-pressure-levels',
        {
            'product_type': 'reanalysis',
            'pressure_level': [
                '1','2',
            ],
            'year': [            '1979', '1980', '1981'
                    ],

            'month': [
                '01','02','12',
            ],
            'day': [
            '01', '02', '03',
            '04', '05', '06',
            ],
            'time': [
                '00:00',
            ],
            "grid": [1, 1],
            "area":[90,-180,60,180],
        }
    )

    climatology = ct.climate.climatology_mean(data,frequency='dayofyear')
    std_deviation = ct.climate.climatology_std(data,frequency='dayofyear')

    area_ave_c = ct.geo.spatial_average(climatology)
    area_ave_s = ct.geo.spatial_average(std_deviation)

    return (area_ave_s, area_ave_c)

The return line throws a bug currently, but I would like to download both data objects and running the code twice to output them sequentially is wasteful (as it gets all the data twice).

A: It turns out that you can return two objects from the retrieve_sample_data() function, and you download them by just calling ct.output.download() twice in the preamble before the function. So my code now reads:
import cdstoolbox as ct

@ct.application(title='Retrieve Data')

@ct.output.download()
@ct.output.download()

def retrieve_sample_data():
etc etc


text:
Q: joining two tables with a third table I wasn't sure what to put into the title for this...please read on...
I have a table of events with 3 days per event
eventID dayID
1       1
1       2
1       3
2       1
2       2
2       3

I also have a number of cars available for the event
carID regNum
1     fg12 bfr
2     gh34 vbn
3     kl56 thg
4     lm32 tfx

I would like to have certain cars available for certain events, for example carIDs 1,2 and 3 might be available for eventID 1 but only carID 4 is available for event 2.
I am unsure how to join these tables together.
I am looking at another table which defines which cars are available to which event for example
eventID carID
1       1
1       2
1       3
2       4

but I can't work out how to join these 3 tables together to get the car list for event1 for example.
Any pointers gratefully received!

A: SELECT e.id, c.carID, c.regNum
FROM tblEvents e
JOIN tblEventCars ec ON ec.eventID = e.eventID
JOIN tblCars c ON c.carID = ec.carID
GROUP BY e.id, c.carID

A: Junction tables are the classic solution for modeling a many-to-many relationship in an RDBMS.
You do not need to join three tables to get cars for event1 - two tables is enough:
select *
from Cars c
join CarEvent e on e.CarId = c.CarId
where e.EventId = 1

If you need the event name, you need to join the event table as well:
select *
from Cars c
join CarEvent ce on ce.CarId = c.CarId
join Event e on e.EventId = ce.EventId
where e.EventName = 'Event1'


text: Q: From which class category filter is added to the filter groups used for aggregation : magento 2 layered navigation From which class category filter is added to the filter groups used for aggregation : magento 2 layered navigation. The aggregation and search classes are used for getting the count of products in each filter in layered navigation. But when the category filter is added to the group of filters which is later used by the search Class.


text:
Q: Look for several values in several value in SQL Here is the rather particular problem :
 id |   column_num   |
 ---|----------------|
   1|  5,12,64,7,78  |
   2|  5,53,7,6      |
   3|  94,78,32,27   |

I need to find lines having the values : 12, 7, 78
I need to look for several values corresponding to a cell SQL.
I use MySQL. You have an idea?
Thank you

A: Alright, I have come out the solution and hope this will help you.

Note: You may normalize the query by yourself as I just share my
  concept on this problem.

Query as below :-
CREATE TABLE table1
(
    id int,
    column_num varchar (max)
)

INSERT INTO table1 (id, column_num) VALUES
(1, '5,12,64,7,78'),
(2, '5,53,7,6'),
(3, '94,78,32,27'),
(4, '1,74,32,12,78')

CREATE VIEW vSeperate_Num AS
WITH tmp(id, num, column_num) AS
(
    SELECT id, LEFT(column_num, CHARINDEX(',',column_num+',')-1), STUFF(column_num, 1, CHARINDEX(',',column_num+','), '')
    FROM table1
    UNION ALL
    SELECT id, LEFT(column_num, CHARINDEX(',',column_num+',')-1), STUFF(column_num, 1, CHARINDEX(',',column_num+','), '')
    FROM tmp
    WHERE column_num > ''
)
SELECT id, num
FROM tmp

;WITH Contain_Selected_Num AS
(
    SELECT *
    FROM
    (
        SELECT id, num
        FROM vSeperate_Num
    ) AS pvt
    PIVOT
    (
        COUNT(num)
        FOR num IN ( [12], [7], [78] )
    ) AS pvt
)
SELECT *
FROM table1
WHERE id IN
(
    SELECT id
    FROM Contain_Selected_Num
    WHERE [12] > 0 AND [7] > 0 AND [78] > 0
)

Thank you. :)

A: At least one to match, try:
select * From table_name where
column_num = '12' or column_num like '%,12,%' or column_num like '%,12' or column_num like '12,%'
union
select * From table_name where
column_num = '7' or column_num like '%,7,%' or column_num like '%,7' or column_num like '7,%'
union
select * From table_name where
column_num = '78' or column_num like '%,78,%' or column_num like '%,78' or column_num like '78,%'

Have all three values, try this SQL:
select * From table_name where (column_num = '12' or column_num like '%,12,%' or column_num like '%,12' or column_num like '12,%')
and (column_num = '7' or column_num like '%,7,%' or column_num like '%,7' or column_num like '7,%')
and (column_num = '78' or column_num like '%,78,%' or column_num like '%,78' or column_num like '78,%')

A: You can try the following:
Add a , to the start and end of each string, i.e. 5,12,64,7,78 -> ,5,12,64,7,78,
Then you can apply MySQL's locate() function for every number.
select id, column_num from (
select id, column_num,
       locate(',12,', column_num) as m12,
       locate(',7,', column_num) as m7,
       locate(',78,', column_num) as m78
from your_table
) a
where m12 > 0 and m7 > 0 and m78 > 0;

If a particular number is not in the string, the result of locate will be 0, otherwise it will be the position in the string. In an outer query you can then check for this in a where statement.
The where statement can easily be adjusted according to your need, e.g. if you need a match of all three numbers or at least one.

A: Thank you for your answers.
I have to find a solution via the function FIND_IN_SET by curling with the PHP.
$_POST['test_ids'] = [12,7,78];

if (!empty($_POST['test_ids'])) {
    $filter .= ' AND (';
    $i = 0;
    foreach ($_POST['test_ids'] as $id) {
        $filter .= ($i > 0) ? ' OR ' : '';
        $filter .= ' FIND_IN_SET(\'' . $id . '\', column_num) ';
        $i++;
    }
    $filter .= ') ';
}


text:
Q: object::method() must be compatible with that of objectAbstract::method() - pass parameter = value? I am fairly new to PHP OOP and I am getting an error.
objectForm::addMessage() must be compatible with that of objectAbstractForm::addMessage() in /www/form/Form.php on line xx
I have seen this a few times where the method parameters are like $var1, $var2 = false (or null) and for whatever reason I get "must be compatible with that of X::Y()"
public function addMessage($message, $messageType = 'info')
{
    if (!in_array($message, $this->_messages)) {
        if ('info' == $messageType) {
            $this->_messages[] = $message;
        } else {
            $this->_errorMessages[] = $message;
        }
    }
}

Since I'm fairly new at OOP, I cannot figure out a better way for this.
Edit: In the parent have for example,
abstract class objectAbstractForm {

abstract protected function addMessage($message, $messageType);

}

What is a better way to do this? I am using PHP 5.2.17

A: The issue is that you've made the 2nd argument optional in the child class but it's required in the parent class. If you want an optional argument, you'll need to make it optional in the parent class as well.

A: I imagine your class is extending another (from the error message it's extending objectForm in /www/form/Form.php), the method signature for the objectAbstractForm::addMessage() (your method posted here) must be the same as objectForm::addMessage().
For example:
class A {
    public function test($a, $b, $c=null) {
        // code
    }
}

class B extends A {
    public function test($a, $b, $c=null) {
        // code
    }
}

class C extends A {
    public function test($a, $b=null) {
        // code
    }
}

Class C will generate your error, the signature of the method C::test() is different from the signature in the method A::test(), whereas B::test() will be accept, because its signature is the same as A::test().
I'll be more than happy to make my answer more specific to your question but you'll need to post the method signature for objectForm::addMessage() and the class signature for both objectAbstractForm and Form
EDIT: I had my guesses of your classes the other way around, but the principle is the same, you cannot have a mismatch of parameters in PHP 5.2. You will need to edit the signature for whichever you prefer.
Alternatively, you can upgrade to PHP 5.3 or higher and this won't nag you.
HTH
P.S.: I'm not sure if I'm using the right terminology when I say "method signature", but if I'm wrong, feel free to correct me :)


text:
Q: Need help understanding definition of total variation metric of two probability measures Fix a measurable space $(X,\Sigma)$. Let $\mu:\Sigma\to\mathbb{R}$ be some signed measure. Then the total variation norm is defined by
$$
\|\mu\|_{\textrm{TV}}=\mu_{+}(X)+\mu_{-}(X),\quad (*)
$$
where $\mu=\mu_{+}-\mu_{-}$ is the Hahn decomposition of $\mu$. Now, let $\mu,\nu:\Sigma\to[0,1]$ be two probability measures. Then
$$
\|\mu-\nu\|_{\textrm{TV}}=2\max_{A\in\Sigma}(\mu(A)-\nu(A)),\quad (**)
$$
To see this, recall that the Hahn decomposition
$$
\mu-\nu=(\mu-\nu)_{+}-(\mu-\nu)_{-}
$$
has the form
$$
(\mu-\nu)_{\pm}(A)=(\mu-\nu)(A\cap A_{\pm}),\quad A\in\Sigma,
$$
where $A_{+}\cup A_{-}=X$, and the choice of the sets $A_{+}$, $A_{-}$ is unique up to a set of zero measures
$$
|\mu-\nu|=(\mu-\nu)_{+}+(\mu-\nu)_{-}.
$$
This apparently immediataly implies (**) with the maximum attained at the set $A_{+}$.
My question: I'm having a hard time connecting the definition of total variation norm in (*) with the arguments that lead to (**). Any help is greatly appreciated.

A: From the Hahn decomposition theorem, you can check that the definition
$$
\|\mu\|_{\textrm{TV}}=\mu_{+}(X)+\mu_{-}(X),\quad (*)
$$
can be rewritten as
$$
\|\mu\|_{\textrm{TV}}=\max_{A \in \Sigma}\mu(A)-\min_{A \in \Sigma}\mu(A)
$$
with the max and min achieved at $A_+$ and $A_-$ respectively.
So for the difference of two probability measures,
\begin{align*}
\|\mu-\nu\|_{\textrm{TV}}&=\max_{A \in \Sigma}(\mu(A)-\nu(A))-\min_{A \in \Sigma}(\mu(A)-\nu(A))\\
&=(\mu(A_+) - \nu(A_+)) - (\mu(A_-)-\nu(A_-))\\
&=(\mu(A_+) - \nu(A_+)) - ((1-\mu(A_+))-(1-\nu(A_+)))\\
&=2(\mu(A_+) - \nu(A_+))\\
&=2\max_{A \in \Sigma}(\mu(A)-\nu(A)) \quad (**)
\end{align*}


text:
Q: How do votes on closed questions affect a question ban? Writing a question that is later closed is not a good thing. Enough of these will lead to a question ban.
Two things that mitigate against a question ban, are upvoted answers, and upvoted other questions.
What about upvotes on the closed question itself? And does this change if the question is later deleted?
On the other hand, if a closed question receives a large number of downvotes, might deleting it be the "lesser evil?" The reason I ask is because "sanctions" (e.g. lighter text) are imposed after three downvotes. Also, there is a "peer pressure" badge for deleting a three downvote question.
From the above, I conclude that for some downvote number X, above three, deleting the question (and removing the X downvotes) will incur a lesser penalty than leaving it on the site. Is this, in fact, true?


text:
Q: OpenCV show err.message at camera lunch I would like to lunch a usb-camera at my raspberry pi, but when I try to start python code (opencv), it shows this message and stop a lunch
    ASSERT: "false" in file qasciikey.cpp, line 501
    Aborted

Can someone please explain me, what error is this?
It doesnt work even with another codes as well... But camera works fine, when I open it in programs like Camorama webcam viewer. I read that this part makes a problem
cv2.waitKey(20)

So it makes in another code (when i uncomment it, it lunch the code but dont show camera output) But in this code, even if I uncomment it, the code themself doesn't work: show upper error message
Here is the code

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    cv2.imshow('gray',gray)
    if cv2.waitKey(20) & 0xFF == ord('q'):  # HERE
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

A: oh are you Japanese yes bro computers are little racist do not press any japanese letter while your code runing. for waitKey you can use esc or number keys:
if cv2.waitKey(20) & 0xFF == ord('0'):
    break


text:
Q: SQL Query to show number of employees on leave I'm using Oracle APEX 20.1. On my dashboard, I want to show the number of employees on leave on current sysdate. I have a leave_details table with emp_id column, leave_start_date column, leave_end_date column, leave_status column. I have tried this SQL Query:
select nvl(count(emp_id),0)
from leave_details
where to_char(leave_start_date,'dd-mon-rr') = to_char(sysdate,'dd-mon-rr')
and leave_status = 'Granted'

but it will only show when the sysdate matches with leave_start_date. I want to show it on the dashboard for the days between leave_start_date and leave_end_date. How can I achieve this? This is what my dashboard looks like

A: Presumably, the dates are stored as dates and not as strings.  So treat them as such!
For the number on leave today:
select count(*)
from leave_details ld
where leave_start_date <= trunc(sysdate) and
      leave_end_date >= trunc(sysdate) and
      leave_status = 'Granted';

COUNT() never returns a NULL value so there is no need for additional logic to check for that.
It is unclear whether or not the end of the leave is included into the leave period.  The above assumes that it is.
Note:  If you have indeterminate leaves where the end date is not known, then you can tweak this as:
select count(*)
from leave_details ld
where leave_start_date <= trunc(sysdate) and
      (leave_end_date >= trunc(sysdate) or leave_end_date is null) and
      leave_status = 'Granted'

A: It should be
select count(1)
from leave_details ld
where leave_start_date <= trunc(sysdate) and
      leave_end_date >= trunc(sysdate) and
      leave_status = 'Granted';


text:
Q: Create flower of life with intersection formula in Javascript Based on this question : Question, I tried to create a flower of life.
So far I got the 7 first petals but to create the rest of the flower (19 petals) I'm stuck because I can't figure out what I'm doing wrong.
I'm not so good in Maths and don't exactly understand how to proceed.
Code so far (Limited to 8 circles):

window.addEventListener('load', function () {
    let distanceX = 75,
        distanceY = 75,
        angle = 60,
        circles = 8;
    for (var i = 0; i < circles; i++) {
        let div = document.createElement('div');
        div.id = 'c' + i;
        div.className = 'circle';
        document.getElementById('fol').appendChild(div);
        let circle = document.getElementById('c' + i);
        if (i == 0) {
            circle.style.transform = "translate(" + 0 + "px," + 0 + "px)";
        } else {
            if (i > 6) {
                let j = i - 2,
                    k = i - 1;
                let previouscircle = document.getElementById('c' + j).getBoundingClientRect();
                let lastcircle = document.getElementById('c' + k).getBoundingClientRect();
                var x0 = previouscircle.left;
                var y0 = previouscircle.top;
                var x1 = lastcircle.left;
                var y1 = lastcircle.top;

                console.log("previous (" + j + ") " + x0 + " " + y0);
                console.log("last (" + k + ") " + x1 + " " + y1);

                function intersection(x0, y0, r0, x1, y1, r1) {
                    var a, dx, dy, d, h, rx, ry;
                    var x2, y2;

                    dx = x1 - x0;
                    dy = y1 - y0;
                    d = Math.sqrt((dy * dy) + (dx * dx));
                    a = ((r0 * r0) - (r1 * r1) + (d * d)) / (2.0 * d);
                    x2 = x0 + (dx * a / d);
                    y2 = y0 + (dy * a / d);
                    h = Math.sqrt((r0 * r0) - (a * a));
                    rx = -dy * (h / d);
                    ry = dx * (h / d);

                    var xi = x2 + rx;
                    var xi_prime = x2 - rx;
                    var yi = y2 + ry;
                    var yi_prime = y2 - ry;

                    return [xi, xi_prime, yi, yi_prime];
                }
                let result = intersection(x0, y0, distanceX, x1, y1, distanceY);
                let resultX = result[1];
                let resultY = result[3];
                circle.style.left = resultX + "px";
                circle.style.top = resultY + "px";
            }
            circle.style.transform = "translate(" + distanceX * Math.cos(Math.PI / 180 * angle * i) + "px," + distanceY * Math.sin(Math.PI / 180 * angle * i) + "px)";
        }

        let limits = circle.getBoundingClientRect();
        console.log("c" + i + " " + limits.left + " " + limits.top);
    }
});
body {
    margin: 0;
    background-color: black;
}

.container {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.circle {
    width: 150px;
    height: 150px;
    position: absolute;
    border-radius: 100%;
    background-color: rgba(255, 255, 255, 0.1);
    box-shadow: 0 0 10px rgba(255, 255, 255, 1);
}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Flower of life</title>

Result I try to achieve:

A: Code cleaned up :-)

window.addEventListener('load', function () {
let distanceX = 75,
    distanceY = 75,
    angle = 60,
    circles = 19;
for (var i = 0; i <= circles; i++) {
    let div = document.createElement('div');
    div.id = 'c' + i;
    div.className = 'circle';
    document.getElementById('fol').appendChild(div);
    let circle = document.getElementById('c' + i);
    if (i == 0) {
        circle.style.transform = "translate(" + 0 + "px," + 0 + "px)";
    } else {
        circle.style.transform = "translate(" + distanceX * Math.cos(Math.PI / 180 * angle * i) + "px," + distanceY * Math.sin(Math.PI / 180 * angle * i) + "px)";
    }
}
function intersection(x0, y0, r0, x1, y1, r1) {
    var a, dx, dy, d, h, rx, ry;
    var x2, y2;

    dx = x1 - x0;
    dy = y1 - y0;
    d = Math.sqrt((dy * dy) + (dx * dx));
    a = ((r0 * r0) - (r1 * r1) + (d * d)) / (2.0 * d);
    x2 = x0 + (dx * a / d);
    y2 = y0 + (dy * a / d);
    h = Math.sqrt((r0 * r0) - (a * a));
    rx = -dy * (h / d);
    ry = dx * (h / d);
    var xi = x2 + rx;
    var yi = y2 + ry;
    return [xi, yi];
}
for (var f = 7; f <= 18; f++) {
    let j = f,
        k = f + 1;
    let previouscircle = document.getElementById('c' + j).getBoundingClientRect();
    let lastcircle = document.getElementById('c' + k).getBoundingClientRect();
    var x0 = previouscircle.left;
    var y0 = previouscircle.top;
    var x1 = lastcircle.left;
    var y1 = lastcircle.top;
    if (f < 13) {
        distanceX = 75;
        distanceY = 0.1;
    } else {
        distanceX = 0.1;
        distanceY = 75;
    }
    let result = intersection(x0, y0, distanceX, x1, y1, distanceY);
        let resultX = result[0];
        let resultY = result[1];
        let circle = document.getElementById('c' + f);
        circle.style.left = resultX + "px";
        circle.style.top = resultY + "px";
}
document.getElementById('c' + circles).remove();
});
body {
    margin: 0;
    background-color: black;
}

.container {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.circle {
    width: 150px;
    height: 150px;
    position: absolute;
    border-radius: 100%;
    background-color: rgba(255, 255, 255, 0.1);
    box-shadow: 0 0 10px rgba(255, 255, 255, 1);
}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Flower of life</title>
    <link rel="stylesheet" type="text/css" href="fol.css" />


text:
Q: Asymptotic behaviour and curve guessing So I have these data points which I plotted and found that for small $x$, my data behaves like $y=x^4$ but for large $x$, it behaves like $y=x^3$. From this, can I guess the relationship between $y$ and $x$? I tried $y=e^{-x}x^4+x^3$, but this doesn't work since the exponential doesn't kill of the $x^4$ quite enough at large values.

A: I've always liked the very simple
$$y=\frac{1}{\frac{1}{x^a}+\frac{1}{x^{b}}}$$
When $x$ is small, the $x^a$-term dominates and you get a slope of $a$ on the log-log plot, whereas when $x$ is large the $x^{b}$-term dominates with a slope of $b$ on the log-log plot.
Of course, without access to your data it's impossible to tell if the $x$-values are sufficiently large to make this feasible. However, that might be fixed with small modifications to the equation.


text:
Q: Laravel - how to create custom 'with' method The question is in the title.
This is what I have been tried:

*

*I created MyView class extending View

*Added to the app aliases list

*I created method withMyData() inside that class like this:

(this is just example. It all works in a regular way)
$my_data = 'some data';
return $this->with( 'my_data', $my_data );

Then I tried:
View::make('some-page')->withMyData();

I got this error:
ErrorException (E_UNKNOWN)
Undefined offset: 0

tnx

A: You definitely chose the wrong approach to pass something to every view. Use view composers instead.
View::composer('layout', function($view){
    $my_data = 'some data';
    $view->with('my_data', $my_data);
});

(layout would be the name of your view. Everytime it gets rendered the composer runs. You can also use wildcards * or an array of view names to target multiple views)
You can put this code in app/filters.php or create a new app/composers.php and include it at the end of app/start/global.php with:
require app_path().'/composers.php';

Edit
You can already use with* as an alternative to with('*'. So:
$view->with('my_data', $my_data);

Can be written as:
$view->withMyData($my_data);


text:
Q: If $\lim_{z\rightarrow z_0} g(z)=B\neq 0$ then $|g(z)|>\frac{1}{2}|B|$ My teacher said that if $\lim_{z\rightarrow z_0} g(z)=B\neq 0$ then $|g(z)|>\frac{1}{2}|B|$.
I am trying to prove this, below is my attempt
For all $ \epsilon$, $\exists \delta>0$ such that
$\epsilon>|g(z)-B|\geq||g(z)-|B||>||g(z)-\frac{1}{2}|B||$
I am not sure what to do next.

A: Let $\epsilon = \dfrac{||B||}{2} \implies \exists \delta > 0$, such that if $0 < ||z-z_0||< \delta\implies ||B||-||g(z)||\le ||g(z) - B|| < \dfrac{||B||}{2} \implies ||B|| - ||g(z)|| < \dfrac{||B||}{2}\implies ||g(z)|| > \dfrac{||B||}{2}$.


text:
Q: Can't connect to mail server anymore I never touched anything on the server which belongs to postfix and dovecot. But for several days I can't connect to my mailbox anymore.
/var/log/mail.log while connecting:
Sep 19 15:58:11 censored-hostname dovecot: auth: Error: BUG: Authentication client sent unknown handshake command: REQUEST?1008074753?14732?1?6068faccfcf40bafc9d4bff43c24e74f
Sep 19 15:58:11 censored-hostname dovecot: imap: Error: Authentication server didn't send valid SPID as expected: MECH^IPLAIN^Iplaintext
Sep 19 15:58:11 censored-hostname dovecot: imap: Error: Disconnected from auth server, aborting (client-pid=14732 client-id=1)
Sep 19 15:58:11 censored-hostname dovecot: imap-login: Internal login failure (pid=14732 id=1) (auth failed, 1 attempts): user=<info@censored.com>, method=PLAIN, rip=censored-ip, lip=censored-ip, mpid=14733, TLS
Sep 19 15:58:11 censored-hostname dovecot: auth: Error: BUG: Authentication client sent unknown handshake command: REQUEST?3226730497?14734?1?007240b93b5d5f7c244d11409e9b03e7
Sep 19 15:58:11 censored-hostname dovecot: imap: Error: Authentication server didn't send valid SPID as expected: MECH^IPLAIN^Iplaintext
Sep 19 15:58:11 censored-hostname dovecot: imap: Error: Disconnected from auth server, aborting (client-pid=14734 client-id=1)
Sep 19 15:58:11 censored-hostname dovecot: imap-login: Internal login failure (pid=14734 id=1) (auth failed, 1 attempts): user=<info@censored.com>, method=PLAIN, rip=censored-ip, lip=censored-ip, mpid=14735, TLS
Sep 19 15:58:12 censored-hostname dovecot: auth: Error: BUG: Authentication client sent unknown handshake command: REQUEST?2949644289?14737?1?52378726316ead0da1733e3e2c8bb2ce
Sep 19 15:58:12 censored-hostname dovecot: imap: Error: Authentication server didn't send valid SPID as expected: MECH^IPLAIN^Iplaintext
Sep 19 15:58:12 censored-hostname dovecot: imap: Error: Disconnected from auth server, aborting (client-pid=14737 client-id=1)
Sep 19 15:58:12 censored-hostname dovecot: imap-login: Internal login failure (pid=14737 id=1) (auth failed, 1 attempts): user=<info@censored.com>, method=PLAIN, rip=censored-ip, lip=censored-ip, mpid=14738, TLS
Sep 19 15:58:13 censored-hostname dovecot: auth: Error: BUG: Authentication client sent unknown handshake command: REQUEST?901382145?14739?1?cd9ac7c93707db11956f55a290b50005
Sep 19 15:58:13 censored-hostname dovecot: imap: Error: Authentication server didn't send valid SPID as expected: MECH^IPLAIN^Iplaintext
Sep 19 15:58:13 censored-hostname dovecot: imap: Error: Disconnected from auth server, aborting (client-pid=14739 client-id=1)
Sep 19 15:58:13 censored-hostname dovecot: imap-login: Internal login failure (pid=14739 id=1) (auth failed, 1 attempts): user=<info@censored.com>, method=PLAIN, rip=censored-ip, lip=censored-ip, mpid=14740, TLS

Dovecot configuration:
# dovecot -n
# 2.0.19: /etc/dovecot/dovecot.conf
# OS: Linux 2.6.32-042stab092.3 i686 Ubuntu 12.04.5 LTS reiserfs
first_valid_uid = 150
last_valid_uid = 150
mail_location = maildir:/var/vmail/%d/%n
passdb {
  args = /etc/dovecot/dovecot-sql.conf.ext
  driver = sql
}
protocols = " imap"
service auth {
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
  }
  unix_listener auth-userdb {
    group = mail
    mode = 0660
    user = vmail
  }
}
ssl_cert = </etc/ssl/certs/dovecot.pem
ssl_key = </etc/ssl/private/dovecot.pem
userdb {
  args = uid=150 gid=8 home=/var/vmail/%d/%n allow_all_users=yes
  driver = static
}
protocol imap {
  imap_client_workarounds = tb-extra-mailbox-sep
}

What's wrong and how to fix? It's about 5 years ago when I configured the mail server.

A: According to some, this error can be cleared by manually restarting dovecot, and I understand that has worked for you.
That said, no machine that hasn't been patched for five years should be considered fit-for-purpose.  It's definitely time for you to bring that box up-to-patch!


text:
Q: Managed instance group autohealing without external IP I can not seem to find any information on this topic, auto-healing health checks is performed by instances in a google external IP range of 130.211.0.0/22, 35.191.0.0/16.
I'm using a Cloud NAT setup and my instance group contains instances without external IP's.
Is there no way to enable auto-healing in the instance group with this kind of setup?

A: You can use Autohealing with managed instance group with instances that don't have external IPs. To achieve this goal you should whitelist access to your service from subnets 130.211.0.0/22, 35.191.0.0/16 as it mentioned in the documentation. If you concerned that your instances don't have external IPs there's nothing to worry about - requests from health check will be routed internally to your instances from health check subnets.
I successfully tried it on my test project, for test service on my instances (without external IPs) I decided to run web server Apache. Please find my steps below:

*

*create custom VPC

*create subnet

*create external static IP

*create router

*create nat

*create instance

*install Apache web server to instance

*create custom disk image

*create instance template

*create managed instance group template

*create managed instance group without health check

*allow connection to port 80 from subnets 130.211.0.0/22, 35.191.0.0/16 at firewall

*edit managed instance group and add health check (port 80)

*check status of managed instance group

*shut down Apache2 on 2 instances

*check status of managed instance group

*wait a few minutes for Autohealing

*check status of managed instance group

So, as you can see, two new instances were created and replaced two instances with stopped Apache.


text:
Q: Single API call exposed via shortcode with params I am attempting to create a Plugin with a single shortcode that takes a param to identify which field to grab from my JSON API response.
The API returns multiple values, which I am attempting to be able to break out. For example:
[user_link type="url"]

would expose just the url, while
[user_link type="user_name"]

would expose just the name.
All of this should only hit the API once, not twice.
I attempted to set it my plugin file to look like this:
$api_response = null;

function get_user_info($type) {
  if($api_response === null) {
     ... make api reqest
     $api_response = api request data;
     return $api_response[$type];
  } else {
    return $api_response[$type];
  }
}
add_shortcode( "user_link", "get_user_info" );

This still results in multiple API requests, one per shortcode I add. I believe this is happening for one of two reasons. Either the variable $api_response is getting cleared, or the shortcodes all run at the same time, and the variable is not set by the time the next one runs.
Is my approach here completely off? Is there a way to accomplish this? I am attempting to expose each piece of data separately to give the end user the ability to display and style the data as they would like.

A: The issue here is variable scoping. You're trying to access a global variable locally.
// Global scope.
$api_response = null;

function get_user_info( $type ) {
    // Local scope.

    if ( $api_response === null ) {
        // make api reqest.
        // $api_response = api request data;
        return $api_response[ $type ];
    } else {
        return $api_response[ $type ];
    }
}
add_shortcode( 'user_link', 'get_user_info' );

Add global $api_response to the top of your function would solve your issue, however using global variables is generally frowned upon and you should consider another solution like transients (as mentioned in the comments).
An example of how to add transients to your function would be:
function get_user_info( $type ) {
    $user_id      = get_current_user_id();
    $api_response = get_transient( "prefix_api_response_$user_id" );

    if ( ! $api_response ) {
        // make api request.
        $api_response = api_request_data();

        // Save response for 1 day.
        set_transient( "prefix_api_response_$user_id", $api_response, DAY_IN_SECONDS );
    }

    return $api_response[ $type ];
}


text:
Q: How to disable menu and swipe back gesture on ionic 5? I want to disable both swiping back and left hand side menu display on my login page, I can't find any information that works.
I have tried (in both ionViewWillEnter and ngOnInit)
this.routerOutlet.swipeGesture = false

I also tried
this.menu.enable(false)

This deactivates the menu button on the header bar but does not deactivate the menu when swiping.


text:
Q: Check if a login and a password is already in Preferences I saw some tutorials for auto login for exemple this one link, but when i use the app for the first time, how do i check if the login and password have already been inserted in Preferences Activity ?
What condition should i put ?

A: SharedPreferences sp=PreferenceManager.
               getDefaultSharedPreferences(context);
if(sp.contains("Username")){
//login  exists assuming you are saving the username to a preference with the name "Username"
}


text:
Q: How to shuffle the rows and columns of a DataFrame with a specific seed? Suppose I have the following DataFrame, and I want to shuffle the rows and columns of the DataFrame with a specific seed value. I tried the following to obtain shuffled indexes, but it gave me a different result every time:
julia> using Random, DataFrames, StatsBase

julia> Random.seed!(123)

julia> df = DataFrame(
           col1 = [1, 2, 3],
           col2 = [4, 5, 6]
       );

julia> idx_row, idx_col = sample.(
           [1:size(df, 1), 1:size(df, 2)],
           [length(1:size(df, 1)), length(1:size(df, 2))],
           replace=false
       )
2-element Vector{Vector{Int64}}:
 [1, 2, 3]
 [2, 1]

julia> idx_row, idx_col = sample.(
           [1:size(df, 1), 1:size(df, 2)],
           [length(1:size(df, 1)), length(1:size(df, 2))],
           replace=false
       )
2-element Vector{Vector{Int64}}:
 [2, 1, 3]
 [2, 1]

As you can see, it's shuffling the values, but it doesn't consider the seed!. How can I shuffle rows and columns of a DataFrame in a reproducible way, like setting a specific seed?

A: Fortunately, you imported a helpful package named Random. However, you didn't search for the function named shuffle. All can be achieved by the following:
julia> @which shuffle
Random

julia> idx_row, idx_col = shuffle.(
           MersenneTwister(123),
           [1:size(df, 1), 1:size(df, 2)]
       )
2-element Vector{Vector{Int64}}:
 [3, 2, 1]
 [2, 1]

julia> df[idx_row, idx_col]
3×2 DataFrame
 Row │ b      a
     │ Int64  Int64
─────┼──────────────
   1 │     6      3
   2 │     5      2
   3 │     4      1

The result is reproducible and won't change after each run, despite being a random process.
Additional point
Note that there is a customized dispatch of the shuffle function suitable for shuffling rows of a given DataFrame:
julia> shuffle(MersenneTwister(123), df)
3×2 DataFrame
 Row │ a      b
     │ Int64  Int64
─────┼──────────────
   1 │     3      6
   2 │     1      4
   3 │     2      5

*Note that this only shuffles the rows.

A: You can choose whatever rng you want, e.g. rng = MersenneTwister(113), and use it to shuffle the range of DataFrame size.
r,c = shuffle.(rng, range.(1,size(df)))
([3, 1, 2], [2, 1])

df[r,c]
3×2 DataFrame
 Row │ col2   col1
     │ Int64  Int64
─────┼──────────────
   1 │     5      2
   2 │     6      3
   3 │     4      1


text:
Q: How to prove that reduction modulo N is onto I have already showed that if
$\begin{pmatrix}a & b\\c & d\end{pmatrix} \in \operatorname{SL}(2,\mathbb{Z}/N\mathbb{Z})$ then $c$ and $d$ are coprime modulo $N$. Now I have to show that for any $(c,d)$ coprime modulo $N$, there exist $c',d'\in \mathbb{Z}$ such that $c'\equiv c\pmod{N}$, $d'\equiv d\pmod{N}$ and $\gcd(c',d')=1$. The definition I am using of coprime modulo $N$ is: $c$ and $d$ are coprime modulo $N$ if there isn't any $f\neq 0$ in $\mathbb{Z}/N\mathbb{Z}$ such that $fc=fd=0$.
If I define for every prime $p_i\mid d$ a $\lambda_{p_i}$ such that $c+\lambda_{p_i}N$ is divisible by $p_i$ then how can I use the Chinese Remainder Theorem to prove this?

A: Lift $c,d$ to $\mathbb{Z}$ such that $d\neq0$.
We will find some $\lambda\in\mathbb{Z}$ such that $c'=c+\lambda N$
is coprime to $d'=d$.
Let $P$ be the product of all primes dividing $d$ and not dividing $N$.
Let $Q=\gcd(d,N)$.
$c'$ and $d'$ are coprime if and only if $c'$ is coprime to both $P$ and $Q$.
Let $g=\gcd(c,Q)$ and $f=N/g$.
Now $fc,fd$ are integer multiples of $fg\equiv0\pmod{N}$,
and since $c,d$ are coprime modulo $N$, we conclude $f\equiv0\pmod{N}$,
therefore $g=1$.
Hence $Q$ is coprime to $c$. Furthermore $Q$ divides $N$.
Consequently, $Q$ is coprime to $c'=c+\lambda N$ for any choice of $\lambda$.
It remains to find some $\lambda$ making $c'$ coprime to $P$.
If $P=1$, then $\gcd(c',P)=1$ follows immediately for any choice of $\lambda$.
Now suppose $P>1$. Since $N$ is coprime to $P$, there exists an integer $m$
such that $mN\equiv1\pmod{P}$. Choose $u\in\mathbb{Z}$ coprime to $P$,
for example $u=1$, and choose $\lambda\equiv m(u-c)\pmod{P}$.
Thus $c'=c+\lambda N\equiv u\pmod{P}$ which makes $c'$ coprime to $P$,
and we are done.


text:
Q: Prove intersection of these two sets is empty. Define $x\sim y$ iff $x-y\in\mathbb{Q}$.
Let $S = [0, 1)$. Define $A\subset S$ such that $A$ contains exactly one element of each class of equivalence of the relation $x\sim y$.
Let $Q = \mathbb{Q}\cap S$. Chose $q\in Q$ and build the set $A_q$ from it: cut the set $A$ in two sets $1$ and $2$, in the position $1-q$. Translate $1$ to where was $2$, and translate $2$ to where was $1$. Then you will glue such pieces in the position $q$.
In other words, define: $A_q = \{x+q : x\in A\cap[0, 1-q)\}\quad\cup\quad \{x+q-1 : x\in A\cap[1 - q, 1)\}$.
If $p\neq q$, how does one proves $A_q\cap A_p = \emptyset$?

The place I was reading proved in the following way. But I was unable to follow it. Maybe it helps you...
Let $x\in S$ and $x\sim y$ which is in $A$, then:
$$
x\in A_q,\quad\mbox{where }q = \begin{cases}
x-y &  \mbox{if }x\ge y \\
x-y+1 & \mbox{if }x < y
\end{cases}
$$
Thus if existed $x\in A_q\cap A_p$ then $x-q$ and $x-p$ would be distinct and equivalent elements of $A$, which is a contradiction of the definition of $A$.

A: The argument that you found is not entirely correct. Here's a corrected and expanded version.
Suppose that $x\in A_q$ for some $q\in Q$. There are two cases to be considered.

*

*If $x\ge q$, then $x$ must be of the form $y+q$ for some $y\in A\cap[0,1-q)$, so $x-q\in A$.

*If $x<q$, then $x$ must be of the form $y-1+q$ for some $y\in A\cap[1-q,1)$, so $x-q+1\in A$.
Thus, either $x-q\in A$, or $x-q+1\in A$. Note that $x-q\sim x\sim x-q+1$.
Now suppose that $x\in A_q\cap A_p$ for some $p,q\in Q$. There are four possibilities:

*

*$x-q\in A$ and $x-p\in A$: then $x-q\sim x\sim x-p$, so $x-q\sim x-p$. But $x-q$ and $x-p$ are both in $A$, which contains only one member of each $\sim$-class, so $x-q=x-p$, and therefore $q=p$.

*$x-q\in A$ and $x-p+1\in A$: then $x-q\sim x\sim x-p+1$, so $x-q\sim x-p+1$. It follows as in the previous case that $x-q=x-p+1$ and hence that $q=p-1$. This, however, is impossible, since $0\le q,p<1$, so this case cannot actually occur. (Recall that $Q\subseteq S\subseteq[0,1)$.)

*$x-q+1\in A$ and $x-p\in A$: this is just like the previous case.

*$x-q+1\in A$ and $x-p+1\in A$: this is like the first case.

We conclude that $q=p$, and hence that $A_q\cap A_p=\varnothing$ whenever $q,p\in Q$ and $q\ne p$.
This shows that $\{A_q:q\in Q\}$ is a pairwise disjoint family.
The first part of the proof that you found does not seem to me to be needed in order to show that the sets $A_q$ are pairwise disjoint. It does show, however, that they cover $S$; I'll expand on that.
Let $x\in S$. $A$ contains a member of each $\sim$-equivalence class, so there is some $y\in $ such that $x\sim y$. Now there are two possibilities: either $x\ge y$, or $x<y$.

*

*If $x\ge y$, let $q=x-y$. Then $y=x-q<1-q$, since $x<1$, so $y\in A\cap[0,1-q)$, and therefore $x=y+q\in A_q$ by definition.

*If $x<y$, let $q=x-y+1$. Then $y=x+1-q\ge 1-q$, since $x\ge 0$, and therefore $y\in A\cap[1-q),1)$, so that again $x=y+q-1\in A_q$ by definition.
The two parts together show that $\{A_q:q\in A\}$ is a partition of $S$.


text:
Q: Python usage of regular expressions How can I extract string1#string2 from the bellow line?
<![CDATA[
string1#string2
]]>

The # character and the structure of the line is always the same.

A: I would like to refer you to this gem:
In synthesis a regex is not the appropriate tool for this job
Also have you tried an XML parser instead?
EDIT:
import xml.etree.ElementTree as ET
a = "
string1#string2
"
root = ET.fromstring(a)
c = root[0][0].text

OUT:
c
'string1#string2'

d = c.replace('#', ' ').split()
Out:
d
['string1', 'string2']

A: Simple, buggy, not reliable:
line.replace('<![CDATA[
', "").replace('
]]>', "").split("#")

A: re.search(r'[^>]+#[^<]+',s).group()

A: If you wish to use a regex:
>>> re.search(r"
(.+?)
", txt).group(1)
'string1#string2'


text:
Q: SCM changeset cannot be detected by Jenkins if building on different branches in the process I have a Jenkins build taking branch name as a parameter. Now the problem comes: if I run the build first against branch A, then on a different branch B, and finally come back to branch A, the code change set (revision) on branch A cannot be captured by Jenkins as there is build on B standing in the middle. Does anyone know how to keep change set still visible in this scenario?

A: The best way to set up builds against multiple branches is to have a separate job for each branch.  Since each job points to the specific branch, it will be able to detect the changes made to that branch.
If you have a lot of branches, this can get hard to maintain as job configuration changes will need to be made multiple times.  The configuration slicing plugin and the job DSL plugin can help you with this.


text:
Q: Evaluating $\lim_{k\to \infty} \frac{\sum_{n=0}^{k}x^{\frac{n}{k}}}{k+1}$ for all $x$ So I was really bored in my math class (I'm a high school sophomore taking precalculus in school) and my mind wandered to this expression:
$$\lim_{k\to \infty} \frac{\sum_{n=0}^{k}x^{\frac{n}{k}}}{k+1}$$
I have no idea how to even begin to evaluate this. I did some playing around with it on Desmos and it looks something like this for large values of $k$, which I don't recognize the shape of at all. I do notice that the graph should have the points $(0,0)$ and $(1,1)$, and it seems like if $j>k$ then $\frac{\sum_{n=0}^{k}x^{\frac{n}{k}}}{k+1}\ge\frac{\sum_{n=0}^{j}x^{\frac{n}{j}}}{j+1}$ for all $x$ with equality at $x=1$.
Also, please feel free to add any suitable tags---I didn't really know which ones to add.
(If you're wondering how I derived this expression, I was thinking about expressions like $\frac{x^0+x^1}{2}$, $\frac{x^0+x^{\frac{1}{2}}+x^1}{3}$, $\frac{x^0+x^{\frac{1}{3}}+x^{\frac{2}{3}}+x^1}{4}$, and then I thought about what would happen if we added more and more terms...)

A: As already noticed by partial sum for geometric series for $x\neq 1$ we have
$$\sum\limits_{n=0}^k x^\frac{n}{k} =\sum\limits_{n=0}^k \left(x^\frac{1}{k}\right)^n = \frac{1 - x^{1+\frac1k}}{1 - x^{\frac1k}}$$
and therefore by standard limits
$$\frac{\sum\limits_{n=0}^k x^\frac{n}{k}}{k+1} = \frac{1 - x^{1+\frac1k}}{(k+1)\left(1 - x^{\frac1k}\right)}=\frac k{k+1}\frac{\frac1k}{x^{\frac1k}-1}\left( x^{1+\frac1k}-1\right)\to 1\cdot \frac1{\log x}\cdot (x-1)=\frac{x-1}{\log x}$$

A: For fixed $x \ne 1$, the quantity $\frac{1}{k+1} \sum_{n=0}^k x^{n/k}$ is an approximation of the integral $$\int_0^1 x^t \, dt = \frac{x-1}{\ln(x)} = \frac{1-x}{\ln(1/x)}.$$
By "approximation of an integral," I mean that if you consider the area under the function $f(t):=x^t$ from $t=0$ to $t=\frac{k+1}{k}$ and divide this interval into $k+1$ intervals each of width $\frac{1}{k}$, you can approximate the area under $f$ by summing the areas of $k$ rectangles each having area $\frac{1}{k} \cdot x^{n/k}$. See pictures of Riemann sums for more intuition. You are only in pre-calculus now, so you probably aren't expected to know this yet, but you will encounter this when you take calculus.

A: We can note $x^\frac{n}{k} = \left(\sqrt[k]{k}\right)^n$, and thus the sum in numerator is geometric series, and we have $$\sum\limits_{n=0}^k x^\frac{n}{k} = \frac{1 - \sqrt[k]{x}^{k + 1}}{1 - \sqrt[k]{x}} = \frac{1 - x \cdot \exp\left(\frac{\ln x}{k}\right)}{1 - \exp\left(\frac{\ln x}{k}\right)}$$
We have $\exp\left(\frac{\ln x}{k}\right) = 1 + \frac{\ln x}{k} + o\left(\frac{1}{k}\right)$ (I am not sure if you are expected to know this, and if not - what tools you can use).
After this substitution, we get under limit
$$\frac{\sum_{n=0}^{k}x^{\frac{n}{k}}}{k+1} = \frac{1 - x - \frac{\ln x}{k} + o(\frac{1}{k})}{-\left(\frac{\ln x}{k} + o\left(\frac{1}{k}\right)\right)\cdot (k + 1)} = -\frac{1 - x - \frac{\ln x}{k} + o(\frac{1}{k})}{\ln x + o(1)}$$
If $x \neq 1$, this simplifies to $-\frac{1 - x + o(1)}{\ln x + o(1)}$ with limit $\frac{x - 1}{\ln x}$.
If $x = 1$, we can find this sum directly - both numerator and denominator under limit equal $k + 1$, so limit is obviously $1$.


text:
Q: Probability of a cheater being caught given a random check So this problem I made up based on this video. I've made three parts to it just to keep things fun

A bunch of $n$ students take an exam. Out of all the students, $x$ of them are cheaters. A teacher, Bob, has too many students to grade and just checks a random bunch of $y$ papers, where $y \leq n$. If it is guaranteed that a student will be caught cheating if Bob checks their paper, what is the probability that Bob will catch a cheater while grading the exam?

Second follow-up:

Now let's say Bob is tired and is no longer perfect. He can catch a cheater with a $p$ probability. What is the probability then that he catches a cheater while grading the exam?

Third part:

Let us say that the $n$ students take one exam each day that is graded instantly. What is the expected number of days until perfect Bob catches his first cheater, and until imperfect Bob catches his first cheater?


text:
Q: Change bootstrap 4 button text in media breakpoint Changing bootstrap button content on media breakpoint is adding content but not clearing previous content.
Say I have this button
<button type="button" class="mybutton btn btn-outline btn-sm">The Before</button>

I hit a breakpoint and change the button text
.mybutton:before {
  content: "The After";
}

The button result should be "The After" but instead it's "The AfterThe Before"
The rendered css is
<button type="button" class="mybutton btn btn-outline btn-sm">
  ::before
  The Before
</button>

A: The trick was to hide the font size before changing content.
.nav-pills, .nav-link > a {
  font-size: 0 !important;
}


text:
Q: How to highlight text using string indexes in WPF RichTextBox? I'm working on a custom RichTextBox which highlights certain words typed in it.
(more like highlight certain strings, because I intent to highlight strings that are not separated by spaces)
I search for strings by loading the text to memory, and looking for a list of strings one by one, then applying formatting to them.
Issue is that, index I get from the plain text representation, doesn't necessarily point to the same position in the RichTextBox's content, when formatting is applied.
(First formatting is perfect. Any subsequent formatting starts to slip to the left. I assume this is because formatting adds certain elements to the documents which makes my indexes incorrect.)
Sample pseudo code for this is as follows.
// get the current text
var text = new TextRange(Document.ContentStart, Document.ContentEnd).Text;

// loop through and highlight
foreach (string entry in WhatToHighlightCollection)
{
    var currentText = text;
    var nextOccurance = currentText.IndexOf(suggestion); //This index is Unreliable !!!

    while (nextOccurance != -1)
    {
        // Get the offset from start. (There appears to be 2 characters in the
        // beginning. I assume this is document and paragraph start tags ??
        // So add 2 to it.)
        int offsetFromStart = (text.Length) - (currentText.Length) + 2;

        var startPointer = Document.ContentStart.
             GetPositionAtOffset(offsetFromStart + nextOccurance, LogicalDirection.Forward);

        var endPointer = startPointer.GetPositionAtOffset(suggestion.Length, LogicalDirection.Forward);

        var textRange = new TextRange(startPointer, endPointer);
        textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
        textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
        textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, new FontFamily("Segoe UI"));

        // Go to the next occurance.
        currentText = currentText.Substring(nextOccurance + suggestion.Length);
        nextOccurance = currentText.IndexOf(suggestion);
    }
}

How do I map string indexes to rich text box content ?
NOTE: I'm not worried about the performance of this at the moment, although any suggestions are always welcome, as currently I run this on every TextChanged event to highlight 'as the user type' and it's getting a bit sluggish.


text:
Q: 3d point cloud of an object using Kinect I've got a point cloud of an object using kinect and I want to create a 3d representation of the point cloud and save the image. I'm not sure how I can approach this task. I want it to be able to detect an object and derive the point cloud of the object. For example for 3d scanning purposes, it would be able to 3d scan the object from all directions and then get a point cloud from it.
main.cpp
#include "main.h"
#include "glut.h"

#include <cmath>
#include <cstdio>

#include <Windows.h>
#include <Ole2.h>

#include <NuiApi.h>
#include <NuiImageCamera.h>
#include <NuiSensor.h>

// OpenGL Variables
long depthToRgbMap[width*height*2];
// We'll be using buffer objects to store the kinect point cloud
GLuint vboId;
GLuint cboId;

// Kinect variables
HANDLE depthStream;
HANDLE rgbStream;
INuiSensor* sensor;

bool initKinect() {
    // Get a working kinect sensor
    int numSensors;
    if (NuiGetSensorCount(&numSensors) < 0 || numSensors < 1) return false;
    if (NuiCreateSensorByIndex(0, &sensor) < 0) return false;

    // Initialize sensor
    sensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH | NUI_INITIALIZE_FLAG_USES_COLOR);
    sensor->NuiImageStreamOpen(NUI_IMAGE_TYPE_DEPTH, // Depth camera or rgb camera?
        NUI_IMAGE_RESOLUTION_640x480,                // Image resolution
        0,        // Image stream flags, e.g. near mode
        2,        // Number of frames to buffer
        NULL,     // Event handle
        &depthStream);
    sensor->NuiImageStreamOpen(NUI_IMAGE_TYPE_COLOR, // Depth camera or rgb camera?
        NUI_IMAGE_RESOLUTION_640x480,                // Image resolution
        0,      // Image stream flags, e.g. near mode
        2,      // Number of frames to buffer
        NULL,   // Event handle
        &rgbStream);
    return sensor;
}

void getDepthData(GLubyte* dest) {
    float* fdest = (float*) dest;
    long* depth2rgb = (long*) depthToRgbMap;
    NUI_IMAGE_FRAME imageFrame;
    NUI_LOCKED_RECT LockedRect;
    if (sensor->NuiImageStreamGetNextFrame(depthStream, 0, &imageFrame) < 0) return;
    INuiFrameTexture* texture = imageFrame.pFrameTexture;
    texture->LockRect(0, &LockedRect, NULL, 0);
    if (LockedRect.Pitch != 0) {
        const USHORT* curr = (const USHORT*) LockedRect.pBits;
        for (int j = 0; j < height; ++j) {
            for (int i = 0; i < width; ++i) {
                // Get depth of pixel in millimeters
                USHORT depth = NuiDepthPixelToDepth(*curr++);
                // Store coordinates of the point corresponding to this pixel
                Vector4 pos = NuiTransformDepthImageToSkeleton(i, j, depth<<3, NUI_IMAGE_RESOLUTION_640x480);
                *fdest++ = pos.x/pos.w;
                *fdest++ = pos.y/pos.w;
                *fdest++ = pos.z/pos.w;
                // Store the index into the color array corresponding to this pixel
                NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution(
                    NUI_IMAGE_RESOLUTION_640x480, NUI_IMAGE_RESOLUTION_640x480, NULL,
                    i, j, depth<<3, depth2rgb, depth2rgb+1);
                depth2rgb += 2;
            }
        }
    }
    texture->UnlockRect(0);
    sensor->NuiImageStreamReleaseFrame(depthStream, &imageFrame);
}

void getRgbData(GLubyte* dest) {
    float* fdest = (float*) dest;
    long* depth2rgb = (long*) depthToRgbMap;
    NUI_IMAGE_FRAME imageFrame;
    NUI_LOCKED_RECT LockedRect;
    if (sensor->NuiImageStreamGetNextFrame(rgbStream, 0, &imageFrame) < 0) return;
    INuiFrameTexture* texture = imageFrame.pFrameTexture;
    texture->LockRect(0, &LockedRect, NULL, 0);
    if (LockedRect.Pitch != 0) {
        const BYTE* start = (const BYTE*) LockedRect.pBits;
        for (int j = 0; j < height; ++j) {
            for (int i = 0; i < width; ++i) {
                // Determine rgb color for each depth pixel
                long x = *depth2rgb++;
                long y = *depth2rgb++;
                // If out of bounds, then don't color it at all
                if (x < 0 || y < 0 || x > width || y > height) {
                    for (int n = 0; n < 3; ++n) *(fdest++) = 0.0f;
                }
                else {
                    const BYTE* curr = start + (x + width*y)*4;
                    for (int n = 0; n < 3; ++n) *(fdest++) = curr[2-n]/255.0f;
                }

            }
        }
    }
    texture->UnlockRect(0);
    sensor->NuiImageStreamReleaseFrame(rgbStream, &imageFrame);
}

void getKinectData() {
    GLubyte* ptr;
    glBindBuffer(GL_ARRAY_BUFFER, vboId);
    ptr = (GLubyte*) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
    if (ptr) {
        getDepthData(ptr);
    }
    glUnmapBuffer(GL_ARRAY_BUFFER);
    glBindBuffer(GL_ARRAY_BUFFER, cboId);
    ptr = (GLubyte*) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
    if (ptr) {
        getRgbData(ptr);
    }
    glUnmapBuffer(GL_ARRAY_BUFFER);
}

void rotateCamera() {
    static double angle = 0.;
    static double radius = 3.;
    double x = radius*sin(angle);
    double z = radius*(1-cos(angle)) - radius/2;
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(x,0,z,0,0,radius/2,0,1,0);
    angle += 0.05;
}

void drawKinectData() {
    getKinectData();
    rotateCamera();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    glBindBuffer(GL_ARRAY_BUFFER, vboId);
    glVertexPointer(3, GL_FLOAT, 0, NULL);

    glBindBuffer(GL_ARRAY_BUFFER, cboId);
    glColorPointer(3, GL_FLOAT, 0, NULL);

    glPointSize(1.f);
    glDrawArrays(GL_POINTS, 0, width*height);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
}

int main(int argc, char* argv[]) {
    if (!init(argc, argv)) return 1;
    if (!initKinect()) return 1;

    // OpenGL setup
    glClearColor(0,0,0,0);
    glClearDepth(1.0f);

    // Set up array buffers
    const int dataSize = width*height * 3 * 4;
    glGenBuffers(1, &vboId);
    glBindBuffer(GL_ARRAY_BUFFER, vboId);
    glBufferData(GL_ARRAY_BUFFER, dataSize, 0, GL_DYNAMIC_DRAW);
    glGenBuffers(1, &cboId);
    glBindBuffer(GL_ARRAY_BUFFER, cboId);
    glBufferData(GL_ARRAY_BUFFER, dataSize, 0, GL_DYNAMIC_DRAW);

    // Camera setup
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, width /(GLdouble) height, 0.1, 1000);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0,0,0,0,0,1,0,1,0);

    // Main loop
    execute();
    return 0;
}


text:
Q: Attempting to set location in String Array, getting out of bounds exception thrown I'm trying to 'add' to my String[].
I'm reading a file with a BufferedFileReader.  I have my code set up to return a String[], lets call it list.  Essentially my code loops through the file until it's empty (well null), adds each line to a string, then out of the loop I split() the string into my list.
I fear that because I do that the list has an immutable size, which is why I'm getting the Exception thrown.
How do I go about writing the following code the 'correct' way?

Code
 note the list below isn't instantiated like that, just for labeling purposes.
String[] list;
int length = list.length;
list[length + 1] = (method that returns a string);
list[length + 2] = (method that returns a string);

It goes on for 5 spaces.
I'm going about this because I'm attempting to save fields to a file, and in order to avoid overwriting a file I'd like to add to it instead.

TL;DR:
Essentially trying to add to a String[] or find a better alternative because I can't change the length.

A: Your question is not so Clear.
If I am correct you want to define array size by dynamically
You better use java.util.ArrayList .. Where you can dynamically change the length of the Array .

A:
String[] or find a better alternative because I can't change the
  length.

You better use ArrayList for this.
ArrayList<String> ar=new ArrayList<String>(put capacity if you want);

you can remove search in arraylist easily.

A: List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");

return list.toArray();


text:
Q: schema to data frame using pyspark I have this schema:
schm = StructType([
        StructField("User ID", IntegerType(), True),
        StructField("Tag", StringType(), True),
        StructField("Activated", StringType(), True),
        StructField("Created Date", StringType(), True),
        StructField("Updated Date", StringType(), True),
        StructField("Valid Until", StringType(), True),
        StructField("last used", StringType(), True),
        StructField("reference", StringType(), True),
        StructField("employee code", IntegerType(), True),
        StructField("Unique user ID", IntegerType(), True),
    ])
schm

I want to build a dataframe for 998 values.But the problem is i can't understand how to get input data for 998 rows(same value for 998 rows):
df = create_df(spark, input_data, schm)


text:
Q: Difference between definitions of a random sample
Definition 5.1.1 The random variables $X_{1}, \ldots, X_{n}$ are called a random sample of size $n$ from the population $f(x)$ if $X_{1}, \ldots, X_{n}$ are mutually independent random variables and the marginal pdf or pmf of each $X_{i}$ is the same function $f(x)$. Alternatively, $X_{1}, \ldots, X_{n}$ are called independent and identically distributed random variables with pdf or pmf $f(x)$. This is commonly abbreviated to iid random variables.

What is the difference between these two definitions? Wouldn't both "random sample of size $n$ from the population" and "independent and identically distributed random variables" be the same thing? both have the same density function and are all independent.


text:
Q: can't get KNearestNeighborMatching in Accord.Imaging to build in C# I want to use SpeededUpRobustFeaturesDetector Class to compare images that may be distorted.
I found a great example here but get build error:
"KNearestNeighborMatching COULD NOT BE FOUND" even though I added reference Accord.Imaging 3.8.0.0 in the past and have been using it without problem for other computer vision work.
The Accord online doc. shows KNearestNeighborMatching Class within Accord.Imaging
I tried "Accord.Imaging.KNearestNeighborMatching" but that doesn't work.
Here is my code copied from that link..........................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualBasic;

using Accord.Video;
using Accord.Video.DirectShow;
using Accord.Imaging;
using Accord.Imaging.Filters;
using ACCORD_WindowsFormsApp9;

namespace ACCORD_WindowsFormsApp9
{
    class Computer_Vision
    {

public class ProcessImage
{
    public static void Similarity(System.IO.Stream model, System.IO.Stream observed,
        out float similPercent)
    {
        Bitmap bitModel = new Bitmap(model);
        Bitmap bitObserved = new Bitmap(observed);

        // For method Difference, see http://www.aforgenet.com/framework/docs/html/673023f7-799a-2ef6-7933-31ef09974dde.htm

        // Inspiration for this process: https://www.youtube.com/watch?v=YHT46f2244E
        // Greyscale class http://www.aforgenet.com/framework/docs/html/d7196dc6-8176-4344-a505-e7ade35c1741.htm
        // Convert model and observed to greyscale
        Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
        // apply the filter to the model
        Bitmap greyModel = filter.Apply(bitModel);
        // Apply the filter to the observed image
        Bitmap greyObserved = filter.Apply(bitObserved);
        int modelPoints = 0, matchingPoints = 0;

        /*
         * This doesn't work. Images can have different sizes
        // For an example, https://thecsharper.com/?p=94
        // Match
        var tm = new ExhaustiveTemplateMatching(similarityThreshold);
        // Process the images
        var results = tm.ProcessImage(greyModel, greyObserved);
        */

        using (SpeededUpRobustFeaturesDetector detector = new SpeededUpRobustFeaturesDetector())
        {
            List<SpeededUpRobustFeaturePoint> surfModel = detector.ProcessImage(greyModel);
            modelPoints = surfModel.Count();
          List<SpeededUpRobustFeaturePoint> surfObserved = detector.ProcessImage(greyObserved);

            KNearestNeighborMatching matcher = new KNearestNeighborMatching(5);
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  "COULD NOT BE FOUND"
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            var results = matcher.Match(surfModel, surfObserved);
            matchingPoints = results.Length;
        }
        // Determine if they represent the same points
        // Obtain the pairs of associated points, we determine the homography matching all these pairs

        // Compare the results, 0 indicates no match so return false
        if (matchingPoints <= 0)
        {
            similPercent = 0.0f;
        }

        similPercent = (matchingPoints * 100) / modelPoints;
    }
}

A: I fixed it: The C# project had become corrupt: reference Accord.Vision was   gone and could not be added.
Just had to create a new VS C# forms project, pop in the old .cs files, and re-add all the NuGet Accord libs.  All builds now, especially KNearestNeighborMatching .


text:
Q: Many input parameters to a binary file I have a simulation program written in C++. Normally, I would want to initialize the binary code with different parameters for different runs. First I tried using all my input parameters as command line arguments, but it happened to be too confusing, there are just too many parameters. Like:
./mysimulation 5 55 True ... output_file_name.txt

Then I decided to parse only a filename with input parameters written in it.
Like:
./mysimulation input_parameters.txt

But then the input file looks messy and confuses me because there are multiple lines, but I forget what lines correspond to what parameters The file would like so:
input_parameters.txt
55
5
True
...
output_file_name.txt

I could add comments, but then it is going to be a hassle to handle input file in C++, as it will require additional effort to parse the parameters in the file.
Now, I thought about using XML files since they are very structured and human-readable. I'm not sure if it is going to be easy to generate these XML files in python (python generates input parameters and launches C++ code multiple times) and read them in C++. Maybe there exists a better solution?
In my future plans, I'd like to have a parallel execution of multiple binaries on a many-CPU server computer. It'd be nice if the solution nicely complied with multiprocessing extension.
I tried linking C++ and Python with boost (as I did with my other projects), but I had trouble setting it up these CMakeFiles as the C++ has multiple classes, and I gave up after a couple of hours. And in one of my projects after making a shared library, multiprocessing with python crashed when using these libraries for some unknown to me reason, that is why I'd like to avoid python boost. (Maybe I did something incorrectly)


text:
Q: Table with most frequent combinations with pandas python The dataset
ID Product
1   A
1   B
2   A
3   A
3   C
3   D
4   A
4   B
5   A
5   C
5   D
.....

The goal is to have the most frequent combinaisons of product by ID regardless the number of string value.
The expected result here is :
[A, C, D]  2
[A, B]     2
[A, C]     2
......

Like that but with a working value
import itertools

(df.groupby('ID').Product.agg(lambda x: list(set(itertools.combinations(x,**?**))))
                 .explode().str.join('-').value_counts())

A: IIUC, groupby ID, aggregate to frozenset and count the occurrences with value_counts:
df.groupby('ID')['Product'].agg(frozenset).value_counts()

output:
(B, A)       2
(D, C, A)    2
(A)          1
Name: Product, dtype: int64

Alternative using sorted tuples:
df.groupby('ID')['Product'].agg(lambda x: tuple(sorted(x))).value_counts()

output:
(A, B)       2
(A, C, D)    2
(A,)         1
Name: Product, dtype: int64

Or strings:
df.groupby('ID')['Product'].agg(lambda x: ','.join(sorted(x))).value_counts()

output:
A,B      2
A,C,D    2
A        1
Name: Product, dtype: int64


text:
Q: Images not loading in Chrome when changing img src via javascript I'm pulling album art from the Deezer API via AJAX for a Chrome extension I'm making however some of the images don't render. I'm fetching the album art for ~30 tracks and some display but some don't.
The AJAX request completes and I receive the image url which I then add to the page with the following (The Date.getTime() was something I read to avoid caching):
var img = $("<img />");
img.attr('src', imageSrc + "?" + new Date().getTime());
$(_this.dom).find(".card-image").html(img);

If I inspect the page, the  src is set correctly to http://cdn-images.deezer.com/images/cover/7f3d5b5c3c0358e3edc58ee8d9f6cabb/250x250-000000-80-0-0.jpg?1438639441322 for example but the  element itself has a height of 0 and nothing is displayed.
If I open the image file in a new tab, it's displayed correctly so there isn't a problem with the link.
Any ideas? This is driving me slowly insane.
There's a screenshot here which shows the problem I'm having: Screenshot


text:
Q: Java Socket RPC protocol I've been asking some questions about adapting the command protocol for use in my client server environment. However, after some experimentation, I have come to the conclusion that it will not work for me. It is not designed for this scenario. I'm thus at a loose end.
I have implemented a sort of RPC mechanism before whereby I had a class entitled "Operation". I also had an enum entitled "Action" that contained names for actions that could be invoked on the server.
Now, in my old project, every time that the client wanted to invoke an action on the server, it would create an instance of 'Operation' and set the action variable with a value from the "Action" enum. For example
Operation serverOpToInvoke = new Operation();
serverOpToInvoke.setAction(Action.CREATE_TIME_TABLE);
serverOpToInvoke.setParameters(Map params);
ServerReply reply = NetworkManager.sendOperation(serverOpToInvoke);
...
On the server side, I had to perform the horrible task of determining which method to invoke by examining the 'Action' enum value with a load of 'if/else' statements. When a match was found, I would call the appropriate method.
The problem with this was that it was messy, hard to maintain and was ultimately bad design.
My question is thus - Is there some sort of pattern that I can follow to implement a nice, clean and maintainable rpc mechanism over a TCP socket in java? RMI is a no go for me here as the client (android) doesn't support RMI. I've exhausted all avenues at this stage. The only other option would maybe be a REST service. Any advice would be very helpful.
Thank you very much
Regards

A: Probably the easiest solution is to loosely follow the path of RMI.
You start out with an interface and an implementation:
interface FooService  {
  Bar doThis( String param );
  String doThat( Bar param );
}

class FooServiceImpl implements FooService {
  ...
}

You deploy the interface to both sides and the implementation to the server side only.
Then to get a client object, you create a dynamic proxy. Its invocation handler will do nothing else but serialize the service classname, the method name and the parameters and send it to the server (initially you can use an ObjectOutputStream but you can use alternative serialization techniques, like XStream for example).
The server listener takes this request and executes it using reflection, then sends the response back.
The implementation is fairly easy and it is transparent from both sides, the only major caveat being that your services will effectively be singletons.
I can include some more implementation detail if you need, but this is the general idea I would follow if I had to implement something like that.
Having said that, I'd probably search a bit more for an already existing solution, like webservices or something similar.
Update: This is what an ordinary (local) invocation handler would do.
class MyHandler implements InvocationHandler {

    private Object serviceObject;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        return method.invoke(serviceObject, args);
    }
}

Where serviceObject is your service implementation object wrapped into the handler.
This is what you have to cut in half, and instead of calling the method, you need to send the following to the server:

*

*The full name of the interface (or some other value that uniquely identifies the service interface)

*The name of the method.

*The names of the parameter types the method expects.

*The args array.

The server side will have to:

*

*Find the implementation for that interface (the easiest way is to have some sort of map where the keys are the interface names and the values the implementation singleton instance)

*Find the method, using Class.getMethod( name, paramTypes );

*Execute the method by calling method.invoke(serviceObject, args); and send the return value back.

A: You should look into protocol buffers from google: http://code.google.com/p/protobuf/
This library defines an IDL for generating struct like classes that can be written and read from a stream/byte array/etc. They also define an RPC mechanism using the defined messages.
I've used this library for a similar problem and it worked very well.

A: RMI is the way to go.

Java RMI is a Java application
  programming interface that performs
  the object-oriented equivalent of
  remote procedure calls (RPC).