text:
Q: Obtain a eigenvector for a matrix Recall that a matrix $A$ is diagonalizable if there is a diagonal matrix $D$ and an invertible matrix $P$ such that
\begin{equation*}
    A = PDP^{-1}.
\end{equation*}

Next we study the possibility of diagonalizing the matrix
\begin{equation*}
     A =
     \begin{pmatrix}
         2&1&1\\
         1&2&1\\
         -2&-2&-1
     \end{pmatrix}. \end{equation*}

We look for the proper values of the matrix $A$, for this we take the roots of the characteristic polynomial given by the expression $\text{det}(A-\lambda I)$, that is
\begin{equation*}
    \text{det}\begin{pmatrix}
        2-\lambda&1&1\\
        1&2-\lambda&1\\
        -2&-2&-1-\lambda
    \end{pmatrix}
    =
    -\lambda^{3} + 3\lambda^{2} - 3\lambda + 1 = -(\lambda - 1)^{3},
\end{equation*}
therefore the only eigenvalue of $A$ is $\lambda = 1$ with algebraic multiplicity $3$.
To find the eigenvectors, it is enough to obtain a base for $\text{Ker}(A-\lambda I)$, this is obtained by solving the homogeneous system $ (A-\lambda I) x = 0 $, in this case we have to
\begin{equation*}
    \left(\begin{array}{ccc|c}
        2-1&1&1&0\\
        1&2-1&1&0\\
        -2&-2&-1-1&0
    \end{array}\right)
    =
    \left(\begin{array}{ccc|c}
        1&1&1&0\\
        1&1&1&0\\
        -2&-2&-2&0
    \end{array}\right),
\end{equation*}
staggering
\begin{equation*}
    \left(\begin{array}{ccc|c}
        1&1&1&0\\
        1&1&1&0\\
        -2&-2&-2&0
    \end{array}\right)
    \to
    \left(\begin{array}{ccc|c}
        1&1&1&0\\
        0&0&0&0\\
        0&0&0&0
    \end{array}\right),
\end{equation*}
thus
\begin{equation*}
    \text{Ker}(A-I) =
    \left\langle\left\{
        \begin{pmatrix}
            -1\\1\\0
        \end{pmatrix};
        \begin{pmatrix}
            -1\\0\\1
        \end{pmatrix}
    \right\}\right\rangle,
\end{equation*}
therefore the geometric multiplicity of $\lambda = 1$ is $2$. Then two eigenvectors are
\begin{equation*}
    v_{1} =
    \begin{pmatrix}
        -1\\1\\0
    \end{pmatrix};\quad
    v_{2}
    \begin{pmatrix}
        -1\\0\\1
    \end{pmatrix}.
\end{equation*}
It is clearly non-diagonalizable, but can we find a third generalized eigenvector? Let's try to factor using Jordan matrix
First idea:
To recap, we have a single eigenvalue of algebraic multiplicity $3$ and geometric multiplicity $2$, the latter means that the eigenvalue associated with $\lambda$ is of dimension $2$, which generates a conflict, since we require $3$ eigenvectors li to get an invertible $P$ array, this means you can't write
\begin{equation*}
    A = PDP^{-1},
\end{equation*}
where $ D $ is a diagonal matrix made up of the eigenvalues of $ A $ and $ P $ is an invertible matrix made up of eigenvectors.
Due to the above, a Jordan decomposition is sought, the Jordan matrix in this case is of the form
\begin{equation*}
    J =
    \begin{pmatrix}
        1&0&0\\
        0&1&1\\
        0&0&1
    \end{pmatrix},
\end{equation*}
then to complete the matrix $P$ (since we need $3$ vectors) we study $AP = PJ $, this is to find a vector $(a, b, c)^{t}$ such that
\begin{equation*}
    \begin{pmatrix}
        2&1&1\\
        1&2&1\\
        -2&-2&-1
    \end{pmatrix}
    \begin{pmatrix}
        -1&-1&a\\
        1&0&b\\
        0&1&c
    \end{pmatrix}
    =
    \begin{pmatrix}
        -1&-1&a\\
        1&0&b\\
        0&1&c
    \end{pmatrix}
    \begin{pmatrix}
        1&0&0\\
        0&1&1\\
        0&0&1
    \end{pmatrix},
\end{equation*}
However, it is not necessary to carry out all the products of the matrix product, since it will be enough to study the equality of matrices in the third column (since it will not verify), this equality of column vectors is
\begin{equation*}
    \begin{pmatrix}
        2a+b+c\\
        a+2b-c\\
        -2a-2b-c
    \end{pmatrix}
    =
    \begin{pmatrix}
        -1+a\\
        b\\
        1+c
    \end{pmatrix},
\end{equation*}
so it is enough to solve the system of equations
\begin{equation*}
    \left(\begin{array}{ccc|c}
        1&1&1&-1\\
        1&1&-1&0\\
        -2&-2&-2&1
    \end{array}\right),
\end{equation*}
but as it turns out that there is no solution for this system, then there is no vector $ v_{3} = (a, b, c)^{t}$ such that $P = (v_{1} | v_{2} | v_{3})$ and check $A = PJP^{-1}$.
Second idea:
To complete the matrix $P$ we look for a generalized eigenvector, this is a vector $v$ such that for some $k\in\mathbb{N}$ it is found in the space $\text{Ker}((A-I)^{k})$).
For example, for $k = 2$, we study the system of equations
\begin{equation*}
    \left(\begin{array}{ccc|c}
        1&1&1&0\\
        1&1&1&0\\
        -2&-2&-2&0
    \end{array}\right)^{2}
    =
    \left(\begin{array}{ccc|c}
        0&0&1&0\\
        0&0&1&0\\
        -2&-2&-3&0
    \end{array}\right)
    \to
    \left(\begin{array}{ccc|c}
        1&1&0&0\\
        0&0&1&0\\
        0&0&0&0
    \end{array}\right),
\end{equation*}
later
\begin{equation*}
    \text{Ker}((A-I)^{2}) =
    \left\langle\left\{
        \begin{pmatrix}
            1\\-1\\0
        \end{pmatrix}
    \right\}\right\rangle,
\end{equation*}
but let's note that $\text{Ker}((A-I)^{2})\subseteq\text{Ker}(A-I)$, so we see what happens with $k = 4$, this is the system
\begin{equation*}
    \left(\begin{array}{ccc|c}
        1&1&1&0\\
        1&1&1&0\\
        -2&-2&-2&0
    \end{array}\right)^{4}
    =
    \left(\begin{array}{ccc|c}
        -2&-2&-3&0\\
        -2&-2&-3&0\\
        6&6&5&0
    \end{array}\right)
    \to
    \left(\begin{array}{ccc|c}
        6&6&5&0\\
        0&0&-4/3&0\\
        0&0&0&0
    \end{array}\right)
    \to
    \left(\begin{array}{ccc|c}
        1&1&0&0\\
        0&0&1&0\\
        0&0&0&0
    \end{array}\right),
\end{equation*}
later
\begin{equation*}
    \text{Ker}((A-I)^{4}) =
    \left\langle\left\{
        \begin{pmatrix}
            1\\-1\\0
        \end{pmatrix}
    \right\}\right\rangle,
\end{equation*}
Due to the above, I don't know how to get the third (generalized) eigenvector. How can I get it?


text:
Q: Header tag error in asp.net? In my application I am getting this error:

You can only have one <head runat="server"> control on a page.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: You can only have one  control on a page.

What could be the problem?

A: Assuming you are  having problem with <head runat="server"> tag, and you are using master pages...
if you are using master pages, do not use <head runat="server"> inside child page... you can add necessary header tags in

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
  </asp:Content>

if you do not have any master page, then make sure whether <head runat="server"> tag is not repeating.

A: Do you have more than one <form runat="server"> tags on your page? You can only have one of these.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 Input Directive is not clearing its view value on form reset I have the following directive:
declare  var $:any;

export const CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => SharedAppDatePickerDirective),
  multi: true
};

@Directive({
  selector: '[date-picker]',
  host: {'(blur)': 'onTouched($event)'},
  providers: [CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR]
})
export class SharedAppDatePickerDirective implements     ControlValueAccessor, OnInit {

  constructor(private el: ElementRef) { }

  private innerValue: string;

  public onChange: any = (_) => { /*Empty*/ }
  public onTouched: any = () => { /*Empty*/ }

  ngOnInit() {

    $(this.el.nativeElement).datepicker().on('change', e => this.onChange(e.target.value)).on('change', e => e.target.focus());
  }

  get value(): any {
    return this.innerValue;
  };

  //set accessor including call the onchange callback
  set value(v: any) {
    if (v !== this.innerValue) {
      this.innerValue = v;
      this.onChange(v);
    }
  }

  writeValue(val: string) : void {
    this.innerValue = val;
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  ngOnDestroy() {
    $(this.el.nativeElement).datepicker('destroy');
  }
}

When a form.reset() occurs, form controls where I have this directive applied to, are not clearing its view value. After form.reset() it becomes untouched, pristine, invalid, but it keeps the value I've typed before.
Any ideas on how to deal with?

A: Fixed that by doing:
writeValue(val: string) : void {
    this.innerValue = val;
    this.el.nativeElement.value = val;
}


text:
Q: Correct usage of long primitive datatype and its array I have been coding a question which asks me to code a modified version of fibonacci. Now although, the code is ready to go, its not working properly, because an int is being returned instead of a long
When the following is used as an input: 0 1 10
the output is -9223372036854775807
intstead of this 84266613096281243382112
Here's the code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static long arr[];

    public static long func(int n,long t1, long t2){
    arr = new long[n+1];
    arr[1]=t1;
    arr[2]=t2;
    return func(arr,n);

    }
    public static long func(long[] arr, int n){
        if(n==0||n==1||n==2){
            return arr[n];
        }
        if(arr[n]!=0){
            return arr[n];
        }
        arr[n]=(long)(Math.pow(func(arr,n-1),2)+func(arr,n-2));
        return arr[n];
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        long t1= s.nextLong();
        long t2=s.nextLong();
        int n=s.nextInt();
        System.out.print(func(n,t1,t2));
    }
}

I am not asking for help with the logic, or solving the question. I want to know where am I going wrong that even though I am using a long array the answer being returned is still an int
Also, any help on how to handle a long array, will be great.

