Q:

Can every infinite cardinal $\mu$ such that $\kappa\leq\mu\leq2^\kappa$ be expressed as $\kappa^\lambda$?

Let $\kappa$ be an infinite cardinal. Can I reach every intermediate cardinal $\mu$ with $\kappa \le \mu \le 2^\kappa$ as some power $\kappa^\lambda$?
If not, is there another construction that allows me to reach every cardinal between $\kappa$ and $2^\kappa$?

A:

The power functions are a total wild card, as shown by Cohen, Solovay, Easton and others.
The only two things we can say about it, is that it is monotonous and increasing in cofinality.
More specifically, suppose that you start with a model of $\sf GCH$, add $\aleph_2$ Cohen reals, and you have a model where $2^{\aleph_0}=\aleph_2$ but $\aleph_1\neq\aleph_0^{\aleph_0}$ and of course that $\aleph_1\neq\aleph_0^n$ for any finite $n$.
And of course you can replace $\aleph_2$ here by any cardinal. Add "many" Cohen reals, and then every cardinal in the interval from $\aleph_0$ to $2^{\aleph_0}$ cannot be expressed like that.
It might be worth pointing out that $\sf GCH$ implies, on the other hand, that this is true, simply because $\mu=\kappa$ or $\mu=2^\kappa$ in that case. I suspect that you can prove that this assertion is in fact equivalent to $\sf GCH$.


Q:

Why does my shutter sound slower in Q (quiet) mode on Nikon?

When I put my camera (d610) in Quiet mode my ears play a trick on me I think. The shutter sounds so much slower when in Q than in regular Single or Continuous. Everything is still the same correct? Or does anything change besides the sound?

A:

Are you sure that it's your shutter you're hearing and not your mirror? Because typically the mirror would make more noise than the shutter (assuming you're shooting through the viewfinder)


Q:

Why code contracts can be added and removed for postconditions and object invariants, but not for preconditions in C#?

Why code contracts can be added and removed for postconditions and object invariants, but not for preconditions in C#?
In the CLR via C# book I met the following excerpt:

And since a contract cannot be made stricter with new versions (without breaking compatibility), you
  should carefully consider preconditions when introducing a new virtual, abstract, or interface member.
  For postconditions and object invariants, contracts can be added and removed at will as the conditions
  expressed in the virtual/abstract/interface member and the conditions expressed in the overriding
  member are just logically AND-ed together.

That is very confusing for me that postconditions and object invariants, contracts can be added and removed at will. I would expect a suggestion that the postconditions and object invariants can become only stricter as well as the preconditions. Why am I expecting this? Because I can come up with an example where the suggestion proves wrong. E.g.
At first we had a postcondition and everything worked just fine:
using System.Diagnostics.Contracts;

public sealed class Program
{
    public static void FooBaseContract(int i)
    {
        Contract.Ensures(i > 0);
    }
}

public class FooBase
{
    public virtual int i
    {
        get {return 2;}
    }
}
public class FooDerived : FooBase
{
    public override int i
    {
        get {return 4;}
    }
}

Now we decide to make the postcondition stricter:
using System.Diagnostics.Contracts;

public sealed class Program
{
    public static void FooBaseContract(int i)
    {
        Contract.Ensures(i > 4);
    }
}

public class FooBase
{
    public virtual int i
    {
        get {return 2;}
    }
}
public class FooDerived : FooBase
{
    public override int i
    {
        get {return 4;}
    }
}

That definitely makes the code which worked with the previous postcondition incompatible with the new postcondition. That means that we lose the backward compatibility by making the postconditions stricter.
Also, I am not getting why the author refers only the virtual, abstract, or interface member. Because in the contrived example I gave above the incompatibility with the new code contract version will happen even if I change code to the following (remove all virtual, abstract, or interface member):
using System.Diagnostics.Contracts;

public sealed class Program
{
    public static void FooBaseContract(int i)
    {
        Contract.Ensures(i > 4);
    }
}

public class FooBase
{
    public int i
    {
        get {return 2;}
    }
}

So, could someone explain in a foolproof manner what am I missing here, please?
UPDATE
As was mentioned in the comments section - the code contracts is a deprecated concept. That is ok for me, I just would like to understand the idea - in this case it is why can we make the postconditions and object invariants stricter? It contradicts with my common sense, meaning that something was allowed to be returned previously (or take place for object invariants) and now we state that that something is not allowed any more and the author of the book tells that such a case is not breaking a backward compatibility.

A:

The text says that the conditions are "anded" together. This means that you simply do not have the ability to remove postconditions and invariants. You can only add them regardless of how you write the code.
Postconditions and invariants are things that must be ensured on exit. It makes sense to be able to add obligations. If you are adding a contradiction then CC should flag that as a postcondition violation.
From a compatibility and extensibility standpoint, users of the base class will receive the guarantees they expect. They might receive additional guarantees that they don't know or care about.


Q:

Why C# compiler generates single class to capture variables of several lambdas?

Assume we have such code:
public class Observer
{
    public event EventHandler X = delegate { };
}

public class Receiver
{
    public void Method(object o) {}
}

public class Program
{
    public static void DoSomething(object a, object b, Observer observer, Receiver r)
    {
        var rCopy = r;
        EventHandler action1 = (s, e) => rCopy.Method(a);
        EventHandler action2 = (s, e) => r.Method(b);
        observer.X += action1;
        observer.X += action2;
    }

    public static void Main(string[] args)
    {
        var observer = new Observer();
        var receiver = new Receiver();
        DoSomething(new object(), new object(), observer, receiver);
    }
}

Here action1 and action2 have completely separated set of captured variables - rCopy was created especially for this. Still, compiler generates just one class to capture everything (checked generated IL). I suppose it is done for optimization reasons, but it allows very hard-to-spot memory leak bugs: if a and b captured in single class, GC is unable to collect both at least so long as any of lambdas are referenced.
Is there a way to convince compiler to produce two different capture classes? Or any reason why it cannot be done?
P.S. Somewhat more detailed, in my blog: here and here.

A:

You have rediscovered a known shortcoming in the implementation of anonymous functions in C#. I described the problem in my blog in 2007.

Is there a way to convince compiler to produce two different capture classes?

No.

Or any reason why it cannot be done?

There is no theoretical reason why an improved algorithm for partitioning closed-over variables so that they are hoisted into different closure classes could not be devised. We have not done so for practical reasons: the algorithm is complicated, expensive to get right and expensive to test, and we have always had higher priorities. Hopefully that will change in Roslyn, but we are making no guarantees.

A:

I'm fairly sure you are seeing practical limitations in the compiler's code rewriting logic, it is not simple to do.  The workaround is easy enough, create the lambda in a separate method so you get two separate instances of the hidden class:
public static void DoSomething(object a, object b, Observer observer, Receiver r) {
    var rCopy = r;
    observer.X += register(r, a);
    observer.X += register(rCopy, b);
}
private static EventHandler register(Receiver r, object obj) {
    return new EventHandler((s, e) => r.Method(obj));
}


Q:

What exactly is the Linux kernel and does Ubuntu use a modified Linux kernel?

What exactly is the Linux kernel? And does Ubuntu, at the core, use a modified Linux kernel? In what manner is it distinguished by the NT/Windows 8 kernel?

A:

An operating system kernel is the central part of the operating system, handling all main tasks. It is loaded into a protected area of memory at boot time. Kernel space, where the kernel carries out its tasks, and user space, where everything else happens, are kept separate. The /sys directory contains a virtual filesystem that provides a view of kernel data structures and objects from user space.

The Linux kernel is a monolithic kernel originally developed by Linus Torvalds, who still directs its development. The latest vanilla kernel can be downloaded from kernel.org, and Ubuntu kernels (patched by Ubuntu kernel team) are available from the Ubuntu mainline kernel ppa
The kernel is found in the /boot directory. When a new kernel is installed (for example, as part of a routine update and upgrade procedure) old kernels are not automatically removed, and over time the /boot directory becomes full, and this can cause serious problems if /boot is on a small separate partition. To prevent this, users should periodically run sudo apt autoremove to clean up (actually the initrd.img file for each kernel is larger than the kernel itself, but that is removed along with the kernel by autoremove). It is advisable to keep at least one "spare" older kernel. The user can select which kernel to boot from the GRUB menu. The newest kernel (with the highest release number) is booted by default.
The release number of the running kernel may by checked with the command uname -r
For more details, see the documentation maintained by the Ubuntu Kernel Team.
Source: 'kernel' tag wiki
Reference: https://help.ubuntu.com/community/Kernel

A:

Linux kernel Wiki
To understand an difference between Win vs Linux kernel
Ubuntu Linux kernel derives its kernel from the vanilla kernel d(using linux.git and stable branches) and builds its own version of supported kernel.
Modified kernel is a user requirement for building a custom kernel from the sources (either from upstream or ubuntu sources) for testing a new device driver etc.
GitKernelBuild
My 2 cents! Hope this helps.


Q:

How to change the message "*!* whispers to you"?

When I type /msg @p xxxxx, it always says *!* whispers to you: xxxx. How do I change this to a name, like xxx: xxxxx, instead?
I'm on the Windows 10 Edition for Xbox One.

A:

I should've been more specific, I put the commands in command blocks. I don't mind who sees it if it's too much of an issue, but would prefer the person who pressed the button (@p). I'm in a standard creative world.

If the command is in a command block then you need to change the command block name (technically "Hover Note") to what you want it to be. Then when you run the command, it will read:
[ChosenName] whispers to you: {Message}
Additionally, if you only want the person who pressed the button to see it, use @p in the command. After this change, your command will look like this:
/msg @p {Message}


Q:

Impute class values based on map

I want to impute marker classes (either class A or class B), based on proximity of known marker classes.  So for example if I know M1 and M4 are class A, then all markers positioned in the map between M1 and M4 can also be classified as A.
If I know marker M4 is class A and its position is chr1 13, and marker M7 is B with position 16, then we can classify all markers with position less than equal to (13+16)/2=14.5 as A and everything between 14.5 and 16 as B on the same chromosome. So M5 is A and M6 can be classified as B.
I have a map of sorted positions of markers
M0  chr1    9
M1  chr1    10
M2  chr1    11
M3  chr1    12
M4  chr1    13
M5  chr1    14
M6  chr1    15
M7  chr1    16
M8  chr2    1
M9  chr2    2
M10 chr2    3
M11 chr2    4

So given a simple backbone of
M1  A
M4  A
M7  B
M8  B
M10 A

I want to impute the rest of the markers on the map, if possible.
So my desired output is
M1  A
M2  A
M3  A
M4  A
M5  A
M6  B
M7  B
M8  B
M9  B
M10 A

I am a biologist trying to learn a little bit of awk, and relaize this maybe just a computational problem and I`m not sure where to get started. Please help. I have access to unix cluster to run awk and perl. Please note, correct imputation can be only done between markers  mapped to the same chromosome.

A:

You never answered any of my questions, so here's a Perl solution that makes a lot of guesses
use strict;
use warnings 'all';
use autodie;

my (@markers, %markers);
{
    open my $fh, '<', 'markers.txt';

    while ( <$fh> ) {
        my @marker = split;
        push @markers, \@marker;
        $markers{$marker[0]} = $#markers;
    }
}

my ($i0, $i1);

open my $fh, '<', 'classes.txt';

while ( <$fh> ) {

    my ($marker, $class) = split;

    $i1 = $markers{$marker};
    my $m1 = $markers[$i1];
    push @$m1, $class;

    next unless defined $i0;

    my $m0 = $markers[$i0];

    next if $m0->[1] ne $m1->[1];          # Different chromosomes

    my $mid = ( $m0->[2] + $m1->[2] ) / 2; # Mid point between markers

    for my $m ( @markers[ $i0+1 .. $i1-1 ] ) {
        push @$m, $m->[2] <= $mid ? $m0->[3] : $m1->[3];
    }
}
continue {
    $i0 = $i1;
}

printf "%-4s%-8s%-4d%-s\n", @{$_}[0..2], $_->[3] // '' for @markers;

output
M0  chr1    9
M1  chr1    10  A
M2  chr1    11  A
M3  chr1    12  A
M4  chr1    13  A
M5  chr1    14  A
M6  chr1    15  B
M7  chr1    16  B
M8  chr2    1   B
M9  chr2    2   B
M10 chr2    3   A
M11 chr2    4


Q:

"свеч" and "свечей" - what is the correct version

I have been thinking about for a while, but didn't come to any conclusion.
What is the correct version for "свечи" (plural for "свеча") in the genitive?

"Как расстанешься, если каждый вечер, лишь только нальются нити лампы в 50 свечей, и в зелёной тени абажура я могу писать и читать, в тепле, не помышляя о том, что на дворе ветерок при 18 градусах мороза".
"Игра не стоит свеч".
" Игра стоит свеч, то есть, идет хорошо настолько, что свечей не жаль."
"Каталог свечей зажигания и накаливания", "Магия свеч и ангелы", etc.

A:

Можно и так и так, вот цитата.

Существительное, неодушевлённое, женский род, 1-е склонение (тип склонения 4f по классификации А. Зализняка).
  Встречается также вариант склонения по схеме 4d (мн. ч. све́чи, све́ч, све́чам, све́чи, све́чами, све́чах).

4f - это как раз -е́й
Соотношение свеч / свечей в Яндексе, впрочем, меньше, чем 1 к 5, то есть свечей говорят чаще.  Это не какая-то новая тенденция, употребление обеих форм и перевес в сторону второй формы прослеживается по меньшей мере с 19-го века.
English summary:
Both свеч and свечей are appropriate, though first form is 5-6 times as rare. This is not a new tendency, both forms are valid and completely interchangeable since at least the 19th century.


Q:

Ruby version syntax, x.x.x-dev, preview, rc, what is the oldest and newest?

I want to ask about naming convention of ruby version.
According to this quesion ruby follows Semantic Versioning, but I could not find about x.x.x-dev and x.x.x-preview syntax in the document.
I think dev comes first and then preview, and at last rc comes up.
Do you know where is the ruby official document that explains about their versioning convention?

A:

I'm not sure this is documented somewhere, however these are the most common conventions used in the Ruby core development

dev means the development version. It's the first stage, no public release. Normally you can download a night build or snapshot
preview is also what other projects normally call beta release.
rc is the release candidate, very close to the release
finally, you have the stable release


Q:

Image flickering in imageView when list is scrolled or new image is downloaded in new row

I have gone through many questions similar to mine of images flickering problem.
I am not able to correct it. Being a beginner,I am not able to understand what to do.
Here is my code.. where I set thumbnail for a image.
private void setThumbnail(final ContentResolver contentResolver, final ViewHolder aHolder,
        final Uri uri) {
    new AsyncTask<String, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(String... params) {

            Bitmap result = mBitmapCache.get(uri.toString());

            if (result == null)
                return getThumbnail(contentResolver, uri);
            else
                return result;
        }

        @Override
        protected void onPostExecute(Bitmap result) {

            if (uri != null && result != null) {
                //                    Log.d(TAG, "setThumbnail result not  null");
                //                    Log.d(TAG, "uri= "+uri);
                //                    Log.d(TAG, "aHolder.mMediaUri= "+aHolder.mMediaUri);
                mBitmapCache.put(uri.toString(), result);

                // confirm the holder is still paired to this uri
                if (!uri.equals(aHolder.mMediaUri)) {
                    return;
                }

                // set the thumbnail
                 ImageLoader imageLoader=ImageLoader.getInstance();
                imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
                DisplayImageOptions options = new DisplayImageOptions.Builder()
           //     .showImageForEmptyUri(R.drawable.ic_empty)
           //   .showImageOnFail(R.drawable.ic_error)
                .resetViewBeforeLoading(true).cacheOnDisk(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
                .cacheInMemory(true)
                .displayer(new FadeInBitmapDisplayer(300)).build();

                imageLoader.displayImage(uri.toString(), aHolder.mMediaThumbnail, options);
               // aHolder.mMediaThumbnail.setImageBitmap(result);
            } else {
                //                    Log.d(TAG, "setThumbnail result  null");
            }
          }
       }.execute();
   }

A:

In ListView view is added when it is required (See https://stackoverflow.com/a/14108676/2274724). So your item will create when you call notifyDataSetChange() or scroll your list.
So whenever your view is created your image will load again from cache which results into flickering. There is a solution :
First Load image in background thread (Either from network or assets) then create a bitmap cache as u did but instead of getting image using AsyncTask get Image directly if it exist in bitmap cache (But this is again not a good way because it will stop flickering but list scroll will not be smooth when size is large).
I will Suggest use UniversalImageLoader. They implemented memory cache in much better way.
private void setThumbnail(final ContentResolver contentResolver, final ViewHolder aHolder,
        final Uri uri) {
ImageLoader.getInstance().displayImage(
                            uri.toString(),
                            aHolder.mMediaThumbnail, getDisplayOption());
}

// Add or remove option according to your requirement
private DisplayImageOptions getDisplayOption() {
        return new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.ic_launcher)
                .showImageOnLoading(R.drawable.ic_launcher)
                .showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
                .cacheOnDisk(true).resetViewBeforeLoading(true)
                .displayer(new RoundedBitmapDisplayer(22))
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                .bitmapConfig(Bitmap.Config.RGB_565).build();
    }

//Put it in your Application file and call it just once.
private void initImageLoader() {

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getApplicationContext())
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .defaultDisplayImageOptions(getDisplayOption()).build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }


Q:

C:How to load a list from a file and save it at the end of the program

I'm working on two functions. The first one loads a list from a file into the program (at the start) and the second one saves the list's data to the file. I've tried to write the two functions but I'm having a hard time(I'm not really good at programming). Here are the structs I'm using I'm also adding the define of index and the creation of the list:
#define index 30

typedef struct dataR* data;
    struct dataR{
        int age;
        char name[index];

    };

    typedef struct nodeR* node;
    struct nodeR{
        data a;
        node next;

    };

    typedef struct listR* list;
    struct listR{
        node head, tail, curr;
        int size;
    };

list list_create(){
    list List=malloc(sizeof(struct listR));
    assert(List);
    List->head=NULL;
    List->tail=NULL;
    List->curr=NULL;
    List->size=0;
    return List;
}

Here is the function to load the file data into the list (at the start of the program). Obviously it is wrong but I don't know how to load the data to each node since the list is empty:
    list load(char *filename, list List)
    {
       FILE *fd=fopen("filename","r");
       fscanf(fd, "%d",&(List->head->a->age));
       fscanf(fd, "%s",&(List->head->a->name[index-1]));
       fclose(fd);
       fd=NULL;
    }

And here is the function that save all of the list's data at the end of the program :
    void save(char *filename, list List)
    {
       FILE *fd=fopen("filename.dat","w");
       if (fd==NULL)
       {
          printf("File does not exist");
          return;
       }
       fwrite(List->head->a, sizeof(struct dataR),1,fd);
       node tmp=List->head->next;
       while(tmp->next!=NULL)
       {
          fwrite(tmp->next->a, sizeof(struct dataR),1,fd);
          tmp=tmp->next;
       }

       fclose(fd);
       fd=NULL;
    }

The data in the file should look kind like this:
35 Nick
29 Jim
19 Helen

Well, ofcourse the functions don't do that as they are. So I need some help to improve them. Any tips (on files) and help is much appreciated.I'm sorry for the long post. Thank you for your time.

A:

To fix like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#define S_(v) #v
#define S(v) S_(v) //stringify

#define MAX_NAME_LENGTH 30 //index is bad name

typedef struct dataR* data;
struct dataR{
    int age;
    char name[MAX_NAME_LENGTH + 1];
};

typedef struct nodeR* node;
struct nodeR{
    data a;
    node next;
};

typedef struct listR* list;
struct listR{
    node head, tail, curr;//curr unused?
    int size;
};

list list_create(void){
    list List = malloc(sizeof(*List));
    assert(List);
    List->curr = List->tail = List->head = NULL;
    List->size=0;
    return List;
}

void addList(list List, data new_data){
    node new_node = malloc(sizeof(*new_node));
    new_node->a = new_data;
    new_node->next = NULL;
    if(List->head == NULL)
        List->head = List->tail = new_node;
    else
        List->tail = List->tail->next = new_node;
    ++List->size;
}

list load(const char *filename, list List){
    FILE *fd = fopen(filename,"r");//"filename"--> filename, LOL
    if(!fd){
        fprintf(stderr, "%s can't open in load.\n", filename);
        perror("fopen");
        return NULL;
    }
    int age;
    while(EOF != fscanf(fd, "%d", &age)){// or 1 == fscanf(fd, "%d", &age)){
        data new_data = malloc(sizeof(*new_data));
        new_data->age = age;
        fscanf(fd, "%" S(MAX_NAME_LENGTH) "s", new_data->name);
        addList(List, new_data);
    }
    fclose(fd);
    //fd=NULL;//meaningless
    return List;//need return value;
}

void save(const char *filename, list List){
    FILE *fd=fopen(filename, "w");
    if(!fd){
        fprintf(stderr, "%s can't open in save.\n", filename);
        perror("fopen");
        return ;
    }
    //fwrite(List->head->a, sizeof(struct dataR),1,fd);//fwrite doesn't match load
    node tmp = List->head;
    while(tmp){
        fprintf(fd, "%d %s\n", tmp->a->age, tmp->a->name);
        tmp = tmp->next;
    }
    fclose(fd);
}

int main(void){
    list List = list_create();

    load("list.txt", List);
    printf("List hold %d data.\n", List->size);
    data addData = malloc(sizeof(*addData));
    addData->age = 73;
    strcpy(addData->name, "Ken");
    addList(List, addData);
    save("list.txt", List);
    //deallocate
    return 0;
}


Q:

jquery, javascript not working in bootstrap

I'm using JQuery and bootstrap, and when I try to click the button that should invoke the function, it doesn't work. I've looked in the developer console and there is nothing there, anyone know?

        <title>Bill</title>

        <link rel="stylesheet" href="css/bootstrap.min.css"/>
        <link rel="stylesheet" href="css/jumbotron-narrow-me.css"/>

                welcome to opposition clicker, its amazing. it has one upgrade.
                "opposition" when you get this, you will get +100 0Cs' every second.

aasasa

        <button id="ocs" type="button" class="btn btn-lg btn-success">0Cs'</button>

A:

You just need to close some script tags properly and place your script
in the bottom:-)

    <title>Bill</title>

    <link data-require="bootstrap@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />

                welcome to opposition clicker, its amazing. it has one upgrade.
                "opposition" when you get this, you will get +100 0Cs' every second.

aasasa

    <button id="ocs" type="button" class="btn btn-lg btn-success">0Cs'</button>

Plunker
PS:- I didn't added the jumbotron-narrow-me.css in example because it is not available on plunker but hope it helps :-)


Q:

how to detect the secondary finger on touching the screen not at same time in android touchlistener?

How to detect an additional finger on the screen? E.g. I touch the screen using one finger and after sometime I keep the first finger on screen and then touch the screen using other finger while keeping first finger as it is? How to detect the second finger touch in Touch Listener?

A:

The MotionEvent.ACTION_POINTER_DOWN and MotionEvent.ACTION_POINTER_UP are send starting with the second finger. For the first finger MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP are used.
The getPointerCount() method on MotionEvent allows you to determine the number of pointers on the device. All events and the position of the pointers are included in the instance of MotionEvent which you receive in the onTouch() method.
To track the touch events from multiple pointers you have to use the MotionEvent.getActionIndex() and the MotionEvent.getActionMasked() methods to identify the index of the pointer and the touch event which happened for this pointer.
    int action = MotionEventCompat.getActionMasked(event);
// Get the index of the pointer associated with the action.
int index = MotionEventCompat.getActionIndex(event);
int xPos = -1;
int yPos = -1;

Log.d(DEBUG_TAG,"The action is " + actionToString(action));

if (event.getPointerCount() > 1) {
    Log.d(DEBUG_TAG,"Multitouch event");
    // The coordinates of the current screen contact, relative to
    // the responding View or Activity.
    xPos = (int)MotionEventCompat.getX(event, index);
    yPos = (int)MotionEventCompat.getY(event, index);

} else {
    // Single touch event
    Log.d(DEBUG_TAG,"Single touch event");
    xPos = (int)MotionEventCompat.getX(event, index);
    yPos = (int)MotionEventCompat.getY(event, index);
}
...

// Given an action int, returns a string description
public static String actionToString(int action) {
    switch (action) {

        case MotionEvent.ACTION_DOWN: return "Down";
        case MotionEvent.ACTION_MOVE: return "Move";
        case MotionEvent.ACTION_POINTER_DOWN: return "Pointer Down";
        case MotionEvent.ACTION_UP: return "Up";
        case MotionEvent.ACTION_POINTER_UP: return "Pointer Up";
        case MotionEvent.ACTION_OUTSIDE: return "Outside";
        case MotionEvent.ACTION_CANCEL: return "Cancel";
    }
    return "";
}

For more details please visit Google Handling Multi-Touch Gestures .


Q:

Usage of Philanthropist Flare as Schizoid

Suppose I'm playing as Schizoid. I have the power to alter reality, so I choose one of the six new cards to be the new win condition. That card is face down.
Then suppose I use Philanthropist Flare:

Send one of your ships to the warp to lend your power to another player for the duration of the encounter. Until the end of the encounter, that player is considered to have your power instead of his or her own. You may not use your power while it is loaned out. The player may not refuse the loan of your power.

Would the player I use this on get to look at the win condition card?

A:

I'll start by saying that there won't be an explicit answer to this question. Cosmic Encounter is about interactions, and given the number of aliens with different powers, sometimes you just have to make it up as you go and use some logic to come to the best conclusion. I think this is probably one of those situations.
My interpretation would be when you play the Philanthropist Flare as the Schizoid, the player you lend your power to can look at the win condition. The most logical reasoning for this is presented by dorakeen in a different answer: the player with the Schizoid power "is responsible to announce when any player(s) have fulfilled the winning conditions". When you use the Philanthropist Flare, you no longer have your power and as such cannot declare a win condition met. The person who is now the Schizoid, even temporarily, has that job.
Additionally, there's nothing on the Schizoid card that says you can't show the alternate win condition to other players. If something in the game would cause that card to be revealed to another player or players for some reason, nothing is there to stop that event. The lack of specification about whether other players could see that card leads me to believe that it could be shown.
Having said that, if you and your game group feel that the answer is actually no, there's nothing in the rules to contradict you. Remember the game is about interactions, so do what makes the most sense to you.


Q:

dial USSD code from iphone programmatically

How to dial USSD code for iphone programmatically?
I searched and found that iOS 7 has already blocked use of USSD code for security reason and in iPhones with < iOS7 we can dial a USSD code manualy but not programmatically.
Any one have an idea, can we call USSD programmatically like:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:\*123* <2334555>#"]]?

A:

You cannot dial a number containing * or # characters. Apple doesn't allow them in a dial string for security reasons.
Apple Documentation says :

To prevent users from maliciously redirecting phone calls or changing
  the behavior of a phone or account, the Phone app supports most, but
  not all, of the special characters in the tel scheme. Specifically, if
  a URL contains the * or # characters, the Phone app does not attempt
  to dial the corresponding phone number. If your app receives URL
  strings from the user or an unknown source, you should also make sure
  that any special characters that might not be appropriate in a URL are
  escaped properly. For native apps, use the
  stringByAddingPercentEscapesUsingEncoding: method of NSString to
  escape characters, which returns a properly escaped version of your
  original string.


Q:

How do we deploy application from azure devops using Pipelines to azure appservice with a different subscription and organization

I am setting up a CI/CD Pipeline  for my organization, we are service company who serve a customer who are using Azure Appservice as their platform with their own subscription.
Now we are planning to  buy Azure DevOps subscription by our own and start using it for our 5 projects to build CI/CD pipeline and release pipeline is  targeted to Customer Azure Appservice.
I am sure that  somebody have already done it and what are the challenges in it. Usually when I am doing in the same organization we create Service connections and it works, wanted to know how it works in case of different subscriptions and different organizations.

A:

You would need to create service principal\azure ad users for azure powershell to rely on for silent auth (examples). After that you can just use New-AzResourceGroupDeployment cmdlet to do the deployments.
Alternatively you can manually create a service connection for an existing Service principal in customers tenant (document covering that).


Q:

If I quit my PhD, would it make my advisor look bad?

I am considering quitting my PhD in computer science, because after doing a software engineering internship I realized I enjoy that kind of work much more.
My advisor has been very kind to me, on both a professional and a personal level, and if I quit it might make her look bad. She is an assistant professor and I was her first student. I do not want people to think she was the one who made me quit.
Are people going to wonder if she was the reason I quit?
How much of an effect would this have on her career?

A:

You are a nice guy, but let me tell you this: no matter if it makes your advisor look bad, if you really like the job in the company and believe it's the best thing for you, then you should quit your PhD and take the job. Doing your PhD just because of your advisor will not do any good to either you or your advisor.
Because pursuing a PhD requires a lot of determination. No matter how your advisor is kind to you, making your advisor look good will not be enough as a sole motivation for your PhD. If you don't quit now, you will quit later and it may cause more damage to your advisor.
For a complete stranger like me, if a guy quits his PhD after 1st or 2nd year, there are many reasons beside a bad advisor: maybe the guy himself finds PhD too difficult, or he changes his mind etc and etc. But if someone quits his PhD after 5th or 6th year, I would think there must be something wrong with the supervision.

A:

If I quit my PhD, would it make my advisor look bad?

Absolutely not -- at least, not in the eyes of anyone who wasn't born yesterday. Most of us realize that PhD students are autonomous creatures with their own lives, hopes, dreams and ambitions. Although certainly there are scenarios in which a bad advisor is the cause or catalyst for a graduate student's decision to quit their PhD, only a fool would jump to the completely unsubstantiated conclusion that this was the case here.
With that said, it is certainly true that if you finish your PhD, it would make your advisor look good.
And with that said, a PhD is such a huge undertaking that I think you'd be hard pressed to find anyone who thinks anyone should ever do a PhD to please someone else. You shouldn't do a PhD to make your mother happy; you shouldn't do a PhD to make your girlfriend or boyfriend happy; and by the same token, you shouldn't do a PhD to make your advisor happy. If she was kind to you, go and buy her a present, or write her a poem, or dedicate your first software product at the engineering firm to her. But I strongly advise you to stick with your PhD if, and only if, this is truly what you, and only you, want to do for yourself.

A:

I read your original post; allow me to respond to that first. In my opinion, based on the information you provide, you may want to examine your Ph.D. situation ignoring the internship for the moment. Do you enjoy what you're doing? Do you like working with your adviser? Is it a good learning experience? Do you value the prospect of holding a Ph.D.?
If the answer is Yes, I would caution you against jumping to conclusions based on an internship. Internships are good fun, in fact they are meant to be since the goal is for you to fall in love with the company as much as they are the other way (if not more). A Ph.D. is a bet on the long run (as is a college degree) and there are sacrifices involved.
If the answer is No, you have a tough decision to make and I can't really tell you what you should do, but in general it wouldn't seem wise to stick to something you dislike or not enjoy.
In general I would disregard what "people have been saying." You have not experienced the kind of jobs that you can access only with a Ph.D. Some of them are insanely fun. This is your decision, not theirs.
As for your adviser, yes your decision may hurt her career if she is an assistant professor on a tenure clock, and/or depending on many other factors. I doubt anyone would see this as a failure on her part, however.
All the best.


Q:

Length Contraction And Simultaneity

I wanted to derive length contraction from the Lorentz transformation, but I keep getting stuck on problems with simultaneity in my derivation.  At some point, I came across Wikipedia's article on Length Contraction where, in the section labeled "Derivation", it states

In an inertial reference frame $S^\prime$, $x_1^{\prime}$ and
  $x_2^{\prime}$ shall denote the endpoints for an object of length
  $L_0^\prime$ at rest in this system. The coordinates in $S^\prime$ are
  connected to those in $S$ by the Lorentz transformations as follows:
$ x_1^{\prime} = \frac{x_1-vt_1}{\sqrt{1-\frac{v^2}{c^2}}} $ and $
 x_2^{\prime} = \frac{x_2-vt_2}{\sqrt{1-\frac{v^2}{c^2}}} $
As this object is moving in $S$, its length $L$ has to be measured
  according to the above convention by determining the simultaneous
  positions of its endpoints, so we have to put $t_1=t_2$. Because
  $L=x_2-x_1$ and $L_0^\prime=x_2^\prime-x_1^\prime$, we obtain
$ L_0^{\prime} = \frac{L}{\sqrt{1-\frac{v^2}{c^2}}}. $

I understand everything except for the line which reads $L_0^\prime=x_2^\prime-x_1^\prime.$  After setting $t_1=t_2$, it is possible to write $L=x_2-x_1,$ since events $1$ and $2$ are simultaneous.  However, in the primed inertial reference frame, which is moving with a nonzero velocity with respect to the laboratory frame, the events are not simultaneous.  Therefore, how can it be that $ L_0^\prime=x_2^\prime-x_1^\prime, $ since $ t_1^\prime \neq t_2^\prime? $

A:

You just confused the frames. In the derivation, $S'$ is the rest frame of the object of length $L'_0=x'_2-x'_1$. In that rest frame, the endpoints are simply at coordinates $x'_1$ and $x'_2$, regardless of $t'$. The length $L'_0$ in that rest frame is measured as the distance between two simultaneous events in that frame, i.e. events with $t'_1=t'_2$, and the result is, once again, $L'_0=x'_2-x'_1$. The world lines of both end points are vertical in that frame. Simple.
We want to know how this object looks like in another frame, $S$, which is moving relatively to $S'$. To measure the length $L_0$ in $S$, we have to see both endpoints simultaneously in $S$ i.e. impose $t_1=t_2$. That's exactly what they did and derived that in the frame $S$ where the object is moving, the length is measured to be $L_0 = L'_0 \cdot \sqrt{1-v^2/c^2}$. It is Lorentz-contracted.
Their derivation may have unnaturally exchanged various things, $S$ with $S'$, and they wrote the final relationship in the inverted way so that it looks like a "length dilatation", but the actual content of the derivation is right given their conventions.


Q:

Unexpected async/await behaviour

Here is a program that mimics the flow of my real case scenario:
using System;
using System.Threading.Tasks;

namespace TestAsync
{
    interface IInterface
    {
        Task<int> DoSomething(int i);
    }

    class MyClass : IInterface
    {
        public async void MainAsync()
        {
            var i = 1;
            Console.WriteLine("Start MainAsync:" + i);
            var t = DoSomething(i);
            Console.WriteLine("After DoSomething: " + i );
            i = await t;
            Console.WriteLine("Done waiting: " + i);
        }

        public async Task<int> DoSomething(int i)
        {
            i = i + 1;
            Console.WriteLine("In Something:" + i);
            await Task.Delay(1000);
            Console.WriteLine("After Long Process: " + i);
            return i;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var m = new MyClass();
            m.MainAsync();
            Console.WriteLine("Main done.");
        }
    }
}

The output I am getting is this:
Start MainAsync:1
In Something:2
After DoSomething: 1
Main done.
Press any key to continue . . .

This tells me that i = await t; is popping the process back up to Main and never comes back once done with the tasks.
What am I doing wrong?
I am looking for a result like:
Start MainAsync:1
In Something:2
After DoSomething: 1
After Long Process: 2
Done waiting: 2
Main done.
Press any key to continue . . .

or maybe
Start MainAsync:1
In Something:2
After DoSomething: 1
Main done.
After Long Process: 2
Done waiting: 2
Press any key to continue . . .

Thank you for your insight.

A:

Once the main method has completed you now no longer have any non-background threads running in your program, so the whole process will end.  The fact that you have code that is going to eventually fire at some point in the future doesn't change that.
This is why you would normally have a message loop at the top level of your application, able to accept and process messages, and wait for more messages if there are currently none to process.  Since the thread that is running the message pump would be a non-background thread, it wouldn't allow the process to end until the whole loop is closed.


Q:

Squeak smalltalk: why can't I activate the do it menu

I downloaded squeak 4.2 http://squeak.org/ and watch this very basic tutorial
http://www.youtube.com/watch?v=0w1Yub4eUAU
When I type 2 + 2 in workspace window and select right-click the line I can't get any popup menu with "do it" option.
Did I miss something ?

A:

Depending on your platform and configuration that menu may be activated either by a right-click or a middle-click. For Squeak on Windows I believe the default is to middle-click.
If the default feels unintuitive you can invert the right and middle mouse buttons.
To invert the mouse buttons for the current image:

Click on the world background
Select open... from the World menu
Select Preference Browser
Search for mouse in the preferences
Toggle swapMouseButtons

To invert the mouse buttons on the Windows VM:

Open the system menu (small Squeak icon in the top-left window corner)
Under VM Preferrences > Mouse mapping toggle 3 button mouse

You can also activate that menu by ALT-clicking or use the quicker ALT-d shortcut for "do it".


Q:

If $\Sigma$ is finitely satisfiable, can both $\Sigma \cup \{ \phi\}$ and $\Sigma \cup \{ \neg \phi\}$ be finitely satisfiable?

In propositional logic, if $\Sigma$ is finitely satisfiable, can both $\Sigma \cup \{ \phi\}$ and $\Sigma \cup \{ \neg \phi\}$ be finitely satisfiable?
I proved that at least one of $\Sigma \cup \{ \phi\}$ and $\Sigma \cup \{ \neg \phi\}$ must be finitely satisfiable, but could both be?

A:

Of course both are satisfiable:
Recall that a set of sentences $S$ is complete if, for every sentence $\varphi$, either $S \vdash \varphi$ or $S \vdash \neg \varphi$.
All we need to show is that not every finite satisfiable set is complete. That is, as observed in the comments, it suffices give a counterexample of an incomplete finite satisfiable set. And for any signature you have, there are certainly many of them:

$\emptyset$ is (vacuously) finite satisfiable, but incomplete.
$\{\alpha\}$ is finite satisfiable, but incomplete.
$\{\alpha, \alpha\rightarrow \alpha\}$ is finite satisfiable, but incomplete and so on

For any arbitrary sentences $\alpha, \beta$ of your language.


Q:

Jquery code is not executing

I am currently learning jQuery. I am having some problems with the following code. I am trying to make my website move using some buttons, but once i click them it does not seem to work. Below is my jquery code.
jQuery(document).ready(function ($) {
    //initialise Stellar.js
    $(window).stellar();
    //Cache some variables
    var links = $('.navigation').find('li');
    slide = $('.slide');
    button = $('.button');
    mywindow = $(window);
    htmlbody = $('html,body');
    //Setup waypoints plugin
    slide.waypoint(function (event, direction) {
        //cache the variable of the data-slide attribute associated with each slide
        dataslide = $(this).attr('data-slide');
        //If the user scrolls up change the navigation link that has the same data-slide attribute as the slide to active and
        //remove the active class from the previous navigation link
        if(direction === 'down') {
            $('.navigation li[data-slide="' + dataslide + '"]').addClass('active').prev().removeClass('active');
        }
        // else If the user scrolls down change the navigation link that has the same data-slide attribute as the slide to active and
        //remove the active class from the next navigation link
        else {
            $('.navigation li[data-slide="' + dataslide + '"]').addClass('active').next().removeClass('active');
        }
    });
    //waypoints doesnt detect the first slide when user scrolls back up to the top so we add this little bit of code, that removes the class
    //from navigation link slide 2 and adds it to navigation link slide 1.
    mywindow.scroll(function () {
        if(mywindow.scrollTop() === 0) {
            $('.navigation li[data-slide="1"]').addClass('active');
            $('.navigation li[data-slide="2"]').removeClass('active');
        }
    });
    //Create a function that will be passed a slide number and then will scroll to that slide using jquerys animate. The Jquery
    //easing plugin is also used, so we passed in the easing method of 'easeInOutQuint' which is available throught the plugin.
    function goToByScroll(dataslide) {
        htmlbody.animate({
            scrollTop: $('.slide[data-slide="' + dataslide + '"]').offset().top
        }, 2000, 'easeInOutQuint');
    }
    //When the user clicks on the navigation links, get the data-slide attribute value of the link and pass that variable to the goToByScroll function
    links.click(function (e) {
        e.preventDefault();
        dataslide = $(this).attr('data-slide');
        goToByScroll(dataslide);
    });
    //When the user clicks on the button, get the get the data-slide attribute value of the button and pass that variable to the goToByScroll function
    button.click(function (e) {
        e.preventDefault();
        dataslide = $(this).attr('data-slide');
        goToByScroll(dataslide);
    });
});

It would be great if anyone can help me solve my problem.

A:

Put your script before the closing tag body (</body>) and include Jquery library


Q:

Proving the intersection of two sets is bounded.

Two sets of real numbers A and B.  A is bounded above, B is bounded below.  Prove their intersection is bounded.
I understand that the union of the two sets A and B would be bounded but I can't necessarily see how the intersection is bounded.  How do we know that their intersection is not the empty set?

A:

The empty set is bounded: $\forall x \in \emptyset : (x \le 1) \land (x \ge -1)$ is certainly a (vacuusly) true statement.
The union of two such sets need not be bounded: Take $A = (-\infty, 1]$, $B= [-1,\infty)$, then $A \cup B= \mathbb{R}$ but $A \cap B = [-1,1]$.
To see the statement: let $a_0$ be an upperbound for $A$ and $b_0$ a lower bound for $B$. Let $x \in A \cap B$ be arbitrary. Then $x \in A$ so $x \le a_0$ an  $x\in B$ too, so $b_0 \le x$. So $A \cap B \subseteq [a_0, b_0]$ hence $A \cap B$ is bounded.


Q:

Get bounds of unrotated rotated rectangle

I have a rectangle that has a rotation already applied to it. I want to get the the unrotated dimensions (the x, y, width, height).
Here is the dimensions of the element currently:
Bounds at a 90 rotation: {
 height     30
 width      0
 x          25
 y          10
}

Here are the dimensions after the rotation is set to none:
Bounds at rotation 0 {
 height     0
 width      30
 x          10
 y          25
}

In the past, I was able to set the rotation to 0 and then read the updated bounds . However, there is a bug in one of the functions I was using, so now I have to do it manually.
Is there a simple formula to get the bounds at rotation 0 using the info I already have?
Update: The object is rotated around the center of the object.
UPDATE:
What I need is something like the function below:
function getRectangleAtRotation(rect, rotation) {
    var rotatedRectangle = {}
    rotatedRectangle.x = Math.rotation(rect.x * rotation);
    rotatedRectangle.y = Math.rotation(rect.y * rotation);
    rotatedRectangle.width = Math.rotation(rect.width * rotation);
    rotatedRectangle.height = Math.rotation(rect.height * rotation);
    return rotatedRectangle;
}

var rectangle = {x: 25, y: 10, height: 30, width: 0 };
var rect2 = getRectangleAtRotation(rect, -90); // {x:10, y:25, height:0, width:30 }

I found a similar question here.
UPDATE 2
Here is the code I have. It attempts to get the center point of the line and then the x, y, width, and height:
var centerPoint = getCenterPoint(line);
var lineBounds = {};
var halfSize;

halfSize = Math.max(Math.abs(line.end.x-line.start.x)/2, Math.abs(line.end.y-line.start.y)/2);
lineBounds.x = centerPoint.x-halfSize;
lineBounds.y = centerPoint.y;
lineBounds.width = line.end.x;
lineBounds.height = line.end.y;

function getCenterPoint(node) {
    return {
        x: node.boundsInParent.x + node.boundsInParent.width/2,
        y: node.boundsInParent.y + node.boundsInParent.height/2
    }
}

I know the example I have uses a right angle and that you can swap the x and y with that but the rotation can be any amount.
UPDATE 3
I need a function that returns the unrotated bounds of a rectangle. I have the bounds at a specific rotation already.
function getUnrotatedRectangleBounds(rect, currentRotation) {
    // magic
    return unrotatedRectangleBounds;
}

A:

I think I can handle the calculation of the bounds size without too much effort (few equations), I'm not sure, instead, how you would like x and y to be handled.
First, let's properly name things:

Now, we want to rotate it by some angle alpha (in radians):

To calculate the green sides, it is clear that it's made of two repeated rectangle-triangles as the following:

So, solving angles first, we know that:

the sum of the angles of a triangle is PI / 2, or 180°;
the rotation is alpha;
one angle gamma is PI / 4, or 90°;
the last angle, beta, is gamma - alpha;

Now, knowing all the angles and a side, we can use the Law of Sines to calculate other sides.
As a brief recap, the Law of Sines tells us that there is an equality between the ratio of a side length and it's opposite angle. More info here: https://en.wikipedia.org/wiki/Law_of_sines
In our case, for the upper left triangle (and the bottom right one), we have:

Remember that AD is our original height.
Given that the sin(gamma) is 1, and we also know the value of AD, we can write the equations:

For the upper right triangle (and the bottom left one), we then have:

Having all needed sides, we can easily calculate the width and height:
width = EA + AF
height = ED + FB

At this point we can write a quite easy method that, given a rectangle and a rotation angle in radians, can return new bounds:
function rotate(rectangle, alpha) {
  const { width: AB, height: AD } = rectangle
  const gamma = Math.PI / 4,
        beta = gamma - alpha,
        EA = AD * Math.sin(alpha),
        ED = AD * Math.sin(beta),
        FB = AB * Math.sin(alpha),
        AF = AB * Math.sin(beta)

  return {
    width: EA + EF,
    height: ED + FB
  }
}

This method can then be used like:
const rect = { width: 30, height: 50 }
const rotation = Math.PI / 4.2 // this is a random value it put here
const bounds = rotate(rect, rotation)

Hope there aren't typos...

A:

I think I might get a solution but, for safety, I prefer to prior repeat what we have and what we need to be sure I understood everything correctly. As I said in a comment, english isn't my native language and I already wrote a wrong answer due to my lack of understanding of the problem :)
What we have

We know that at x and y there is a bounds rectangle (green) of size w and h that contains another rectangle (the grey dotted one) rotated of alpha degrees.
We know that the y axis is flipped relatively to the Cartesian one, and that makes the angle to be considered clockwise instead of counter-clockwise.
What we need

At first, we need to find the 4 vertices of the inner rectangle (A, B, C and D) and, knowing the position of the vertices, the size of the inner rectangle (W and H).
As a second step, we need to counter rotate the inner rectangle to 0 degrees, and find it's position X and Y.

Find the vertices
Generally speaking for each vertex we know only one coordinate, the x or the y. The other one "slides" along the side of the bounding box in relation to the angle alpha.
Let's start with A: we know Ay, we need Ax.
We know that the Ax lies between x and x + w in relation to the angle alpha.
When alpha is 0°, Ax is x + 0. When alpha is 90°, Ax is x + w. When alpha is 45°, Ax is x + w / 2.
Basically, Ax grows in relation of the sin(alpha), giving us:

Having Ax, we can easily compute Cx:

In the same way we can compute By and then Dy:

Writing some code:
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// alpha is the rotation IN RADIANS
const vertices = (bounds, alpha) => {
  const { x, y, w, h } = bounds,
        A = { x: x + w * Math.sin(alpha), y },
        B = { x, y: y + h * Math.sin(alpha) },
        C = { x: x + w - w * Math.sin(alpha), y },
        D = { x, y: y + h - h * Math.sin(alpha) }
  return { A, B, C, D }
}

Finding the sides
Now that we have all the vertices, we can easily compute the inner rectangle sides, we need to define a couple more points E and F for clarity of explanation:

Its clearly visible that we can use the Pitagorean Theorem to compute W and H  with:

where:

In code:
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// vertices is a POJO with shape: { A, B, C, D }, as returned by the `vertices` method
const sides = (bounds, vertices) => {
  const { x, y, w, h } = bounds,
        { A, B, C, D } = vertices,
        EA = A.x - x,
        ED = D.y - y,
        AF = w - EA,
        FB = h - ED,
        H = Math.sqrt(EA * EA + ED * ED),
        W = Math.sqrt(AF * AF + FB * FB
  return { h: H, w: W }
}

Finding the position of the counter-rotated inner rectangle
First of all, we have to find the angles (beta and gamma) of the diagonals of the inner rectangle.

Let's zoom in a little bit and add some additional letters for more clarity:

We can use the Law of Sines to get the equations to compute beta:

To make some calculations we have:

We need to compute GC first in order to have at least one side of the equation completely known. GC is the radius of the circumference the inner rectangle is inscribed in and also half of the inner rectangle diagonal.
Having the two sides of the inner rectangle, we can use the Pitagorean Theorem again:

With GC we can solve the Law of Sines on beta:

we know that sin(delta) is 1

Now, beta is the angle of the vertex C in relation with the unrotated x axis.

Looking again at this image, we can easily get the angles of all the other vertices:

Now that we have almost everything, we can compute the new coordinates of the A vertex:

From here, we need to translate both Ax and Ay because they are related to the center of the circumference, which is x + w / 2 and y + h / 2:

So, writing the last piece of code:
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// sides is a POJO with shape: { w, h }, as returned by the `sides` method
const origin = (bounds, sides) => {
  const { x, y, w, h } = bounds
  const { w: W, h: H } = sides
  const GC = r = Math.sqrt(W * W + H * H) / 2,
        IC = H / 2,
        beta = Math.asin(IC / GC),
        angleA = Math.PI + beta,
        Ax = x + w / 2 + r * Math.cos(angleA),
        Ay = y + h / 2 + r * Math.sin(angleA)
  return { x: Ax, y: Ay }
}

Putting all together...
// bounds is a POJO with shape: { x, y, w, h }, update if needed
// rotations is... the rotation of the inner rectangle IN RADIANS
const unrotate = (bounds, rotation) => {
  const points = vertices(bounds, rotation),
        dimensions = sides(bounds, points)
  const { x, y } = origin(bounds, dimensions)
  return { ...dimensions, x, y }
}

I really hope this will solve your problem and that there are no typos. This was a very, veeeery funny way to spend my weekend :D

// bounds is a POJO with shape: { x, y, w, h }, update if needed
// alpha is the rotation IN RADIANS
const vertices = (bounds, alpha) => {
 const { x, y, w, h } = bounds,
    A = { x: x + w * Math.sin(alpha), y },
    B = { x, y: y + h * Math.sin(alpha) },
    C = { x: x + w - w * Math.sin(alpha), y },
    D = { x, y: y + h - h * Math.sin(alpha) }
 return { A, B, C, D }
 }

// bounds is a POJO with shape: { x, y, w, h }, update if needed
// vertices is a POJO with shape: { A, B, C, D }, as returned by the `vertices` method
const sides = (bounds, vertices) => {
  const { x, y, w, h } = bounds,
      { A, B, C, D } = vertices,
      EA = A.x - x,
      ED = D.y - y,
      AF = w - EA,
      FB = h - ED,
      H = Math.sqrt(EA * EA + ED * ED),
      W = Math.sqrt(AF * AF + FB * FB)
  return { h: H, w: W }
}

// bounds is a POJO with shape: { x, y, w, h }, update if needed
// sides is a POJO with shape: { w, h }, as returned by the `sides` method
const originPoint = (bounds, sides) => {
  const { x, y, w, h } = bounds
  const { w: W, h: H } = sides
  const GC = Math.sqrt(W * W + H * H) / 2,
      r = Math.sqrt(W * W + H * H) / 2,
      IC = H / 2,
      beta = Math.asin(IC / GC),
      angleA = Math.PI + beta,
      Ax = x + w / 2 + r * Math.cos(angleA),
      Ay = y + h / 2 + r * Math.sin(angleA)
  return { x: Ax, y: Ay }
}

// bounds is a POJO with shape: { x, y, w, h }, update if needed
// rotations is... the rotation of the inner rectangle IN RADIANS
const unrotate = (bounds, rotation) => {
  const points = vertices(bounds, rotation)
  const dimensions = sides(bounds, points)
  const { x, y } = originPoint(bounds, dimensions)
  return { ...dimensions, x, y }
}

function shortNumber(value) {
  var places = 2;
 value = Math.round(value * Math.pow(10, places)) / Math.pow(10, places);
 return value;
}

function getInputtedBounds() {
  var rectangle = {};
  rectangle.x = parseFloat(app.xInput.value);
  rectangle.y = parseFloat(app.yInput.value);
  rectangle.w = parseFloat(app.widthInput.value);
  rectangle.h = parseFloat(app.heightInput.value);
  return rectangle;
}

function rotationSliderHandler() {
  var rotation = app.rotationSlider.value;
  app.rotationOutput.value = rotation;
  rotate(rotation);
}

function rotationInputHandler() {
  var rotation = app.rotationInput.value;
  app.rotationSlider.value = rotation;
  app.rotationOutput.value = rotation;
  rotate(rotation);
}

function unrotateButtonHandler() {
  var rotation = app.rotationInput.value;
  app.rotationSlider.value = 0;
  app.rotationOutput.value = 0;
  var outerBounds = getInputtedBounds();
  var radians = Math.PI / 180 * rotation;
  var unrotatedBounds = unrotate(outerBounds, radians);
  updateOutput(unrotatedBounds);
}

function rotate(value) {
  var outerBounds = getInputtedBounds();
  var radians = Math.PI / 180 * value;
  var bounds = unrotate(outerBounds, radians);
  updateOutput(bounds);
}

function updateOutput(bounds) {
  app.xOutput.value = shortNumber(bounds.x);
  app.yOutput.value = shortNumber(bounds.y);
  app.widthOutput.value = shortNumber(bounds.w);
  app.heightOutput.value = shortNumber(bounds.h);
}

function onload() {
  app.xInput = document.getElementById("x");
  app.yInput = document.getElementById("y");
  app.widthInput = document.getElementById("w");
  app.heightInput = document.getElementById("h");
  app.rotationInput = document.getElementById("r");

  app.xOutput = document.getElementById("x2");
  app.yOutput = document.getElementById("y2");
  app.widthOutput = document.getElementById("w2");
  app.heightOutput = document.getElementById("h2");
  app.rotationOutput = document.getElementById("r2");
  app.rotationSlider = document.getElementById("rotationSlider");
  app.unrotateButton = document.getElementById("unrotateButton");

  app.unrotateButton.addEventListener("click", unrotateButtonHandler);
  app.rotationSlider.addEventListener("input", rotationSliderHandler);
  app.rotationInput.addEventListener("change", rotationInputHandler);
  app.rotationInput.addEventListener("input", rotationInputHandler);
  app.rotationInput.addEventListener("keyup", (e) => {if (e.keyCode==13) rotationInputHandler() });

  app.rotationSlider.value = app.rotationInput.value;
}

var app = {};
window.addEventListener("load", onload);
* {
  font-family: sans-serif;
  font-size: 12px;
  outline: 0px dashed red;
}

granola {
  display: flex;
  align-items: top;
}

flan {
  width: 90px;
  display: inline-block;
}

hamburger {
  display: flex:
  align-items: center;
}

spagetti {
  display: inline-block;
  font-size: 11px;
  font-weight: bold;
  letter-spacing: 1.5px;
}

fish {
  display: inline-block;
  padding-right: 40px;
  position: relative;
}

input[type=text] {
  width: 50px;
}

input[type=range] {
  padding-top: 10px;
  width: 140px;
  padding-left: 0;
  margin-left: 0;
}

button {
  padding-top: 3px;
  padding-bottom:1px;
  margin-top: 10px;
}
<granola>
  <fish>
    <spagetti>Bounds of Rectangle</spagetti>

    <flan>x: </flan><input id="x" type="text" value="14.39">

    <flan>y: </flan><input id="y" type="text" value="14.39">

    <flan>width: </flan><input id="w" type="text" value="21.2">

    <flan>height: </flan><input id="h" type="text" value="21.2">

    <flan>rotation:</flan><input id="r" type="text" value="90">

    <button id="unrotateButton">Unrotate</button>
  </fish>

  <fish>
    <spagetti>Computed Bounds</spagetti>

    <flan>x: </flan><input id="x2" type="text" disabled="true">

    <flan>y: </flan><input id="y2" type="text"disabled="true">

    <flan>width: </flan><input id="w2" type="text" disabled="true">

    <flan>height: </flan><input id="h2" type="text" disabled="true">

    <flan>rotation:</flan><input id="r2" type="text" disabled="true">

    <input id="rotationSlider" type="range" min="-360" max="360" step="5">

  </fish>
</granola>

A:

How does this work?
Calculation using width, height, x and y
Radians and Angles
Using degrees calculate the radians and calculate the sin and cos angles:

function calculateRadiansAndAngles(){
  const rotation = this.value;
  const dr = Math.PI / 180;
  const s = Math.sin(rotation * dr);
  const c = Math.cos(rotation * dr);
  console.log(rotation, s, c);
}

document.getElementById("range").oninput = calculateRadiansAndAngles;
<input type="range" min="-360" max="360" id="range"/>

Generate 4 points
we assume the origin of a rectangle is the center with the location of 0,0
The double for loop will create the following value pairs for i and j: (-1,-1), (-1,1), (1,-1) and (1,1)
Using each pair, we can calculate one of the 4 square vectors.
(i.e for (-1,1), i = -1, j = 1)
const px = w*i/2; //-> 30 * -1/2 = -15
const py = h*j/2; //-> 50 * 1/2  = 25
//[-15,25]

Once we have a point, we can calculate the new position of that point by including the rotation.
const nx = (px*c) - (py*s);
const ny = (px*s) + (py*c);

Solution
Once all the points are calculated based off of the rotation, we can redraw our square.
Before the draw call, a translate is used to position the cursor at the x and y of the rectangle. This is the reason as to why I was able to assume the center and the origin of the rectangle was 0,0 for the calculations.

const canvas = document.getElementById("canvas");
const range = document.getElementById("range");
const rotat = document.getElementById("rotat");

range.addEventListener("input", function(e) {
  rotat.innerText = this.value;
  handleRotation(this.value);
})

const context = canvas.getContext("2d");
const container = document.getElementById("container");

const rect = {
  x: 50,
  y: 75,
  w: 30,
  h: 50
}

function handleRotation(rotation) {
  const { w, h, x, y } = rect;

  const dr = Math.PI / 180;
  const s = Math.sin(rotation * dr);
  const c = Math.cos(rotation * dr);

  const points = [];
  for(let i = -1; i < 2; i+=2){
    for(let j = -1; j < 2; j+=2){

      const px = w*i/2;
      const py = h*j/2;

      const nx = (px*c) - (py*s);
      const ny = (px*s) + (py*c);
      points.push([nx, ny]);
    }
  }
  //console.log(points);
  draw(points);

}

function draw(points) {
  context.clearRect(0,0,canvas.width, canvas.height);
  context.save();
  context.translate(rect.x+(rect.w/2), rect.y + (rect.h/2))
  context.beginPath();
  context.moveTo(...points.shift());
  [...points.splice(0,1), ...points.reverse()]
  .forEach(p=>{
    context.lineTo(...p);
  })
  context.fill();
  context.restore();
}

window.onload = () => handleRotation(0);
div {
  display: flex;
  background-color: lightgrey;
  padding: 0 5px;
}

div>p {
  padding: 0px 10px;
}

div>input {
  flex-grow: 1;
}

canvas {
  border: 1px solid black;
}

0

  <input type="range" id="range" min="-360" max="360" value="0" step="5" />

<canvas id="canvas"></canvas>


Q:

Debian GNU/Linux 9 (stretch) 64-bit doesn`t detect wireless

I can`t use my wi-fi on my dual boot laptop. In Windows it works perfectly, but in Debian it not.
> ip a:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
   valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
   valid_lft forever preferred_lft forever
2: enp4s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 18:31:bf:74:90:24 brd ff:ff:ff:ff:ff:ff
inet 192.168.31.220/24 brd 192.168.31.255 scope global dynamic enp4s0
   valid_lft 42027sec preferred_lft 42027sec
inet6 fe80::1a31:bfff:fe74:9024/64 scope link
   valid_lft forever preferred_lft forever

> lsusb:
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 005: ID 8087:0a2b Intel Corp.
Bus 001 Device 004: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card
Reader Controller
Bus 001 Device 003: ID 04f2:b57a Chicony Electronics Co., Ltd
Bus 001 Device 002: ID 046d:c077 Logitech, Inc. M105 Optical Mouse
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

> lspci:
00:00.0 Host bridge: Intel Corporation Device 5910 (rev 05)
00:01.0 PCI bridge: Intel Corporation Skylake PCIe Controller (x16) (rev 05)
00:02.0 VGA compatible controller: Intel Corporation Device 591b (rev 04)
00:04.0 Signal processing controller: Intel Corporation Skylake Processor Thermal Subsystem (rev 05)
00:14.0 USB controller: Intel Corporation Sunrise Point-H USB 3.0 xHCI Controller (rev 31)
00:14.2 Signal processing controller: Intel Corporation Sunrise Point-H Thermal subsystem (rev 31)
00:15.0 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO I2C Controller #0 (rev 31)
00:15.1 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO I2C Controller #1 (rev 31)
00:16.0 Communication controller: Intel Corporation Sunrise Point-H CSME HECI #1 (rev 31)
00:17.0 RAID bus controller: Intel Corporation 82801 Mobile SATA Controller [RAID mode] (rev 31)
00:1c.0 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #1 (rev f1)
00:1c.2 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #3 (rev f1)
00:1c.3 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #4 (rev f1)
00:1e.0 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO UART #0 (rev 31)
00:1e.2 Signal processing controller: Intel Corporation Sunrise Point-H Serial IO SPI #0 (rev 31)
00:1f.0 ISA bridge: Intel Corporation Sunrise Point-H LPC Controller (rev 31)
00:1f.2 Memory controller: Intel Corporation Sunrise Point-H PMC (rev 31)
00:1f.3 Audio device: Intel Corporation Device a171 (rev 31)
00:1f.4 SMBus: Intel Corporation Sunrise Point-H SMBus (rev 31)
01:00.0 3D controller: NVIDIA Corporation Device 1c8d (rev ff)
03:00.0 Network controller: Intel Corporation Device 24fd (rev 78)
04:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 15)

> lspci -knn | grep Net -A2:
03:00.0 Network controller [0280]: Intel Corporation Device [8086:24fd] (rev 78)
Subsystem: Intel Corporation Device [8086:0010]
Kernel modules: iwlwifi

A:

As sudo, do the following:
cat "deb http://httpredir.debian.org/debian/ stretch main contrib non-free" >> /etc/apt/sources.list
apt-get update
apt-get install firmware-iwlwifi
modprobe -r iwlwifi
modprobe iwlwifi

It should work now.


Q:

multiple Regex line changes: duplicate, replace and delete parts

I have text file:
/path/to/delete/dir1/dir2/dir3/file1.ext
/path/to/delete/dir1/dir2/dir3/file2.ext
/path/to/delete/dir1/dir2/dir3/file3.ext

I want copy duplicate each string and make some replacements to get this:
dir1/dir2/dir3/file1.ext dir1-dir2-dir3/file1.ext
dir1/dir2/dir3/file2.ext dir1-dir2-dir3/file2.ext
dir1/dir2/dir3/file3.ext dir1-dir2-dir3/file3.ext

I've made script, whitch delete leading path and duplicate string:
sed -e 's/\/path\/to\/delete\///' -e 's/.\+/\0 \0/'  list.txt

Now I've got this:
dir1/dir2/dir3/file1.ext dir1/dir2/dir3/file1.ext
dir1/dir2/dir3/file2.ext dir1/dir2/dir3/file2.ext
dir1/dir2/dir3/file3.ext dir1/dir2/dir3/file3.ext

But a have no idea to replace slashes after space.

A:

This might work for you (GNU sed):
sed -r 's|/path/to/delete/(.*)|\1 \1|;:a;s|/([^ /]*/[^ /]*)$|-\1|;ta' file

Delete require pattern and then duplicate the string.
Work backwards through the second string replacing all but the last / with -.


Q:

Is there a “right” way to Prototype functions in C++?

I was taught to do:
functionReturn function(dataType_of_parameter)

While more and more I have been seeing
functionReturn function(dataType_of_parameter parameter_identifier)

A:

Both suggestions are right ways to declare a function. The argument names are optional and make no difference to the compiler except in the function definition.
The advantage of naming function arguments in forward declarations is that a programmer can deduce the the purpose of the argument. Consider for example void copy(T* source, T* dest) versus void copy(T*, T*).


Q:

How to get column between two values as per user input

I am stuck on one solution I want to get column as per user in put value.

for 1000 Rs. i want all data below 1000.
for 2000 Rs. I want data between 1000 & 2000.
for 3000 Rs. I want data between 2000 & 3000.
for 4000 Rs. I want data between 4000 & 4000.

I have done it like below but it is not working.
     $product = Product::select('product_price')
                        ->get();

        foreach ($product as $value) {

            if($value->product_price == 1000){

                  $prod1 = Product::join('company', 'timeline_product.company_id', '=', 'company.company_id')
                    ->select('company.name', 'company.logo', 'timeline_product.company_id', 'timeline_product.product_name', 'timeline_product.product_desc', 'timeline_product.product_price','timeline_product.reward_points' ,'timeline_product.created_at', 'timeline_product.updated_at')
                    ->where('timeline_product.product_price','<=',1000)
                    ->orderBy('timeline_product.updated_at', 'desc')
                    ->limit($limit)
                    ->offset($offset)
                    ->get();

                   // $post = array('result' => $prod1);

            }elseif ($value->product_price == 2000) {

                    $prod2 = Product::join('company', 'timeline_product.company_id', '=', 'company.company_id')
                    ->select('company.name', 'company.logo', 'timeline_product.company_id', 'timeline_product.product_name', 'timeline_product.product_desc', 'timeline_product.product_price','timeline_product.reward_points' ,'timeline_product.created_at', 'timeline_product.updated_at')
                    ->whereBetween('timeline_product.product_price', [1000, 2000])
                    ->orderBy('timeline_product.updated_at', 'desc')
                    ->limit($limit)
                    ->offset($offset)
                    ->get();

                  // $post = array('result' => $prod2);

            }elseif ($value->product_price == 3000) {

                     $prod3 = Product::join('company', 'timeline_product.company_id', '=', 'company.company_id')
                    ->select('company.name', 'company.logo', 'timeline_product.company_id', 'timeline_product.product_name', 'timeline_product.product_desc', 'timeline_product.product_price','timeline_product.reward_points' ,'timeline_product.created_at', 'timeline_product.updated_at')
                    ->whereBetween('timeline_product.product_price', [2000, 3000])
                    ->orderBy('timeline_product.updated_at', 'desc')
                    ->limit($limit)
                    ->offset($offset)
                    ->get();
                  // $post = array('result' => $prod3);

            }elseif ($value->product_price == 4000) {

                     $prod4 = Product::join('company', 'timeline_product.company_id', '=', 'company.company_id')
                    ->select('company.name', 'company.logo', 'timeline_product.company_id', 'timeline_product.product_name', 'timeline_product.product_desc', 'timeline_product.product_price','timeline_product.reward_points' ,'timeline_product.created_at', 'timeline_product.updated_at')
                    ->whereBetween('timeline_product.product_price', [3000, 4000])
                    ->orderBy('timeline_product.updated_at', 'desc')
                    ->limit($limit)
                    ->offset($offset)
                    ->get();

                  // $post = array('result' => $prod4);

            }

        // array_push($product,$post);

        }

Please help to achieve the same.
Thanks,

A:

I guess this what you need:
Product::join('company', 'timeline_product.company_id', '=', 'company.company_id')
    ->select('company.name', 'company.logo', 'timeline_product.company_id', 'timeline_product.product_name', 'timeline_product.product_desc', 'timeline_product.product_price', 'timeline_product.reward_points', 'timeline_product.created_at', 'timeline_product.updated_at')
    ->when(request('product_price') <= 1000, function ($q) {
        $q->where('timeline_product.product_price', '<=', 1000);
    })
    ->when(request('product_price') > 1000 && request('product_price') <= 2000, function ($q) {
        $q->whereBetween('timeline_product.product_price', [1000, 2000]);
    })
    ->when(request('product_price') > 2000 && request('product_price') <= 3000, function ($q) {
        $q->whereBetween('timeline_product.product_price', [2000, 3000]);
    })
    ->when(request('product_price') > 3000 && request('product_price') <= 4000, function ($q) {
        $q->whereBetween('timeline_product.product_price', [3000, 4000]);
    })
    ->orderBy('timeline_product.updated_at', 'desc')
    ->limit($limit)
    ->offset($offset)
    ->get();


Q:

How to sign off a patch using git

I'm working on a project where some people will sent me git patches and I've to verify those patches and sign off the commits.
We are creating the patches using
git format-patch master --stdout > file.patch

And the file is mailed to us, then we've to verify the patch. For this we creates a new branch and then applies the patch to that using
git apply file.patch

Then verifies the contents of the commit, if it is correct then we need to add sign off to each commit from the patch.
I've seen the git -am command where we can add the signoff at the time of applying the patch.
Is it possible to add a commit after applying a patch?
Thank you

A:

Is it possible to add a commit after applying a patch?

Well, yes, you just make some changes and create a new commit.


Q:

Compare two arrays and update second array element in Javascript

I have two Arrays :
var allObjects = [
    {
        ani: "082817093649",
        customerID: "C20110324223733_971",
        invoiceDate: "2014-05-20",
        invoiceDebt: "0",
        totalAmount: "160434",
        totalUsage: "140849"
    },
    {
        ani: "082817093649",
        customerID: "C20110324223733_971",
        invoiceDate: "2014-05-20",
        invoiceDebt: "28631",
        totalAmount: "28631",
        totalUsage: "21028"
    },
    {
        ani: "082817054972",
        customerID: "C20111213222859_852",
        invoiceDate: "2012-11-20",
        invoiceDebt: "0",
        totalAmount: "60500",
        totalUsage: "14648"
    },
    {
        ani: "082817054972",
        customerID: "C20111213222859_852",
        invoiceDate: "2014-02-20",
        invoiceDebt: "0",
        totalAmount: "60500",
        totalUsage: "47986"
    },
];

var objRow = [
    {
        customerID  : "C20110324223733_971",
        2014-05-20  : [0, 0, 0] // totalAmount, totalUsage, invoiceDebt
    },
    {
        customerID  : "C20111213222859_852",
        2012-11-25  : [0, 0, 0] // totalAmount, totalUsage, invoiceDebt
    },
    {
        customerID  : "C20111213222859_852",
        2014-02-20  : [0, 0, 0] // totalAmount, totalUsage, invoiceDebt
    }
];

I want to update the data in objRow array with index that same in allObjects array, which condition is from 'customerID' value
If the objRow array has same index (date index), the value is Sum of data from allObjects array, and update to objRow array.
So the final result like this :
var objRow = [
    {
        customerID  : "C20110324223733_971",
        2014-05-20  : [189065, 161877, 28631] // totalAmount, totalUsage, invoiceDebt
    },
    {
        customerID  : "C20111213222859_852",
        2012-11-25  : [0, 0, 0] // totalAmount, totalUsage, invoiceDebt
    },
    {
        customerID  : "C20111213222859_852",
        2014-02-20  : [60500, 47986, 0] // totalAmount, totalUsage, invoiceDebt
    }
];

I already try to compare two arrays using loop, But it makes duplicate in date index. :(
Here is my code :
for (var b = 0; b < objRow.length; b++) {

    for (var a = 0; a < allObjects.length; a++) {

        if (objRow[b].customerID == allObjects[a].customerID) {

            objRow[b][allObjects[a].invoiceDate] = [allObjects[a].totalAmount,allObjects[a].totalUsage,allObjects[a].invoiceDebt];

        }

    }

}

Please help, thank you.

A:

First you have to populate temporary object map mapping customerID and invoiceDate to appropriate property values. Then you can use it to obtain the desired result:
var map = {};
for (var n = allObjects.length, i = 0; i < n; i++) {
    var el = allObjects[i], id = el.customerID, date = el.invoiceDate;
    if (!(id in map)) map[id] = {};
    if (!(date in map[id])) map[id][date] = [0, 0, 0];
    var arr = map[id][date];
    arr[0] += el.totalAmount;
    arr[1] += el.totalUsage;
    arr[2] += el.invoiceDebt;
}

n = objRow.length; i = 0;
for (; i < n; i++) {
    var el = objRow[i], id = el.customerID;
    for (var key in el) {
        if (key != 'customerID')
            el[key] = id in map && key in map[id]? map[id][key] : [0,0,0];
    }
}


Q:

Temperature reached in x minutes

I have a table with some temperature measurements and some timestamps. In this I will find out if there is a continuous period of 10 minutes where the temperature is 80 degrees or above.
First some testdata:
declare @TestTable Table
(
  Temperature int,
   TimeStamp DateTime2
)

insert into  @TestTable  values
(84, '2018-01-11 13:46:17.2933333'),
(82, '2018-01-11 13:46:47.2900000'),
(83, '2018-01-11 13:47:17.4300000'),
(44, '2018-01-11 13:47:47.4266667'),
(27, '2018-01-11 13:48:17.4300000'),
(21, '2018-01-11 13:48:47.4300000'),
(18, '2018-01-11 13:49:17.4300000'),
(17, '2018-01-11 13:49:47.4333333'),
(16, '2018-01-11 13:50:17.4433333'),
(16, '2018-01-11 13:50:47.4800000'),
(18, '2018-01-11 13:51:17.4833333'),
(19, '2018-01-11 13:51:47.5000000'),
(21, '2018-01-11 13:52:17.5333333'),
(24, '2018-01-11 13:52:47.5500000'),
(28, '2018-01-11 13:53:17.5500000'),
(30, '2018-01-11 13:53:47.5800000'),
(28, '2018-01-11 13:54:17.6200000'),
(31, '2018-01-11 13:54:47.6133333'),
(33, '2018-01-11 13:55:17.6133333'),
(34, '2018-01-11 13:55:47.6166667'),
(35, '2018-01-11 13:56:17.6333333'),
(35, '2018-01-11 13:56:47.6366667'),
(36, '2018-01-11 13:57:17.6500000'),
(37, '2018-01-11 13:57:47.6500000'),
(25, '2018-01-11 13:58:17.6533333'),
(16, '2018-01-11 13:58:47.6533333'),
(13, '2018-01-11 13:59:17.6566667'),
(12, '2018-01-11 13:59:47.6533333'),
(11, '2018-01-11 14:00:17.6533333'),
(11, '2018-01-11 14:00:47.6700000'),
(11, '2018-01-11 14:01:17.6833333'),
(11, '2018-01-11 14:01:47.6900000'),
(13, '2018-01-11 14:02:17.6900000'),
(14, '2018-01-11 14:02:47.7066667'),
(15, '2018-01-11 14:03:17.7066667'),
(16, '2018-01-11 14:03:47.7233333'),
(17, '2018-01-11 14:04:17.7233333'),
(18, '2018-01-11 14:04:47.7400000'),
(19, '2018-01-11 14:05:17.7566667'),
(20, '2018-01-11 14:05:47.7733333'),
(20, '2018-01-11 14:06:17.7733333'),
(20, '2018-01-11 14:06:47.8066667'),
(21, '2018-01-11 14:07:17.8066667'),
(22, '2018-01-11 14:07:47.8233333'),
(22, '2018-01-11 14:08:17.8233333')

I've tried CROSS APPLY and I've tried Exists:
CROSS APPLY
select T.TimeStamp, t.Temperature from  @TestTable T
CROSS APPLY
(
      select * from Temperatures T2
        where
          T.TimeStamp = T2.TimeStamp AND
          T2.Temperature >= 80 AND
          T2.TimeStamp >= T.TimeStamp
          AND T2.TimeStamp < dateadd(minute, 10, t.TimeStamp)
) A

Exists:
select T.TimeStamp, t.Temperature from  @TestTable T
where exists (select  1 from @TestTable T2
                    where T2.Temperature >= 80 AND
                    T2.TimeStamp >= T.TimeStamp and
                    T2.TimeStamp <= DATEADD(MINUTE, 10, T.TimeStamp)
                    )

Both gives me the wrong answer. Which is an empty table.

A:

this will gives you the sets of data where the continuous temperature is higher than 80
; with cte as
(
    select  rn = row_number() over (order by TimeStamp),
        *, flag = case when Temperature >= 80 then 1 else 0 end
    from    @TestTable
)
,
cte2 as
(
    select  *, grp  = rn - rank() over (partition by flag order by TimeStamp)
    from    cte
)
select  grp, min(TimeStamp), max(TimeStamp)
from    cte2
where   flag    = 1
group by grp


Q:

SSDT/SSRS - Report Previewer Won't Run

I'm having a very peculiar issue with SQL Server Data Tools 2012. Whenever I attempt to launch the report previewer, I get the following exception:

There was no endpoint listening at net.pipe://localhost/PreviewProcessingServce7324/ReportProcessing that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more deatils.

As far as I can tell, nothing I did triggered the issue. It just started happening one day when I fired up SSDT. I tried the suggestion on
Report Designer Preview in SSDT throws up a 'end point' not found error.
However, my service is up and running just fine (restarting it didn't help), and using Setspn didn't do anything for it, either.
Anyone have any ideas?

A:

That is a current bug in SSDT-BI. The current workaround for now is to right click on the report you want to preview in your Solution Explorer and click RUN.
You will also notice that if you try to preview the report for the first time a command prompt window opens up that runs the preview process, If you don't close this window and just minimize it then you can preview the report but I think the RUN method is much easier for now. Please mark as answer if this helped.

A:

This can happen when you have some SQL Services installed and running on your machine that interfere with the Report Preview. You can check your current services by going opening Sql Server Configuration Manager:

To fix this you can do the following:

Type WinKey + R,  input services.msc in the Run box, and press Enter.
Find the "Net.Pipe Listener Adapter" and either Restart or Disable it.

The workaround, as SQLnbe mentioned, is to:

Right Click the RDLC file from solution explorer
Click "Run" from there which will open up a new window.


Q:

Does "Nivdak" flour, grains, beans or pasta exist?

I know Bodek, among other brands sells pre-checked (for bugs, worms, etc.) produce. However, I have not seen any commercially available pre-checked rice, barley (etc. - pretty much any grain that is subject to having worms, bugs, moths, etc.) or flour and pasta. Does it exist? If so, where can I obtain it?
I am not particularly machmir on inspecting grains under an X-ray light, but I hate having moths flying around my cupboard or worms crawling in the rice a few weeks after I buy these things.

A:

FWIW, in Eretz Yisroel, there are vacuum packed bags of grains under Badatz supervision. They tend to be slightly more expensive but are "נקי מחשש תולעים". I saw some in stores near the Mir (in the Beit Yisrael neighborhood of Jerusalem), and would guess they're widely available in chareidi neighborhoods.
If your concern is to prevent bugs being born in bought bags, store them in the freezer for at least two days. The colder temperature will kill any bugs or eggs. Personally, i store my flour long-term in the freezer.
Barley can be easily checked and cleaned. Put it in a bowl, fill it with water, and give it a swish. Within a few seconds, bugs, eggs, and other debris (if any) will float to the top. This is hardly an extra step, as bagged barley really needs to washed anyway before use, as it is usually filthy with dirt, little stones, and other things i'd rather not think of.


Q:

Check interrupted status from within wait()

When a thread t calls the wait() method on an object u, it goes to the WAITING state until another thread calls notify() on the same object u OR another thread calls the interrupt() method on the waiting thread t. Taking into account that a waiting thread does not consume CPU cycles, how is it possible for the waiting thread to check the interrupted status within wait() and throw an InterruptedException?
That is, I imagine the following code within wait():
if (Thread.interrupted())  // Clears interrupted status!
  throw new InterruptedException();

A:

A thread in the status WAITING must be resumed to become RUNNABLE again.
This resumption is being done at a lower level and is invoked by both, a notification or an interrupt.
A waiting thread does not execute any code. Instead the interrupt flag is set (at a lower level), the thread is resumed - state RUNNABLE - and once it is RUNNING again, the interrupt status is checked.


Q:

AWS Lambda: Execute function B 10 minutes after function A

Im developing a serverless backend for a time sensitive application.
Is it possible to execute Lambda function B XX minutes after Lambda function A?
Im looking for a clean serverless solution. Using setTimeout or a similar approach is too much of a hack to be accepted.
Example: Send a notification using SNS 10 minutes after a Lambda function has executed.

A:

The easiest way is to use SQS with a delayed delivery.

Lambda-A adds a message to an SQS queue and sets the delivery delay of 10 minutes. You can set any delay between 0 and 15 minutes. You can also use SQS Delay Queues to delay all messages added to the queue.
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-delay-queues.html
After 10 minutes SQS message becomes visible and SQS triggers Lambda-B.
Lambda-B receives Amazon SQS Event and deletes message from the queue using receipt handle. Here is an example from https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-sqs:

.
 "Records": [
    {
        "messageId": "c80e8021-a70a-42c7-a470-796e1186f753",
        "receiptHandle": "AQEBJQ+/u6NsnT5t8Q/VbVxgdUl4TMKZ5FqhksRdIQvLBhwNvADoBxYSOVeCBXdnS9P+erlTtwEALHsnBXynkfPLH3BOUqmgzP25U8kl8eHzq6RAlzrSOfTO8ox9dcp6GLmW33YjO3zkq5VRYyQlJgLCiAZUpY2D4UQcE5D1Vm8RoKfbE+xtVaOctYeINjaQJ1u3mWx9T7tork3uAlOe1uyFjCWU5aPX/1OHhWCGi2EPPZj6vchNqDOJC/Y2k1gkivqCjz1CZl6FlZ7UVPOx3AMoszPuOYZ+Nuqpx2uCE2MHTtMHD8PVjlsWirt56oUr6JPp9aRGo6bitPIOmi4dX0FmuMKD6u/JnuZCp+AXtJVTmSHS8IXt/twsKU7A+fiMK01NtD5msNgVPoe9JbFtlGwvTQ==",
        "body": "{\"foo\":\"bar\"}",
        "attributes": {
            "ApproximateReceiveCount": "3",
            "SentTimestamp": "1529104986221",
            "SenderId": "594035263019",
            "ApproximateFirstReceiveTimestamp": "1529104986230"
        },
        "messageAttributes": {},
        "md5OfBody": "9bb58f26192e4ba00f01e2e7b136bbd8",
        "eventSource": "aws:sqs",
        "eventSourceARN": "arn:aws:sqs:us-west-2:594035263019:NOTFIFOQUEUE",
        "awsRegion": "us-west-2"
    }
]


Q:

android Gcm registrationID conflicts with 3rd party library like Parse

I have a simple project that use my gcm provider and also I want to implement parse library to send push for all user. But I have an issue about that situation. When I register the gcm with my GCMSenderID, I get the registrationID and then Parse register the gcm with its default GCMSenderID(1076345567071). Then I realized that the regID that get from my gcm provider has written the parse push table as deviceToken. For this reason I think, I cannot send push message to all devices with parse.
I use parse quickstart implementation also make some research from parse.com/docs/push_guide#top/Android.
How can I resolve this conflict?
Here is my implementation:
AndroidManifest.xml

    <service android:name="com.parse.PushService" />

    <meta-data
        android:name="com.parse.push.notification_icon"
        android:resource="@drawable/icon" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <receiver
        android:name=".gcm.GcmBroadcastReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="xxx.android" />
        </intent-filter>
    </receiver>

    <receiver android:name="com.parse.ParseBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
    </receiver>
    <receiver
        android:name="com.parse.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="xxxx.android" />
        </intent-filter>
    </receiver>
    <receiver
        android:name=".gcm.ParseReceiver"
        android:exported="false">
        <intent-filter>
            <action android:name="com.parse.push.intent.RECEIVE" />
            <action android:name="com.parse.push.intent.DELETE" />
            <action android:name="com.parse.push.intent.OPEN" />
        </intent-filter>
    </receiver>

Application.java
    Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE);
    Parse.initialize(this, ParseAPPLICATION_ID, ParseCLIENT_KEY);
    ParseInstallation.getCurrentInstallation().saveInBackground();

Parse uses its default sender id to request a GCM registration token: In particular, the SDK will automatically register your app for push at startup time using Parse's sender ID (1076345567071) and will store the resulting registration ID in the deviceToken field of the app's current ParseInstallation. (from parse.com/docs/push_guide#top/Android). So at startup 2 registrations for GCM tokens are requested, and my question is: how can I be sure which regToken Parse receives vs which regToken my GCM implementation/client receives? In theory they could get mixed up?

A:

I fixed this issue with registering multiple senders by calling :
GoogleCloudMessaging.getInstance(this).register(YOUR_GCMSENDERID,  PARSE_DEFAULT_GCM_SENDERID);

PARSE_DEFAULT_GCM_SENDERID = 1076345567071


Q:

By default make links target blank

Possible Duplicate:
make links posted by users open in a new window

It always annoys me when I go to click a link on a Stack Exchange site within a question, comment, or answer and it targets the current tab, making it so I have to go back to return to the question I was on after going to another question or going to an external webpage.
All anchor tags should use target="_blank" by default. I'm sure it's quite possible, Gmail does it. I have just gotten in the habit of doing Ctrl + click so that it will open in a new tab.
I think this would be a good feature, because most of the time we don't want to leave the question we are on. We want to stay there, so we can answer the question. We just need to see the link in order to help answer the question.
It has just always been a pain trying to get back to questions we were on, so I propose that by default links in questions, comments, and answers open new tabs.

A:

Jeff Atwood, Stack Exchange CTO, retweeted this tweet a few days ago, which links to
.
Why is target="_blank" a bad practice? Because for every one person it pleases, it annoys ten others. Most people don't like their desktop cluttered with new windows (I suppose it's marginally better if your browser settings are set to open things in new tabs) because every website has decided to make leaving the website open in a new window. They're going somewhere; let them go and don't force them to come back.
Jakob Nielsen, the respected UI guru, has made this point clear.

A:

Personally, I hate when sites start launching windows all over the place without my consent. If I wanted a new window or tab, I would've opened one.
Use the tools available to you: as you mentioned, you can open links in a new window by using the middle mouse button or, holding Ctrl while clicking (Windows, Linux?), or by holding Command while clicking (Mac OS X). What's wrong with that? You want links to behave differently than normal, so you in turn have to do something slightly different. It's one extra key press.
The upside is that this works for virtually any link on any website, so you don't have to rely on sites adding target="_blank" to all their external links.

A:

If you have a mouse with a middle button or a clickable scrollwheel, just use that instead to open links in a new tab. No need for an extra key press.
As others already said, target="_blank" is bad for UX. It changes the default browser behaviour.


Q:

Angular factory returning only part of resource response

I have an Angular factory DogePrice:
.factory('DogePrice', ['$resource', function ($resource) {
    return $resource("https://chain.so/api/v2/get_info/DOGE");
}])

The typical api response is like this:
{
  "status" : "success",
  "data" : {
    "name" : "Dogecoin",
    "acronym" : "DOGE",
    "network" : "DOGE",
    "symbol_htmlcode" : "Ð",
    "url" : "http://www.dogecoin.com/",
    "mining_difficulty" : "18661.80200222",
    "unconfirmed_txs" : 7,
    "blocks" : 1119625,
    "price" : "0.00000046",
    "price_base" : "BTC",
    "price_update_time" : 1453938374,
    "hashrate" : "1289658619826"
  }
}

Here is the JSfiddle example
How can I create a factory that only returns the data.price field? I'd like to have a clean controller with only $scope.price = DogePrice.get(); or something similar.

A:

Do use promise return by $resource object. In that case you should use promise pattern to get data from the factory.
Factory
.factory('DogePrice', ['$resource', function ($resource) {
   var myResource = $resource("https://chain.so/api/v2/get_info/DOGE")
   var getData = function(){
      return myResource.get().$promise.then(function(response){
          //here you have control over response
          //you could return whatever you want from here
          //also you could manipulate response OR validate data
          return response.data;
      });
   }
   return {
     getData: getData
   }
}])

Controller
DogePrice.getData().then(function(data){
   $scope.price = data;
});