A: Answer returned is not integer because integer has maximum value of 2147483647 and if value is greater than integer value number between [-2147483647, 2147483647] is returned. I think there is some problem in logic.

A: For all those wondering, I realized yesterday that the range of long was exhausted and hence, couldnot be used to solve the question. I have used the BigInteger class, and it works.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static BigInteger func(int n,BigInteger t1, BigInteger t2){
    BigInteger arr[] = new BigInteger[n+1];
    arr[1]=t1;
    arr[2]=t2;
    return func(arr,n);

    }
    public static BigInteger func(BigInteger[] arr, int n){
        if(n==0||n==1||n==2){
            return arr[n];
        }
        if(arr[n]!=null){
            return arr[n];
        }
        arr[n]=(func(arr,n-1).pow(2)).add(func(arr,n-2));
        return arr[n];
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        BigInteger t1= s.nextBigInteger();
        BigInteger t2= s.nextBigInteger();
        int n=s.nextInt();
        System.out.print(func(n,t1,t2));
    }
}

A: You can use this code instead, because they didn't ask for the entire array but only the nth term.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String args[] ) throws Exception {
        Scanner in=new Scanner(System.in);
        BigInteger t1=in.nextBigInteger();
        BigInteger t2=in.nextBigInteger();
        int n=in.nextInt();
        for(int i=0;i<n-2;i++)
        {
            BigInteger temp;
            temp = (t2.pow(2)).add(t1);
            t1=t2;
            t2=temp;
        }
        System.out.println(t2);
    }
}


text:
Q: Android Navigate Component navigate to sub graph I hava two Fragment(OverviewFragment、PersonalFragment), and one sub graph(contains two Fragment :BucketsFragment and ObjectsFragment, BucketsFragment is start destination). They are bind to one BottomNavigateView.
Now, After navigate to the sub graph start destination(BucketsFragment), and continue to navigate to ObjectsFragment. Then navigate to OverviewFragment and finally return to the sub graph.
Now, I came to start destination(BucketsFragment), but actually what I want is ObjectsFragment. what should I do?
The whole process is shown here
I want to navigate to the sub graph that retains the previous state, instead of a new sub graph.

A: As per the material design guidelines for bottom navigation:

On Android: the app navigates to a destination's top-level screen. Any prior user interactions and temporary screen states are reset, such as scroll position, tab selection, and in-line search.

So technically, this behavior is expected.
When you're on the Resources tab and go to the ObjectsFragment, the back stack is
DashBoardFragment -> BucketsFragment -> ObjectsFragment

When you go back to the Overview tab, the back stack becomes
DashBoardFragment

And no state is saved for Fragments that aren't on the back stack. That's why when you reselect the Resources tab, it is recrated from scratch and you get back to
DashBoardFragment -> BucketsFragment

There's an existing issue for supporting multiple back stacks which aims to bring support for saving the state of each tab separately, allowing the behavior you wish. As per that issue, this requires significant changes to how Fragments work (since they are the one saving the state of Fragments) as well as integration into Navigation itself.
That issue points out a temporary workaround, demonstrated in the NavigationAdvancedSample where each tab uses its own separate navigation graph and separate NavHostFragment, thus allowing each one to keep its own state independently from one another. This requires a bit different of a setup in the MainActivity and the help of a set of NavigationExtensions to get that working.
It is expected that all of that functionality, once the multiple back stacks work is done, to be folded into the Navigation library itself.


text:
Q: Ramp of lanes <= 1 exception when cross-compile Halide for RISC-V Tried this tutorial https://halide-lang.org/tutorials/tutorial_lesson_11_cross_compilation.html on x86 host machine (Ubuntu 20.04) but for RISC-V target architecture. Unfortunately, there is an exception from IR.cpp. The exception appears only when .vectorize(x, 16) is applied, so problem is somewhere in RISC-V Vectorization support. Any ideas how to debug this?
Internal Error at /home/dkurt/Halide/src/IR.cpp:272 triggered by user code at : Condition failed: lanes > 1: Ramp of lanes <= 1

Everything is OK locally for x86 target.

*

*Halide @ https://github.com/halide/Halide/commit/16243da75944ce9ea8d4e8eb90d6f104f06284ec

*LLVM 15.0.2

#include "Halide.h"

using namespace Halide;

int main(int argc, char** argv) {
    Func brighter;
    Var x, y;

    Param<uint8_t> offset;
    ImageParam input(type_of<uint8_t>(), 2);
    std::vector<Argument> args(2);
    args[0] = input;
    args[1] = offset;

    brighter(x, y) = input(x, y) + offset;

    brighter.bound(x, 0, 64).bound(y, 0, 64);

    brighter.vectorize(x, 16).parallel(y);

    Target target;
    target.os = Target::Linux;
    target.arch = Target::RISCV;
    target.bits = 64;

    std::vector<Target::Feature> features;
    features.push_back(Target::RVV);
    target.set_features(features);

    try {
        brighter.compile_to_static_library("compiled", args, "brighter", target);
    } catch(Halide::InternalError& ex) {
        std::cout << ex.what() << std::endl;
    }
}

A: Solved by switching to a custom branch. See https://github.com/halide/Halide/issues/7070.


text:
Q: UISegmentedControl: Programmatically Set Index? I'm trying to load a user setting into a segmented control. The NSUserDefault reads correctly, and the preference is correctly translated into an index. However, the segmented control does not seem to respond to setting the index, preferring to stay at index 0.
The code clean compiles with -Wall -Wextra, and clang does not report any issues. I've also run with both Leaks and Zombies - OK. And the ASSERTs below do not fire.
The UISegmentedControl were created using Interface Builder (there are 4 total on the view). I've verified the connections. I've tried calling -loadPreferences in -viewDidLoad, -viewWillAppear, and -viewDidAppear.
Are there any tricks I'm missing? Should I be calling a needsUpdate or some other method to get the controls to repaint?
Jeff
-(void)loadPreferences
{
   NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
   ...

    int days = [userDefaults integerForKey:kDirtyAfter];
    ASSERT(IsValidDirtyDays((DirtyDays)days));
    if(!IsValidDirtyDays((DirtyDays)days))
        days = (int)DirtyDaysDefault;

    int idx;
    switch(days)
    {
        case DirtyDays1: idx = 0; break;
        case DirtyDays3: idx = 1; break;
        case DirtyDays7: idx = 2; break;
        case DirtyDays14: idx = 3; break;
        case DirtyDays28: idx = 4; break;
        default: idx = 1;
    }

    // dirtyAfterSegment.selectedSegmentIndex = idx;
    [dirtyAfterSegment setSelectedSegmentIndex:idx];
    ASSERT(dirtyAfterSegment.selectedSegmentIndex == idx);
}

A: If the Assert does not fire, then something must be changing the index to 0 after this code, or the code itself is always using the first case statement.
Create an action on valueChanged for the segment, and set a breakpoint in that action to see when the segment is being changed and who is changing it.

A: You said you created the segmented controls in interface builder, did you create IBOutlets for them and connect them as well?


text:
Q: How multi purpose search works with Searchkick? I'm looking to understand how a multi purpose search works,
for exemple i'm looking to search cell phone and the left menu return electronics related categories
and if i decide in the same search find shoes and the left menu return clothes related categories
like the amazon or Walmart, someone know how this shift of sections works in the same search?

A: It sounds like you want your UI to react to choices users make, one choice leading to another choice.
A common solution to this is to write some JSON endpoints in your application in Ruby, PHP, or whatever you're using while leveraging jQuery's AJAX functionality.
You would write some JavaScript with the jQuery library included to watch for what the user does and call the backend for what the UI should do next.
Note that you can accomplish this in plain old JavaScript, but people tend to use jQuery for smaller one-offs.  Or, you could decouple your backend from the frontend completely by turning the server side code into a JSON API and use a frontend framework like React or Angular2 to consume the backend.
It sounds like your best bet is to give jQuery's AJAX stuff a try though.
http://api.jquery.com/jquery.ajax/
If you're using Ruby:  http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html
Edit to add more info
Before I answer that, let me note that jQuery is a library for JavaScript written in JavaScript.  It just makes JavaScript nicer to deal with, especially when you're wanting to do some API calls like this.
JavaScript can watch and react to anything a user does in your app.  If you want to say hi when they click a button, then you would do something like this
<button id="the-button">Say Hi</button>

<script>
$( "#the-button" ).click(function() {
  alert( "Hi!" );
});
</script>

AJAX can be used just like this "on click" functionality.
If you want to react to something the user typed into a search field, you might use the .change method to fire off the AJAX call the same way the .click method says alert(hi):  https://api.jquery.com/change/


text:
Q: Why POST method return 500 error for array of values with successfully inserted value? In loopback 4 There is a strange issue when I POST a single value like :
{
email: "sit@leoVivamusnibh.net",
password: "430975896"
}

in swagger, there is no issue report but when I post an array of values like:
[{
email: "metus.facilisis.lorem@sitamet.org",
password: "168978823"
},
{
email: "fringilla@enim.org",
password: "933013104"
}]

the value was posted to the database but this error appears:
{
  "error": {
    "statusCode": 500,
    "message": "Internal Server Error"
  }
}

and in console shows the following lines:

Unhandled error in POST /users: 500 TypeError: model.toObject is not a
  function
      at UserRepository.toEntity (D:\apps\test\node_modules@loopback\repository\src\repositories\legacy-juggler-bridge.ts:471:39)
      at UserRepository.create (D:\apps\test\node_modules@loopback\repository\src\repositories\legacy-juggler-bridge.ts:338:17)

user model
@model({ settings: {} })
export class User extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true
  })
  id: number;

  @property({
    type: 'string'
  })
  email: string;

  @property({
    type: 'string'
  })
  password: string;
  constructor(data?: Partial<User>) {
    super(data);
  }
}

user controller:
async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(User),
        },
      },
    })
    user: Omit<User, 'id'>,
  ): Promise<User> {
    return this.userRepository.create(user,
                                    //{ exclude: ['id'] }
                                      );
  }

A: First of all, in LoopBack 4, the POST method does not accept an array of model instances to create, it works for a single model only.
Having said that, LoopBack should not respond with a 500 error when the request contains an array of objects. I would expect a 422 Unprocessable Entity response instead.
Can you fill a bug please? https://github.com/strongloop/loopback-next/issues/new/choose

A: The array you are requesting in the request body is fine as you mentioned.
The thing is if you want to create these users profile in the database
You will have to do something like:
async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(User),
        },
      },
    })
    userList: User[],
  ): Promise<User> {
      return await Promise.all(
        userList.forEach(user => {
          return await this.userRepository.create(user);
       ))
  }

Hopefully, this helps, write to me if you have any query or suggestion.
Thank you


text:
Q: posting formdata with ajax has csrf error in django I'm new to ajax and django and I'm trying to send a file in a form using formdata and ajax but I'm getting csrf token missing error and I've searched alot but can't solve this problem.Should I use cookies?if so,how?.I really need help.My codes are here:
urls.py
...
url(r'^administration/library/add_ebook/ajax/$',upload_ebook_ajax, name='upload_ebook_ajax'),

...
forms.py
class EbookForm(forms.ModelForm):
    class Meta:
        model = Ebook
        fields = ('ebook_title', 'ebook_publisher','ebook_publication_date','ebook_Type','ebook_keywords','ebook_preview','ebook_url','ebook_categories', )

views.py
@transaction.atomic()
def upload_ebook_ajax(request):

if request.method == 'POST':
    form = EbookForm(request.POST, request.FILES)
    if form.is_valid():

        form.save()
        data['form_is_valid'] = True

    else:
        data['form_is_valid'] = False
else:
    form = EbookForm()

context = {'form': form}
data['html_form'] = render_to_string('upldebook.html',context,request=request)
return JsonResponse(data)

upldebook.html
{% load crispy_forms_tags %}
{% crispy form %}

add_ebook.html

                <form method="post" enctype="multipart/form-data" action="{% url 'upload_ebook_ajax' %}" class="js-upload-ebook-form">
                    {% csrf_token %}

                    <button type="submit">Upload</button>
                    </form>

uploadebook.js
//for showing form
 $.ajax({
      url: '/administration/library/add_ebook/ajax',
      type: 'get',
      dataType: 'json',
      success: function (data) {
        $(".frmclass").html(data.html_form);
      }
    });
//for form submit
    $(".js-upload-ebook-form").submit( function (e) {
    e.preventDefault();
    var frmdt = new FormData($('form').get(0)); //I don't know what is 'form' :|
    frmdt.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: frmdt,
    cache: false,
    processData: false,
    contentType: false,
    dataType: 'json',
    success: function(data) {
        alert("SUCCESS1");
        window.location = "/"
    }

    });
    return false;
    });

A: One solution I use is to add @csrf_exempt to your ajax methods (it might decrease security):
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def upload_ebook_ajax(request):
    # your code

A: {% csrf_token %} puts a hidden html input inside your form, so if you just the form with original inputs, it should work.
data: $(this).serialize();

A: Serialize the data field, the token will be posted along with it
data: frmdt.serialize(),

Read this SO post page for more, your answer could be there

A: I just needed this:
data:  new FormData(this)

and now it works.
Thanks to this link:
http://phppot.com/php/php-ajax-image-upload/


text:
Q: Use LAN with Cloud I have a scenario in my new office that I have only client PC's which i have to setup a server to manage these PC's. So of the high cost of server, can i use any of the cloud computing services to do so, so that all my PC's will b managed by the cloud service(i think it is active directory). Please help me in how can i do this?
I thought of having an internal server that will manage the client PC's. But the cost of server is a big problem. Also we will need to expand the server config when requirement increases.

A: Taking a brief look, Microsoft offers Azure Active Directory(http://azure.microsoft.com/en-us/services/active-directory/), which has a free trial. If the server is cost prohibitive, I would consider looking into the long term cost of the cloud service to see if it really outweighs the purchase of on-campus equipment. The problem with cloud services is that you are now dependent on your internet connection for people to log into their systems and interact with the directory. What happens if the connection goes down?
Another option, depending on the size of the business and it's needs, are to purchase a couple of lower end server options and host active directory and other services in appropriate VMs. This will be a bigger up front cost but MAY be a more robust solution depending on your needs.
Furthermore, security is always a consideration when using cloud services - make sure you read up on the docs and have a good idea of how to keep thing secure (you'll be passing user credentials back and forth to AD).

A: I'm not so sure this belongs here but I'll try and answer.
Going to the cloud only saves you the capex costs of doing something or getting something going quickly.  You still will have to account for the OpEx costs of having stuff in the cloud.  The monthly, VM cost, networking traffic.  You get free into cloud but every outbound traffic is going cost you something.  Read that all the traffic pushed to your clients in your office will keep th
I have a local recycler (Seattle) here that sells HP DL180 (Dual Quad Core Rack mounted servers for 69$ that use SAS or SATA drives Raid controller and 4GB of ram) for 69$.
I have work on a few startups where OpEx over ran the Cap in less than 7 months.


text:
Q: Original exception text was: 'int' object has no attribute 'name'. in django rest framework I am trying to call a get api but it gives me this error everytime.
The error:
AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the int instance.
Original exception text was: 'int' object has no attribute 'name'.
My models:
class Destination(models.Model):
    Continent_Name = (
        ('Europe', 'Europe',),
        ('Asia', 'Asia',),
        ('North America', 'North America',),
        ('South America', 'South America',),
        ('Africa', 'Africa',),
        ('Oceania', 'Oceania',),
        ('Polar', 'Polar',),
        ('Regions', 'Regions',),
    )
    name = models.CharField(max_length=255, unique=True)
    continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe')
    top = models.BooleanField(default=False)
    dest_image = models.ImageField(blank=True)

    def __str__(self):
        return self.name

class Package(models.Model):
    TOUR_TYPE = (
        ('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',),
        ('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',),
        ('Group Tour', 'Group Tour',),
        ('Cruise Tour', 'Cruise Tour',),
    )

    operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
    package_name = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    featured = models.BooleanField(default=False)
    price = models.IntegerField(verbose_name="Price in Nrs")
    price_2 = models.IntegerField(verbose_name="Price in $")
    duration = models.IntegerField(default=5)
    duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour")
    discount = models.IntegerField(verbose_name="Discount %", default=15)
    #discounted_price = models.IntegerField(default=230)
    #savings = models.IntegerField(default=230)
    tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour')
    new_activity = models.ManyToManyField(NewActivity)
    accommodation = models.CharField(max_length=255, default='Guest House & Hotel')
    transport = models.CharField(max_length=150, default='Flight')
    age_range = models.CharField(max_length=100, default='6 to 79 years old')
    fix_departure = models.BooleanField(default=False)
    rating = models.IntegerField(choices=((1, 1),
                                          (2, 2),
                                          (3, 3),
                                          (4, 4),
                                          (5, 5))
                                 )

    image = models.ImageField(blank=True, verbose_name="Thumbnail Image-Vertical")

    content =RichTextField()
    highlights = RichTextField()
    inclusions = RichTextField()
    exclusions = RichTextField()
    # itinerary = models.ManyToManyField(Itinerary)
    itinerary_text = RichTextField()
    faqs = RichTextField(blank=True)
    image_1= models.ImageField(blank=True,null = True,verbose_name="Image-Horizontal")
    image_2= models.ImageField(blank=True,null = True,verbose_name="Image-Square")
    image_3= models.ImageField(blank=True,null = True,verbose_name="Image-Sqaure")
    date_created = models.DateField()

    def __str__(self):
        return self.package_name

My views:
class PackageSearchAPi(ListAPIView):
    queryset = Package.objects.all().order_by('package_name')
    serializer_class = PackageSerializer

    def get(self, request, *args, **kwargs):

        search = self.request.query_params.get('search',None)
        if search is not None:
            qs = Package.objects.filter(Q(destination__name__icontains=search)|
                                        Q(destination__continent__icontains=search)|
                                        Q(package_name__icontains=search)|
                                        Q(city__icontains=search)).disctinct()

        else:
            qs = Package.objects.values('id','destination','package_name','city')

        serializer = PackageSerializer(qs,many=True)
        return Response(serializer.data,status=200)

My serializers:
class PackageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Package
        fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
                   'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
                   'fix_departure', 'rating', 'image', 'date_created', ]

        depth = 1

Here I checked the code and nothing seems to be wrong in any part but keeps getting the same above error.
Traceback:
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
    raise exc
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\apps\packages\views.py", line 251, in get
    return Response(serializer.data,status=200)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 760, in data
    ret = super().data
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 260, in data
    self._data = self.to_representation(self.instance)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
    return [
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
    attribute = field.get_attribute(instance)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
    raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `NestedSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'name'.

A: For nested relations you have to define nested serializer
class DestinationSerializer(serializers.Serializer):
    name = serializers.CharField()
    top = serializers.BooleanField()
    continent = serializers.CharField()

class PackageSerializer(serializers.ModelSerializer):
    destination = DestinationSerializer()
    class Meta:
        model = Package
        fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
                   'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
                   'fix_departure', 'rating', 'image', 'date_created', ]


text:
Q: How to find best match of element within array to a set array node.js Set array:
let arr = ["hello","my","name","connor"]

Array of all elements to compare to arr:
let allArr = ["hello my name is", "hello my name is connor", "hello connor name"]

So in this scenario, I would like a solution that picks the best element of allArr that matches to arr, its index with be suffice.
I have tried integrating two for loops e.g
for (i in allArr){
  for(x in arr){
     if(allArr[i].includes(arr[x]){
        do something
     }
  }
}

But doesn't seem to work properly.
Need the fastest, but best explained solution[only applicable if it is complicated haha].

A: You could map the count of each word in each sentences. Later, you could take the index of the max value.

var words = ["hello", "my", "name", "connor"],
    sentences = ["hello my name is", "hello my name is connor", "hello connor name"],
    counts = sentences.map(s => words.reduce((sum, word) => sum + s.includes(word), 0)),
    indices = counts.reduce((r, c, i, a) => {
        if (!(a[r[0]] >= c)) {
            return [i];
        }
        if (a[r[0]] === c) {
            r.push(i);
        }
        return r;
    }, []);

console.log(counts);
console.log(indices);


text:
Q: Sender's Logo in Gmail via PHP Is there any way I can control the contact image when sending an email via PHP even if i'm not on the recipients contacts?

A: Profile pictures is a functionality proposed by emails client. In you case, Gmail, the user #Sports might have created a Google account with his own email address and then set up a profile picture.
More about creating an account without gmail


text:
Q: Rampart: how to use a JKS certificate without any password I have the following situation:
a JKS keystore file without password, containing a private key ALSO unprotected. I've tried to configure Rampart in order to use this keystore, but i keep getting the following error:
Caused by: org.apache.rampart.RampartException: No password supplied by the callback handler for the user : "username"

my password callback handler is as follows:
public class PWCBHandlerCertificate implements CallbackHandler {
public void handle( Callback[] callbacks ) throws IOException, UnsupportedCallbackException {

    for ( int i = 0; i < callbacks.length; i++ ) {
        WSPasswordCallback pwcb = (WSPasswordCallback) callbacks[i];

        String id = pwcb.getIdentifer();
        int usage = pwcb.getUsage();
        if ( usage == WSPasswordCallback.DECRYPT || usage == WSPasswordCallback.SIGNATURE ) {
            Element temp = pwcb.getCustomToken();
            // used to retrieve password for private key
            if ( "username".equals( id ) ) {
                pwcb.setPassword( "" );
            }

        }
    }
}

}
what am i missing?
Thanks in advance

A: It turned out that rampart 1.5.2 (i don't know about newer versions, i must keep this one...) forces the certificate to have a valid password (not null and not empty).
I downloaded the source for rampart 1.5.2, and i found the following code inside the class BindingBuilder.java (package org.apache.rampart.builder):
WSPasswordCallback[] cb = { new WSPasswordCallback(user,
                WSPasswordCallback.SIGNATURE) };

        try {
            handler.handle(cb);
            if(cb[0].getPassword() != null && !"".equals(cb[0].getPassword())) {
                password = cb[0].getPassword();
                log.debug("Password : " + password);
            } else {
                //If there's no password then throw an exception
                throw new RampartException("noPasswordForUser",
                        new String[]{user});
            }
        }

The problem resides here:
if(cb[0].getPassword() != null && !"".equals(cb[0].getPassword()))

The exception is thrown if the password is received null or empty from the callback. In order to avoid this problem i had to comment out a part of the code like this:
if(cb[0].getPassword() != null /*&& !"".equals(cb[0].getPassword())*/)

I recompiled the class and replaced the resulting .class inside rampart-core-1.5.2.jar
The exception disappeared, i can now successfully use the passwordless certificate.
I hope it helps.


text:
Q: How to get id from a href link during popup I wish to get 'id' value from  href tag.
When i click the  tag the popup will shown , but i want id value within popup
HTML
            <a href="#myPopup" data-rel="popup" id="<?php echo $rows['vid'];?>" class="p-buy ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left">View Now

i want this 'id' value in popup it will come like id='1' ,id='2',..
'id' value shown properly in inspect area. But i am not getting this value to my popup
POPUP HTML

  <form method="post" action="">

Please fill below information

      Name:
      <input type="text" name="name" id="name" placeholder="Name">
      <input type="text" name="vids" id="vids" placeholder="video id">
      Email Id:
      <input type="text" name="email" id="email" placeholder="Email">
      Mobile:
      <input type="text" name="mobile" id="mobile" placeholder="Mobile">
      <input type="submit" name="submit" id="submit" data-inline="true" value="Submit">

  </form>

Then i use JQuery for to get the ID. But when i click the  tag it does not go to ready function also
JQUERY
$(document).ready(function()
{
   alert("ready");
   $("a").click(function()
   {
      alert("click");
      var pos = $(this).attr('id');
      alert(pos);
      $('#vids').val(pos);
   });
 });

Please help me anyone i stucked long time with this.
Thanks in advance

A: If you want to retrieve id in variable you can use document.getElementByTagName('href') and store into variable x. Then document.write(x.id) should write id of href.


text:
Q: Is there a way that I can connect a polygon format (JS) to a map (HTML) I'm trying to put a polygon format from Mapbox into the Mapbox map itself (via a Github copy for a project), and I haven't yielded any results.
I did the formatting, using different files, combining them into 1 via a combiner, etc.
Polygon (JS):
map.on('load', () => {
  // Add a data source containing GeoJSON data.
  map.addSource('maine', {
    'type': 'geojson',
    'data': {
      'type': 'Feature',
      'geometry': {
        'type': 'Polygon',
        // These coordinates outline Maine.
        'coordinates': [
          [
            [-125.15625000000001, 48.04870994288686],
            [-124.71679687499999, 43.32517767999296],
            [-125.15625000000001, 39.639537564366684],
            [-121.11328124999999, 34.59704151614417],
            [-121.11328124999999, 34.59704151614417],
            [-117.158203125, 32.47269502206151],
            [-105.732421875, 31.27855085894653],
            [-97.20703125, 25.64152637306577],
            [-84.287109375, 29.84064389983441],
            [-80.947265625, 24.84656534821976],
            [-74.970703125, 35.38904996691167],
            [-66.62109375, 45.02695045318546],
            [-68.73046875, 47.39834920035926],
            [-71.455078125, 44.84029065139799],
            [-82.880859375, 41.96765920367816],
            [-88.154296875, 48.22467264956519],
            [-109.072265625, 49.03786794532644],
            [-123.134765625, 49.15296965617042],
            [-125.15625000000001, 48.04870994288686],
          ]
        ]
      }
    }
  });

  // Add a new layer to visualize the polygon.
  map.addLayer({
    'id': ' ',
    'type': 'fill',
    'source': 'maine', // reference the data source
    'layout': {},
    'paint': {
      'fill-color': '#0080ff', // blue color fill
      'fill-opacity': 0.2
    }
  });
  // Add a black outline around the polygon.
  map.addLayer({
    'id': 'outline',
    'type': 'line',
    'source': 'maine',
    'layout': {},
    'paint': {
      'line-color': '#000',
      'line-width': 0
    }
  });
});

Said remaining copies of code are located in https://github.com/AliCodes-Beep/Google-Map-Clone


text:
Q: Handling database in Android I have a database which I need to manage within a library.
The library is the only one who will have access to the data, while anyone else will need to access it through the library API.
Do I need to implement content provider for this or is this overkill as it will anyway only be accessed internally?
Is the second option doing everything in raw SQL and then adding a thin API above?
Is there any solution in between these which takes advantage of available wrappers but don't require implementation of ContentProvider (which as far as I understand is not necessary here)?

A: You can create a service that is able to interact with the database. Your service will provide the API.


text:
Q: SOAP error when publishing Infopath 2010 form to Sharepoint I am working in a list which contains around 300 different fields.  I have also added another list as second data connection.     Everything is perfect at this stage and i am able to publish successfully.  After that i have given a action rule as Set Field Value to copy fields from the second data connection to Main data connection.   Now i am not able to save the form and publish the same.   I am getting "SOAP error when publishing Infopath form to Sharepoint" without any further description.    If i disable the rule, then its published successfully.  Since the above rule is necessary to copy data, i cannot disable the rule.    Kindly help me to fix this issue.

A: 300 Fields means you have created 300 columns in the Sharepoint list. That's pretty extreme for a sharepoint list. Especially since data will populate those fields. SOAP errors in infopath are generally a timeout with communicating between Infopath and the Sharepoint server, which means when you click publish it goes through each field in infopath and writes it in sharepoint. I have similar issues with a 250 field infopath form and I have begun to sacrifice lesser needed fields. If you have access to the farm you can try extending the timeout which I believe is defaulted at 5 minutes. Also from my experience Infopath takes especially long with calculated sharepoint fields, for me more than 3 is a deal breaker.

A: One possible problem maybe, the "Main Connection" is a receive data connection and so you are not able to change the values of this data.
Though you can create data connections that submit data to a list which you could use, you would just need to create another data connection that submits data to the same list as the "Main Connection".
Hope this helps!


text:
Q: How do I constrain a lazy composition before I know the callable arguments? So I'm playing around with GCC6 and its concepts implementation and I figured the Haskell Prelude would be a good source for experimenting. One of the core features of Haskell is function composition and this is something I needed to tackle straight away.
Mimicking the Haskell syntax as best that I could, I wrote this function:
template <typename F, typename G>
auto operator*(F f, G g)
{
  return [f, g](auto... args) {
    return f(g(args...));
  }
}

Which works great and allows me to do stuff like:
auto add([](int a, int b) { return a + b; }
auto doubled([](int a) { return a * 2; }

auto add_then_double(doubled * add);
assert(add_then_double(2, 3) == 10);

Happy, I decided to go back and apply some constraints to my function composition but I quickly hit a problem due to its laziness.
First I wrote this concept:
template <typename F, typename Ret, typename... Args>
concept bool Function()
{
  return requires(F f, Args ...args) {
    { f(args...) } -> Ret;
  }
}

Which I based off of the concepts found in Andrew Sutton's origin github project.
And so I tried to apply to my original function. The problem I have is that I don't know what G returns without knowing what arguments are passed to G so I can't constrain G and I don't know what F returns without knowing what parameter it is given and I don't know that because I don't know what G returns.
I'm pretty sure I need a new Function concept that doesn't care about the return type as my composition function doesn't care what F returns, so long as it's invokable. And I guess I could put the constraint on the inner lambda that the parameter types and correct for G and therefore for F but this means I can compose non-composable functions and won't get an error until the call site. Is this avoidable?
Maybe something like this:
template <typename F, typename G>
auto operator*(F f, G g)
{
  return [f, g](auto... args)
    // is it even possible to constrain here?
    requires FunctionAnyReturn<G, decltype(args)...>
      && FunctionAnyReturn<F, decltype(G(decltype(args)...))>
  {
    return f(g(args...));
  }
}

Is this the best I can do (if I can even do that)?

A: As you discovered, it is indeed important to put constraints at the right place. In your case it is the operator() of the result that must be constrained, not the composition function itself. You really can't do any better, consider for instance that many functions don't have a single return type (e.g. std::make_tuple). However while Concepts-Lite does touch on lambda expressions a little, it doesn't go as far as allowing a requires clause on them, so your attempt will not work.
In most situations my usual advice is to write the lambda expression such that the resulting operator() is naturally constrained thanks to SFINAE. In your case, this means avoiding return type deduction:
return [f, g](auto... args) -> decltype( f(g(args...)) )
{ return f(g(args...)); }

If you're using e.g. Clang, everything is peachy. If using GCC, you may run into a bug where GCC performs some checking too early.
An alternative is to go out of your way to 'unroll' the closure type of the lambda expression. By making it a user-defined type, you gain access to all the tricks and in particular you can then write the explicit constraints you want:
template<typename F, typename G>
struct compose_type {
    F first_composed_function;
    G second_composed_function;

    template<typename... Args>
    constexpr auto operator()(Args... args)
        // substitute in whichever concepts and traits you're actually using
        requires
            Callable<G, Args...>
            && Callable<F, result_of<G, Args...>>
    { return first_composed_function(second_composed_function(args...)); }
};

template<typename F, typename G>
constexpr compose_type<F, G> compose(F f, G g)
{ return { std::move(f), std::move(g) }; }

Live On Coliru


text:
Q: salesforce trigger or schedule invoke after a period of time I looked into salesforce trigger and scheduler is there any way i can create a scheduler to repeat itself for an hour or the time i configured in the screen.
Schedule should stop automatically after the given time.
inputs will be
Start time
Frequency
End time(This where the schedule should stop executing)
if you can provide a sample code will be great


text:
Q: Import Facebook posts and not just embed them I am looking at importing Facebook posts and not just embedding a Facebook iframe in the page. I want to be able to get the SEO benefits of having my website news page updated all the time by my Facebook page and I believe if I just use the Facebook embed code this wont work to improve it ?. Does anyone know of a tutorial or plugin for importing posts / pics into a php based website ?.
Thanks
Iain :-)

A: For this you may want to look at their graph api, https://developers.facebook.com/docs/reference/api/post/
https://developers.facebook.com/blog/post/490/
you need to authenticate to facebook and retrieve the post using the api
or you can use their plugin to display the fanpage posts on your website, it's much simpler.

A: Social2blog ( http://www.social2blog.com/ ) import facebook posts in your blog, with a creation of Wordpress post and then with real SEO benefits. Furthermore Social2blog permit to decide if you want to point the canonical url to Facebook post. The problem with Social2blog is that it works only with facebook page. Otherwise you can create your own php script, please refer to:
How to pull in Facebook Page posts as blog posts to WordPress?


text:
Q: IntelliJ auto detect indentation for each file I recently switched from Sublime Text to IntelliJ and I trying to figure out, if there's a way for IntelliJ to auto detect what indentation the current file is using and use that instead of the default
I have to deal with a lot of 3rd party code, which can have different indentation settings, which I'm not allowed to change for obvious reasons.
Sublime Text was able to detect and abide to the indentation for the current file, which is quite intuitive and unobtrusive. IntelliJ on the other hand just sticks to it's own settings, resulting in mixed tabs and spaces, wrong indentation levels and wrong merge conflicts.
Is there a way to make IntelliJ behave, other than having to manually change the indentation settings every time I get a file with different indentation.
Thanks

A: In recent versions of Intellij there is a Detect and use existing file indents for editing setting for this:

A: Each project you open in IntelliJ has it's own settings. You will need to set the indent style the first time you open up the project, but it will be saved after that (and can be different for every project you work on). From the IntelliJ help site:

Project settings are stored with each specific project as a set of xml files
  under the .idea folder. If you specify the
  default project settings,
  these settings will be automatically used for each newly created project.

You can edit the indent settings for the project in the Code Style dialog.


text:
Q: Can I have a user-defined error message next to a restplus model? I have written a Flask application that provides an API. I am using the RESTplus library.
I use a model to format the data. If a request is successful, the values are inserted into the model and the model is returned.
However, if the request is unsuccessful, the model is returned and all values are null. My goal is to return a user-defined error message with multiple key-value pairs. The error message should have a different structure than as Model.
Here is a minimal example:
from flask import Flask
from flask_restplus import Resource, fields, Api

app = Flask(__name__)

api = Api()
api.init_app(app)

books = {'1': {"id": 1, "title": "Learning JavaScript Design Patterns", 'author': "Addy Osmani"},
         '2': {"id": 2, "title": "Speaking JavaScript", "author": "Axel Rauschmayer"}}

book_model = api.model('Book', {
    'id': fields.String(),
    'title': fields.String(),
    'author': fields.String(),
})

@api.route('/books/<id>')
class ApiBook(Resource):

    @api.marshal_with(book_model)
    def get(self, id):
        try:
            return books[id]
        except KeyError as e:
            return {'message': 'Id does not exist'}

if __name__ == '__main__':
    app.run()

Successful output
curl -X GET "http://127.0.0.1:5000/books/1" -H "accept: application/json"
{
  "id": "1",
  "title": "Learning JavaScript Design Patterns",
  "author": "Addy Osmani"
}

Erroneous output
curl -X GET "http://127.0.0.1:5000/books/3" -H "accept: application/json"
{
  "id": null,
  "title": null,
  "author": null
}

Is it possible to have a user-defined error message next to a model? Is there an alternative?

A: Don't catch the exception in the get method and then return an object; anything you return from the method will be marshalled using the model.
Instead, follow the error handling documentation and use flask.abort() to set a 404 response with message:
# at the top of your module
from flask import abort

# in the resource class
@api.marshal_with(book_model)
def get(self, id):
    try:
        return books[id]
    except KeyError as e:
        raise abort(404, 'Id does not exist')

The second argument you give abort() is automatically turned into a JSON object with message key, so {"message": "Id does not exist"}.
You could also create a @api.errorhandler registration for the KeyError exception and turn that into a 404 response:
@api.errorhandler(KeyError)
def handle_keyerror(error):
    return {"message": f"Object with id {error} could not be found"}, 404

and then don't catch the exception in your get() methods:
@api.marshal_with(book_model)
def get(self, id):
    return books[id]

Note that when ERROR_404_HELP is set to True (the default) then the message is added to by RestPlus with an alternative route suggestion, tacked on to every 404 response:
curl -X GET "http://127.0.0.1:5000/books/3" -H "accept: application/json"
{
    "message": "Object with id '3' could not be found. You have requested this URI [/books/3] but did you mean /books/<id> ?"
}

This may not be that helpful in your specific case so you may want to disable ERROR_404_HELP.


text:
Q: Copy ListBox to Clipboard, return carrier not conserved In a C++ application using MFC, i would like to be able to copy the entire CListBox content to clipboard.
I found a function which copy the content, neverheless, the return carrier aren't conserved.
I look with an HexEditor, and it appear there is $0A instead of $0D&$0A.
Here is my code :
CListBox * myListBox = (CListBox *)GetDlgItem(IDC_LIST_RESULT);
CString sContents = _T("");
CString temp = _T("");
int NumberOfSelections = 0;

NumberOfSelections = myListBox->GetCount();
for(int Selection = 0; Selection <= NumberOfSelections-1; Selection++)
{
    myListBox->GetText(Selection, temp);
    sContents += temp;
    sContents +="\n";
}

if (OpenClipboard())
{
    HGLOBAL clipbuffer;
    char * buffer;

    if (EmptyClipboard())
    {
        clipbuffer = GlobalAlloc(GMEM_DDESHARE, sContents.GetLength() + 1);
        buffer = (char*)GlobalLock(clipbuffer);
        CStringA ansiString(sContents);
        size_t cbString = strlen(ansiString) + 1;
        strcpy_s(buffer, cbString, ansiString);
        GlobalUnlock(clipbuffer);

        if (SetClipboardData(CF_TEXT, clipbuffer) == NULL)
        {
            CString msg;
            msg.Format(_T("Unable to set Clipboard data, error: %d"), GetLastError());
            AfxMessageBox(msg);
        }
        else
            AfxMessageBox(_T("Successfully copied selected laps to clipboard"));
    }
    else
        AfxMessageBox(_T("Unable to empty Clipboard"));
    CloseClipboard();
}
else
AfxMessageBox(_T("Unable to open Clipboard"));
// TODO: ajoutez ici le code de votre gestionnaire de notification de contrôle

I use unicode configuration with Visual Studio 2013.
Anyone have some ideas ?
Thanks a lot,
Best regards,
Nixeus

A: There only a \n because that's what you put in the clipboard.
sContents +="\n";

It should be
sContents +="\r\n";


text:
Q: Jframe Program giving NoClassDefFoundError on run My Code
import java.awt.*;
 import javax.swing.*;

 // Create a simple GUI window
 public class TopLevelWindow {

    private static void createWindow() {

       //Create and set up the window.
       JFrame frame = new JFrame("Simple GUI");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       JLabel textLabel = new JLabel("I'm a label in the window",SwingConstants.CENTER);
       textLabel.setPreferredSize(new Dimension(300, 100));
       frame.getContentPane().add(textLabel, BorderLayout.CENTER);

       //Display the window.
       frame.setLocationRelativeTo(null);
       frame.pack();
       frame.setVisible(true);
    }

    public static void main(String[] args) {

       createWindow();

    }
 }

And how i run the program with the exceptions are

A: Use . rather than / to specify the fully qualified class name when using java
java java1.TopLevelWindow

Also add a package declaration:
package java1;


text:
Q: Short story about an astronaut that has to harvest/collect the body fluids of an alien for a panacea Short story read in the 60's or 70's, an astronaut has to enter an alien ship and collect the tears/sweat? of an alien to use as a wonder drug for humans. The alien has some sort of presence which affects the mental state of any human near it.

A: This is Stranger Station by Damon Knight.  There is a summary here:

"Stranger Station," Damon Knight, 1956 – Paul Wesson is stationed on Stranger Station, which will be visited by an overwhelmingly alien consciousness. His only companion is the robot (female) Aunt Jane. His purpose is to establish contact with the alien, in the interest of picking up a longevity serum that the aliens have offered to humanity as a gift.  He tries to endure the saturating presence of the alien mind–and the degradation of his ability to communicate with other humans that results from this communion–but he begins to fixate on what he calls Wesson's Law: "When two alien cultures meet, the stronger must transform the weaker with love or hate." He comes to suspect that the aliens, having determined that humanity will one day be a space-faring race, are attempting to "adapt" humanity to the aliens in advance, perhaps over the course of centuries. Humans will have been conquered–not by hate, but by love–and Wesson decides that he will use hate to resist.


text:
Q: How to detect whether the OS muted speaker in the browser? How to detect whether the OS muted speaker in the browser?
I want to detect it while the user can not hear any audio in my webRTC app.
enter image description here
enter image description here

A: To check if your browser tab is muted you can use tabs.MutedInfo.
But on your screenshots there's an OS volume slider, not from browser. You can't get information about your system volume from JS code running in browser.


text:
Q: Local HTML website hosted by XAMPP is not reachable when domain name is used instead of the local IP address in local network I have hosted a HTML webpage using XAMPP in LAN; I am able to access the webpage from other computers present in the same local network when I use http://IP address:port but unable to access it when I use a custom domain name.
My host file looks like this.
    192.168.1.24:90    cohab.com

My httpd-vhosts.config looks as follows.
    <VirtualHost 192.168.1.24:90>
    ServerAdmin webmaster@www.cohab.com
    ServerName www.cohab.com
    ServerAlias cohab.com
    DocumentRoot "C:/xampp/htdocs/cohab"
    </VirtualHost>

My HTML file is present in C:/xampp/htdocs/cohab directory. Where am i going wrong?


text:
Q: What is the difference between shr() and ushr() named functions in Kotlin Difference of a.shr(b) and a.ushr(b) functions in the Kotlin language.When use both the functions I'm getting same output so please help in to know the difference between these functions

A: *

*shr shifts your bits to right

*ushr also shift right, but fills up the most left bit with zero

If you're only doing bit shifts on positive values, there is no difference. If you're also doing it on negative values, there is a big difference.
                 Int          Binary
                 -63532       11111111111111110000000000000100
-63532 ushr 1    2147450882   01111111111111111000000000000010
-63532 shr 1     -32766       11111111111111111000000000000010
                              ^
                              |
                          Difference

In this case, the ushr will flip the left most bit so you're now having a positive value.


text:
Q: How to get the timezone offset in android? I found some similar questions, such as:
How to get the timezone offset in GMT(Like GMT+7:00) from android device?
How to find out GMT offset value in android
But all these answers(+12:00) are incorrect for New Zealand Daylight Saving Time now.
When I did debug, I got this from Google Calendar event object:
"dateTime" -> "2016-11-06T10:00:00.000+13:00"
So how to get the correct offset which should be +13:00?
Thanks.

A: To get the current offset from UTC in milliseconds (which can vary according to DST):
return TimeZone.getDefault().getOffset(System.currentTimeMillis());

To get a RFC 822 timezone String instead, you can simply create a SimpleDateFormat instance:
return new SimpleDateFormat("Z").format(new Date());

The format is (+/-)HHMM

A: So, I tried to get gmt offset through Calendar and SimpleDateFormat but both returns 0. I found the solution using deprecated methods in Date class.
So, this code works for me.
private double getOffset() {
    Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
    int defHour = calendar.get(Calendar.HOUR_OF_DAY);
    int defMinute = calendar.get(Calendar.MINUTE) + (defHour * 60);
    Date date = new Date(System.currentTimeMillis());
    int curHour = date.getHours();
    int curMinute = date.getMinutes() + (curHour * 60);
    double offset = ((double) curMinute - defMinute) / 60;
    return offset > 12? -24 + offset : offset;
}

Then you can format a result

A: This code return me GMT offset.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);

It returns the time zone offset like this: +0530


text:
Q: Git - branch commits history are duplicated I have a branch, and almost all commits had a wrong email "mywrong@email.com" and I wanted to change that e-mail to my current email "mynew@email.com".
While searching, I found this:
git filter-branch --commit-filter 'if [ "$GIT_COMMITTER_EMAIL" = "mywrong@email.com" ];
  then
    export GIT_AUTHOR_NAME="Sandrina Pereira";
    export GIT_AUTHOR_EMAIL=mynew@email.com;
    export GIT_COMMITTER_NAME="Sandrina Pereira";
    export GIT_COMMITTER_EMAIL=mynew@email.com;
  fi; git commit-tree "$@"'

See here the difference between COMMITTER and AUTHOR. It is important to really change the commit auth, otherwise wit will show that mynew did a commit under oldnew original commit. And here I want to change both author and commiter.
Then I did git commit -am "change author", git pull and git push.
The problem is that now all my commits are duplicated as you can see here
I searched how to delete those commits and I found this:
git filter-branch --commit-filter '
  if [ "$GIT_AUTHOR_EMAIL" = "mywrong@email.com" ];
     then skip_commit "$@";
  else git commit-tree "$@";
fi' HEAD

But I didn't try it yet... What should i do?
And on the next time I want to replace the e-mail commits what is the right command to avoid this mess?

A: Your question is a duplicate of a handful of other questions, but I will give an answer so that this question has some clousure.
You used git filter-branch from this question, in order to correct the email on a handful of commits.  This succeeded, however you then took the following incorrect actions:

Then I did git commit -am "change author", git pull and git push.

I don't think you needed to make a commit, but what is problematical is the git pull.  This pulled in the alternate original version of the branch on the remote, and then merged it into your local branch.  This resulted in the commits which you rewrote becoming duplicated.  Here is what you should have done immediately after running filter-branch:
git push --force origin master    # assumes your branch is master; change if needed

This would overwrite the remote branch, replacing it with the version you have created locally, containing the update email addresses.  Keep in mind that filter-branch, like git rebase, rewrites the history of a Git branch.  As a result, the finishing step to bring the branch to the remote is always doing a force push, to rewrite that remote history.
See this SO question for some tips to recover from the situation you are in now, but realize that just doing a force push would have avoided this problem to begin with.


text:
Q: How can I replicate an Eureka Client? I'm doing an app with Spring boot and Spring Cloud, have 2 microservices.  I'm using Eureka Server to register both microservices as a clients, but I want to replicate one of them.
How can I do that? I saw info on Google, but seems like I need to replicate Eureka Server, and I don't understand it.
Is it possible to replicate one eureka Client?
Thank you in advance!
I tried to replicate eureka server, but it's not the thing that I want to do. I want to replicate a client.


text:
Q: ICViewPager intercepting touch event from my uislider I've used ICViewPager to act as a scrollview with tabs. When i put a slider in the view, the user has to press the scroll knob for a second before moving it, otherwise the whole page moves with the slider.
I tried:

*

*setting the slider to exclusiveTouch.

*creating a slider controller and sending the touch event directly to the slider
-(CGRect)thumbRect
{
CGRect trackRect = [self trackRectForBounds:self.bounds];
CGRect thumbRect = [self thumbRectForBounds:self.bounds
                                  trackRect:trackRect
                                      value:self.value];
return thumbRect;

}

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
CGRect thumbFrame = [self thumbRect];

// check if the point is within the thumb
if (CGRectContainsPoint(thumbFrame, point))
{
    // if so trigger the method of the super class
    NSLog(@"inside thumb");
    return [super hitTest:point withEvent:event];
}
else
{
    // if not just pass the event on to your superview
    NSLog(@"outside thumb");
    return [[self superview] hitTest:point withEvent:event];
}
}

A: Had the same issue. I found a workaround by using a custom slider and used the UIGestureRecognizer instead of touchesBegan, touchesEnded functions


text:
Q: Grid sorting with nested objects How can I enable grid sorting with nested object. For example I have the following object which I bind locally to the grid
{
    DataId: 1,
    Duration: 4.5,
    Customer: {
        CustomerId: 1,
        Name: 'Foo'
    }
}

Now I want to enable sorting for the Name of the Customer (Customer.Name). The parse method didn't worked for me, cause I wrote a custom editortemplate which replace the complete customer with the new selected one.


text:
Q: The best way of checking for -moz-border-radius support I wanted some of those spiffy rounded corners for a web project that I'm currently working on.
I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly.
I already utilize jQuery so I looked at the excellent rounded corners plugin and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs.
I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific -moz-border-radius-* properties and if so utilize them.
The check for webkit support looks like this:
var webkitAvailable = false;
try {
    webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined);
}
catch(err) {}

That, however, did not work for -moz-border-radius so I started checking for alternatives.
My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse.
My best solution yet is as follows.
var mozborderAvailable = false;
try {
    var o = jQuery('<div>').css('-moz-border-radius', '1px');
    mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px';
    o = null;
} catch(err) {}

It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties

*

*-moz-border-radius-topleft

*-moz-border-radius-topright

*-moz-border-radius-bottomleft

*-moz-border-radius-bottomright
Is there any javascript/CSS guru out there that have a better solution?
(The feature request for this page is at http://plugins.jquery.com/node/3619)

A: Why not use -moz-border-radius and -webkit-border-radius in the stylesheet? It's valid CSS and throwing an otherwise unused attribute would hurt less than having javascript do the legwork of figuring out if it should apply it or not.
Then, in the javascript you'd just check if the browser is IE (or Opera?) - if it is, it'll ignore the proprietary tags, and your javascript could do it's thing.
Maybe I'm missing something here...

A: I know this is an older question, but it shows up high in searches for testing border-radius support so I thought I'd throw this nugget in here.
Rob Glazebrook has a little snippet that extends the support object of jQuery to do a nice quick check for border-radius support (also moz and web-kit).
jQuery(function() {
jQuery.support.borderRadius = false;
jQuery.each(['BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {
    if(document.body.style[this] !== undefined) jQuery.support.borderRadius = true;
    return (!jQuery.support.borderRadius);
}); });

Attribution
That way, if there isn't support for it you can fall back and use jQuery to implement a 2-way slider so that other browsers still have a similar visual experience.

A: How about this?
var mozborderAvailable = false;
try {
  if (typeof(document.body.style.MozBorderRadius) !== "undefined") {
    mozborderAvailable = true;
  }
} catch(err) {}

I tested it in Firefox 3 (true) and false in: Safari, IE7, and Opera.
(Edit: better undefined test)

A: Apply CSS unconditionally and check element.style.MozBorderRadius in the script?

A: As you're already using jQuery you could use jQuery.browser utility to do some browser sniffing and then target your CSS / JavaScript accordingly.

A: The problem with this is that Firefox 2 does not use anti-aliasing for the borders. The script would need to detect for Firefox 3 before is uses native rounded corners as FF3 does use anti-aliasing.

A: I've developed the following method for detecting whether the browser supports rounded borders or not. I have yet to test it on IE (am on a Linux machine), but it works correctly in Webkit and Gecko browsers (i.e. Safari/Chrome and Firefox) as well as in Opera:
function checkBorders() {
  var div = document.createElement('div');
  div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');
  for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {
    if ( /border.*?-radius/i.test(div.style[stylenr]) ) {
      return true;
    };
  return false;
};

If you wanted to test for Firefox 2 or 3, you should check for the Gecko rendering engine, not the actual browser. I can't find the precise release date for Gecko 1.9 (which is the version that supports anti-aliased rounded corners), but the Mozilla wiki says it was released in the first quarter of 2007, so we'll assume May just to be sure.
if ( /Gecko\/\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\/\d*/)[0].split('/')[1]) > 20070501 )

All in all, the combined function is this:
function checkBorders() {
  if ( /Gecko\/\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\/\d*/)[0].split('/')[1]) > 20070501 ) {
    return true;
  } else {
    var div = document.createElement('div');
    div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');
    for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {
      if ( /border.*?-radius/i.test(div.style[stylenr]) ) {
        return true;
      };
    return false;
  };
};


text:
Q: Can't manage to run a simple angular js example I wrote a very simple angular js sample that doesn't work and I don't understand why.
If anyone sees what I did wrong please let me know, and if not, what steps should I take in order to face it?
this is my index.html:

This is the index level

This is my only view (profile.html):

This is a profile page

And this is the js file:

var example = angular.module("example", ['ui.router']);

example.config(function($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state("profile", {
            url: "profile",
            templateUrl: "templates/profile"
        })
    $urlRouterProvider.otherwise("/profile")
});

I would expect the result to be:
This is the index level
This is a profile page

But this is what I get:

This is the index level

All the js file pathes are correct because I can see them in the developer tool.
Any help will be profoundly appreciated!

A: As you have .otherwise redirect to /profile, you should change you URL of state definition to below, so that ui-router will loaded the correct state with correct template.
$stateProvider
  .state("profile", {
     url: "/profile",
     templateUrl: "templates/profile" //make sure this template has correct path
})

A: I think that its not working for you because templateUrl isn't correct. It should be correct path to a file together with file extension (unless you use something on backend or the template was compiled and named with templates/profile) but angular will make an XHR call to get that file


text:
Q: Delphi: Is system menu opened? I Delphi, I need a function which determinates if the system menu (resp. window menu, the menu that appears when the icon is clicked) is opened. The reason is that I am writing a anti-keylogger functionality which sends garbage to the current active editcontrol (this also prevents keylogger which read WinAPI messages to read the content). But if system-menu is opened, the editcontrol STILL has the focus, so the garbage will invoke shortcuts.
If I use message WM_INITMENUPOPUP in my TForm1, I can determinate when the system menu opens, but I wish that I do not have to change the TForm, since I want to write a non visual component, which does not need any modifications at the TForm-derivate-class itself.
//I do not want that solution since I have to modify TForm1 for that!
procedure TForm1.WMInitMenuPopup(var Message: TWMInitMenuPopup);
begin
 if message.MenuPopup=getsystemmenu(Handle, False) then
 begin
  SystemMenuIsOpened := true;
 end;
end;

TApplicaton.HookMainWindow() does not send the WM_INITMENUPOPUP to my hook function.
function TForm1.MessageHook(var Msg: TMessage): Boolean;
begin
Result := False;
if (Msg.Msg = WM_INITMENUPOPUP) then
begin
// Msg.Msg IS NEVER WM_INITMENUPOPUP!
 if LongBool(msg.LParamHi) then
 begin
  SystemMenuIsOpened := true;
 end;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 Application.HookMainWindow(MessageHook);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Application.UnhookMainWindow(MessageHook);
end;

Even after very long research I did not found any information about how to query if the system-menu is opened or not. I do not find any way to determinate the opening+closing of that menu.
Has someone a solution for me please?
Regards
Daniel Marschall

A: Application.HookMainWindow doesn't do what you seem to think. It hooks the hidden application window, not the main form. To intercept WM_INITMENUPOPUP on a specific form, all you need to do is write a handler for it, as you have seen.
To do this generically for any owner form of a component, you could assign WindowProc property of the form to place the hook:
unit FormHook;

interface

uses
  Windows, Classes, SysUtils, Messages, Controls, Forms;

type
  TFormMessageEvent = procedure(var Message: TMessage; var Handled: Boolean) of object;

  TFormHook = class(TComponent)
  private
    FForm: TCustomForm;
    FFormWindowProc: TWndMethod;
    FOnFormMessage: TFormMessageEvent;
  protected
    procedure FormWindowProc(var Message: TMessage); virtual;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property OnFormMessage: TFormMessageEvent read FOnFormMessage write FOnFormMessage;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Test', [TFormHook]);
end;

procedure TFormHook.FormWindowProc(var Message: TMessage);
var
  Handled: Boolean;
begin
  if Assigned(FFormWindowProc) then
  begin
    Handled := False;

    if Assigned(FOnFormMessage) then
      FOnFormMessage(Message, Handled);

    if not Handled then
      FFormWindowProc(Message);
  end;
end;

constructor TFormHook.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FFormWindowProc := nil;
  FForm := nil;
  while Assigned(AOwner) do
  begin
    if AOwner is TCustomForm then
    begin
      FForm := TCustomForm(AOwner);
      FFormWindowProc := FForm.WindowProc;
      FForm.WindowProc := FormWindowProc;
      Break;
    end;
    AOwner := AOwner.Owner;
  end;
end;

destructor TFormHook.Destroy;
begin
  if Assigned(FForm) and Assigned(FFormWindowProc) then
  begin
    FForm.WindowProc := FFormWindowProc;
    FFormWindowProc := nil;
    FForm := nil;
  end;
  inherited Destroy;
end;

end.

You could then use this component on a form:
procedure TForm1.FormHook1FormMessage(var Message: TMessage; var Handled: Boolean);
begin
  case Message.Msg of
    WM_INITMENUPOPUP:
      ...
  end;
end;

The problem might be that if the form has any other components which do the same thing then you need to make sure that unhooking happens in reverse order (last hooked, first unhooked). The above example hooks in the constructor and unhooks in the destructor; this seems to work even with multiple instances on the same form.

A: If you don't want any modifications to TForm-derivate-class, why don't try pure Windows API way to implement your current solution, that is, use SetWindowLongPtr() to intercept the WM_INITMENUPOPUP message. Delphi VCL style to intercept messages is just a wrapper of this Windows API function actually.
For that purpose, use SetWindowLongPtr() to set a new address for the window procedure and to get the original address of the window procedure, both at one blow. Remember to store the original address in a LONG_PTR variable. In 32-bit Delphi, LONG_PTR was Longint; supposing 64-bit Delphi will have been released in the future, LONG_PTR should be Int64; you can use $IFDEF directive to distinguish them as follows:
  Type
    {$IFDEF WIN32}
    PtrInt = Longint;
    {$ELSE}
    PtrInt = Int64;
    {$ENDIF}
    LONG_PTR = PtrInt;

The value for nIndex parameter to be used for this purpose is GWLP_WNDPROC. Also, pass the new address for the window procedure to dwNewLong parameter, e.g. LONG_PTR(NewWndProc). The NewWndProc is a WindowProc Callback Function that processes messages, it is where your put your intercept criteria and override the default handling of the message you are going to intercept. The callback function can be any name, but the parameters must follow the WindowProc convention.
Note that you must call CallWindowProc() to pass any messages not processed by the new window procedure to the original window procedure.
Finally, you should call SetWindowLongPtr() again somewhere in your code to set the address of modified/new window procedure handler back to the original address. The original address has been saved before as mentioned above.
There was a Delphi code example here. It used SetWindowLong(), but now Microsoft recommends to use SetWindowLongPtr() instead to make it compatible with both 32-bit and 64-bit versions of Windows.
SetWindowLongPtr() didn't exist in Windows.pas of Delphi prior to Delphi 2009. If you use an older version of Delphi, you must declare it by yourself, or use JwaWinUser unit of JEDI API Library.

A: Not tried this myself, but give this a shot:
Use GetMenuItemRect to get the rect for item 0 of the menu returned by GetSystemMenu.
I (assume!) GetMenuItemRect should return 0 if the system menu is not open (because system could not know the rect of the menu item unless it is open?) If the result is non-zero, check if the coords returned are possible for the given screen resolution.
If you have the time, you could look into AutoHotKey's source code to see how to monitor when system menu is open/closed.


text:
Q: Git - branch present on list but not found to delete I have an old branch presence on git branch list, but I do not able to remove it using:
git branch -D hotfix/my_old_branch

error: branch 'hotfix/my_old_branch' not found.

Trying to git push origin :hotfix/my_old_branch

error: unable to delete 'hotfix/my_old_branch': remote ref does not
  exist

Any idea?
EDIT:
git branch ... the branch appears on list
$ git branch
* Dev
  Pro
  Test
  hotfix/my_old_branch
  master

git branch -D hotfix/my_old_branch ...

error: branch 'hotfix/my_old_branch' not found.


text:
Q: what are the dangers of letting website members upload js for other members to use? for example CodePen and Khan Academy programming projects. they let their users upload js scripts that will run on other computers, codepen even lets users with pro account use 3rd libraries. I want to do the same thing on my site, how dangerous is this ? how to minimise risks ?

A: It's relatively quite safe if you implement proper sandboxing.
The one thing you want to avoid is letting user code run at the top level of other users' browsers, because if you permit that, all data the other user has on the website could be retrieved, logged, and stolen, among other things. But if you make sure the user code runs not on the top level, but inside a sandboxed iframe (one that can't make the top window run anything), it'll probably be fine.
See this question on Meta Stack Overflow for a similar discussion of the issue. The sites you mentioned, and other sites that implement live code editors from users like Stack Overflow and JSFiddle and many more all use this technique of running users' code inside a sandboxed iframe, so that code that runs can't reach the top level window, whose data must be kept safe. The iframe should also use a different origin (if any) from the parent site - modern browsers have naturally implemented pretty strict restrictions for cross-site communication precisely for this sort of reason (so that an iframe from one origin can do very little to a parent window on another origin, unless the parent window is specifically set up such things).
I say that a sandboxed iframe is pretty safe but not absolutely safe because it's not impossible that something like Spectre could eventually be exploited in front-end JavaScript to do something truly productively malicious. I don't think it's been seen in the wild yet, and it might never be, but it's not impossible.


text:
Q: An antiderivative of an odd function is even. Proof in general. We have:

*

*$\int f(x)dx=F(x)+C$,

*$f(x) = -f(-x)$ - odd function.

Proof that $F(x)$ - even function.

My suggetion (please, check it):

*

*Since
$\int f(x)dx = F(x) + C$,
$\int f(-x)dx = -F(-x) + C$.

*Since
$f(x)=-f(-x)$,
$\int f(x)dx=-\int f(-x)dx$

*Hence,
$F(x) + C = F(-x) + C \Rightarrow F(x)=F(-x)$

The nuance is that those constants are not necessarily the same. I mean, I know that this statement is correct, but I cant find the justification of this C-issue.
Even more. If eberything above is true, can we use the same technique to prove the reverse statement, i.e. an antiderivative of an even function is odd?

A: Your idea is correct, but can be streamlined.
You can prove that two differentiable functions are equal by proving that they have the same derivative and the same value at some point. Equivalently, that their difference is constant (derivative zero) and has value zero at some point.
Let $f$ be continuous over $\mathbb{R}$ and odd. Let $F$ be an antiderivative of $f$. Then we can consider $G(x)=F(x)-F(-x)$. Then, using the chain rule,
$$
G'(x)=F'(x)+F'(-x)=f(x)+f(-x)=f(x)-f(x)=0
$$
and $G(0)=F(0)-F(0)=0$.
Can you prove that an antiderivative of an even function $f$ is odd? Not in general. There is only one antiderivative of an even function that's odd, precisely the only antiderivative $F$ such that $F(0)=0$.

A: Basically, in step $3$ you use the initial value for the odd function $f(-0)=-f(0)=0$:
$$f(-x)=-f(x) \iff \\
\int f(-x)dx = \int -f(x)dx \iff \\
-F(-x)+A=-F(x)+B \iff \\
\require{cancel}\cancel{-F(-0)}+A=\cancel{-F(0)}+B \iff \\
A=B.$$

A: If $f$ is odd,
$$F(x):=\int_0^x f(x)\,dx+C\implies
\\F(-x)=\int_0^{-x}f(x)\,dx+C=-\int_0^{x}f(-x)\,dx+C=F(x).$$
If $f$ is even,
$$F(x):=\int_0^x f(x)\,dx+C\implies F(0)=C$$ and in general $F$ is not odd.


text:
Q: How to apply D3 data interpolate/animate functions to a dynamically changing pie chart I currently have a sample pie chart in the js fiddle that is able to do a static update between two datasets (with the second dataset having more values)
[1,2,3,4,5]

[1,2,3,4,5,6,7,8,9,10]

http://jsfiddle.net/qkHK6/115/
My aim is to get the data join animation depicted in
 http://bl.ocks.org/mbostock/5682158
There obviously is quite a bit of complication when Mike is using the findPreceding and findNeighbouring functions and these are obviously used to form the animation with the new data.
function findNeighborArc(i, data0, data1, key) {
  var d;
  return (d = findPreceding(i, data0, data1, key)) ? {startAngle: d.endAngle, endAngle: d.endAngle}
      : (d = findFollowing(i, data0, data1, key)) ? {startAngle: d.startAngle, endAngle: d.startAngle}
      : null;
}

// Find the element in data0 that joins the highest preceding element in data1.
function findPreceding(i, data0, data1, key) {
  var m = data0.length;
  while (--i >= 0) {
    var k = key(data1[i]);
    for (var j = 0; j < m; ++j) {
      if (key(data0[j]) === k) return data0[j];
    }
  }
}

// Find the element in data0 that joins the lowest following element in data1.
function findFollowing(i, data0, data1, key) {
  var n = data1.length, m = data0.length;
  while (++i < n) {
    var k = key(data1[i]);
    for (var j = 0; j < m; ++j) {
      if (key(data0[j]) === k) return data0[j];
    }
  }
}

However I'm really struggling to apply it to my own js fiddle graph I'm unsure how to apply the information  between two simple data arrays as obviously the key functions are not really needed.
If anyone could point me in the right direction or would be able to give some advice I'd appreciate it as I've attempted this several times and I'm still trying to get to grips d3 and its syntax.

A: To animate a transition for a pie chart where values are added, the same tween function as with the same number of elements can be used (see e.g. this example). The only difference is the initialisation for the new arcs -- instead from starting from where they actually are, they start from 0 to make it appears as if they're coming in.
The trick is therefore to take this into account when setting ._current:
.each(function(d) {
        this._current = {data: d.data,
                         value: d.value,
                         startAngle: 0,
                         endAngle: 0};
    });

Apart from that, the code is basically the same as for the example I've linked to above. Complete example here. I've simplified your code (e.g. removed the additional g elements) so that the core update code is easier to understand.


text:
Q: Is there a faster way to compare these decimals? I have a stream of decimals and I am trying to compare the most recent decimal to the difference of the last 6 decimals, I may increase this number
I have the following class
public class CompareRandom
{
    private const decimal DIFFERENCE = 1.8m;

    public decimal a;
    public decimal b;
    public decimal c;
    public decimal d;
    public decimal e;
    public decimal f;
    public decimal g;

    public bool Compare(decimal num)
    {
        this.g = this.f;
        this.f = this.e;
        this.e = this.d;
        this.d = this.c;
        this.c = this.b;
        this.b = this.a;
        this.a = num;

        if (b != decimal.Zero && b / DIFFERENCE > a)
        {
            return true;
        }

        if (c != decimal.Zero && c / DIFFERENCE > a)
        {

            return true;
        }

        if (d != decimal.Zero && d / DIFFERENCE > a)
        {
            return true;
        }

        if (e != decimal.Zero && e / DIFFERENCE > a)
        {
            return true;
        }

        if (f != decimal.Zero && f / DIFFERENCE > a)
        {
            return true;
        }

        if (g != decimal.Zero && g / DIFFERENCE > a)
        {
            return true;
        }

        return false;
    }
}

Then I initialize it as volatile
volatile static CompareRandom CompareRandom = new CompareRandom();

Then I call CompareRandom.Compare(value) synchronously as part of a loop that updates every 1ms to compare the values.
The part I am the most interested in knowing if there is a faster way to do is this part
    this.g = this.f;
    this.f = this.e;
    this.e = this.d;
    this.d = this.c;
    this.c = this.b;
    this.b = this.a;
    this.a = num;

A successful answer will demonstrate a faster execution of the method Compare
See if you can make it faster:
https://dotnetfiddle.net/tLw8qM
https://dotnetfiddle.net/jd0bSF

A: You don't need to perform the division every time. Instead, multiply a by DIFFERENCE to obtain a threshold:
// Name changed to be more conventional
private const decimal Difference = 1.8m;

public bool Compare(decimal num)
{
    g = f;
    f = e;
    e = d;
    d = c;
    c = b;
    b = a;
    a = num;
    var threshold = num * Difference;
    return (b != decimal.Zero && b > threshold) ||
           (c != decimal.Zero && c > threshold) ||
           (d != decimal.Zero && d > threshold) ||
           (e != decimal.Zero && e > threshold) ||
           (f != decimal.Zero && f > threshold) ||
           (g != decimal.Zero && g > threshold);
};

As asides:

*

*It's odd for a Compare method to return bool rather than an integer; given that it's not the "common" meaning of Compare, it's probably worth renaming it for clarity

*It's very odd for a comparison method to change the state of an object, as this is doing (assigning to a) - another good reason to change the name.

Using a collection instead of separate variables would make all of this more maintainable, but I'd be surprised if it improved the speed.

A: I also really like the idea of eliminating the division, but I don't like the way you're handling booleans: the original question says something like:
if condition1 then return true;
if condition2 then return true;
if condition3 then return true;

If condition1 is true, then the code does not bother about the calculation of the other conditions (why would it, when one condition is true, then the OR of all conditions also is true).
The proposal from Jon looks as follows:
return (condition1 || condition2 || condition3)

This does exactly the same thing, but the fact if the calculation of the OR equation is determined by the compiler: if you're dealing with an older compiler, not performing optimsation, then the entire calculation is done, even if condition1 is true.


text:
Q: Get only users who do not have the id equal to a condition (SQL) I have two tables, user:

id
full_name

1
Beatriz

2
Mauro

3
Jose

4
fran

approver :

id
subordinate_id
approver_id

1
1
2

2
3
4

I would like to bring up the names of people who are not registered in the subordinate_id column
I did the following query:
SELECT
    U.full_name
FROM user AS U
INNER JOIN approver as A
ON U.id <> A.subordinate_id ;

enter image description here
and still users are coming in that are in the subordinate_id column of the approver table.
I would like to get the result only for user names that are not subordinate_id, can someone help with this?
I would like a result with only the users that are not subordinate_id

A: This is simple to accomplish an ansi-sql with a not exists semi join:
Select full_name
from user u
where not exists (
  select * from approver a
  where a.approver_id = u.id <-- or (subordinate_id, whichever it should be)
);


text:
Q: Auto complete milestone step and move to next step I have an Entitlement process where in each milestone there are multiple steps. Milestone 1 first step says case not assigned to user after 1 day send alert email to manager. Milestone 1 second step says after 2 days if case not assigned auto assign it to a person. Then it moves onto Milestone 2.
However if step 1 is violated it sends the email to the manager but never moves on to step 2. Instead it shows how much time we are beyond the failure of step 1.
Is there a way for it to move to step 2 automatically. The conditions are the same except for time passed.
I added a checkbox and when step 1 violation occurs it sends and email and performs a field update on the checkbox setting it to true. However the SLA is not re-evaluated when the field update occurs. I have tried it with and without the field update being told to re-evaluate workflow rules. I can manually edit the record and set the box to true and when I save it re-evaluates and moves on to the next step.
How do I get it to re-evaluate the SLA steps and milestones when a step performs a field update after violation?


text:
Q: Can I pass parameters specific to an exe while launching it from a UWP app that has full trust capabilities? In the Package.appmanifest we specify the GroupID and the parameters for launching an executable, for example - mstsc.exe. Can we also pass some parameters like mstsc /v:hostname? I have tried passing it that way but that hasn't worked. Is there a different way of doing this?
Thanks!!

A: The FullTrustProcessLauncher API/extension can only launch EXEs that are included in the package. That EXE will receive the parameters you have specified in the manifest.
If you want to launch mstsc.exe (or any other EXE on the system outside of your package) you can do so by including a simple launcher EXE in your package that you launch via FullTrustProcessLauncher and it then takes care of launching the EXE you ultimately want to run, with the parameters of your choice.
I have a blog post with examples here (one of them actually launches mstsc.exe):
https://stefanwick.com/2018/04/06/uwp-with-desktop-extension-part-2/