text:
Q: Hoe can I view the skeleton in 3D coordinate system in matlab I have the following code in matlab which save the pics of each position that the skeleton at, but it displayed as a skeleton in 2D coordinate system.
In order to better use the data, I want to make the skeleton view in 3D coordinate system.
Here is the code that I am running, could anybody tell me how to make is possible?
>> for j=1:size(JointLocation_3D,1)
    for jointNum=1:14
    XL(1,jointNum)= JointLocation_3D(j,jointNum*3-2);
    XL(2,jointNum)=JointLocation_3D(j,jointNum*3-1);
    XL(3,jointNum)=JointLocation_3D(j,jointNum*3);
    end

    h=figure(j);
    i=1;
    x_leg = XL(1,i*14-13:i*14-8);
    y_leg = XL(2,i*14-13:i*14-8);
    z_leg = XL(3,i*14-13:i*14-8);
    line(x_leg,y_leg,z_leg,...
        'Marker', 'o',...
        'Color','r',...
        'LineWidth',5,...
        'MarkerSize',8,...
        'MarkerEdgeColor','b',...
        'MarkerFaceColor','b');
    hold on

    %arms and shoulders
    x_arm_right = XL(1,i*14-7:i*14-5);
    y_arm_right = XL(2,i*14-7:i*14-5);
    z_arm_right = XL(3,i*14-7:i*14-5);
    line(x_arm_right,y_arm_right, z_arm_right,...
        'Marker', 'o',...
        'Color','r',...
        'LineWidth',5,...
        'MarkerSize',8,...
        'MarkerEdgeColor','b',...
        'MarkerFaceColor','b');
    hold on;

    x_arm_left = XL(1,i*14-4:i*14-2);
    y_arm_left = XL(2,i*14-4:i*14-2);
    z_arm_left = XL(3,i*14-4:i*14-2);
    line('XData',x_arm_left,'YData',y_arm_left, 'ZData',z_arm_left,...
        'Marker', 'o',...
        'Color','r',...
        'LineWidth',5,...
        'MarkerSize',8,...
        'MarkerEdgeColor','b',...
        'MarkerFaceColor','b');
    hold on;

    line('XData',[XL(1,i*14-5); XL(1,i*14-1); XL(1,i*14-4)],...
        'YData',[XL(2,i*14-5); XL(2,i*14-1); XL(2,i*14-4)],...
        'ZData',[XL(3,i*14-5); XL(3,i*14-1); XL(3,i*14-4)],...
        'Marker', 'o',...
        'Color','r',...
        'LineWidth',5,...
        'MarkerSize',8,...
        'MarkerEdgeColor','b',...
        'MarkerFaceColor','b');
    hold on;

    mid_point = [mean(XL(1,i*14-11:i*14-10));mean(XL(2,i*14-11:i*14-10));mean(XL(3,i*14-11:i*14-10))];
    line('XData', [mid_point(1); XL(1,i*14-1);  XL(1,i*14)],...
        'YData',[mid_point(2); XL(2,i*14-1);  XL(2,i*14)],...
        'ZData', [mid_point(3); XL(3,i*14-1); XL(3,i*14)],...
        'Marker', 'o',...
        'Color','r',...
        'LineWidth',5,...
        'MarkerSize',8,...
        'MarkerEdgeColor','b',...
        'MarkerFaceColor','b');
  % hold off
   hold on
     figure();
     xlim([-50,350]);
     ylim([-350,350]);
     zlim([1100, 1700]);
     %axis off;
     axis normal
     grid on;
     %view(3);
     %view(90,30);
     %view(-181,-90);

      set(h,'visible','off');
      str=strcat('C:\Program Files\VirtApps\MATLAB\remove',sprintf('3D_%.4d',j),'.jpg');
      saveas(h,str);
 close all
end


text:
Q: wp-cron for a multiple server wordpress installation I am setting up wordpress multisite website on a multiple server stack (behind an ELB).
I have the following setup

*

*3 Apache Instances

*1 MySQL Server

*1 Memcache Server

*S3 bucket for uploads

All of the setup is working perfectly. My question is "Anything special required for wp-cron"?
A normal cron generally runs only on 1 Server. Should I disable wp-cron and add it to a cron job on 1 of the instances? I am not trying to optimize the cron, if wp-cron will continue to work on multiple instances, then i am fine.
Plugins upgrades & wordpress upgrades will be disabled and done manually.

A: wp-cron works in a slightly different way to a normal cron.  It will only run when your site has traffic.
Unless there's anything specific to your environment, there should be no reason why you can't just run wp-cron as per normal, especially given that there is only one database involved.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PreparedStatement in Java on a Fulltext MSSQL Table only takes 3 Arguments Strange behavior.
We have the MSSQL server 2008 R2.
Our Java Servlet is calling a PreparedStatement with the following join.
... inner join Containstable (fulltextTable, mycolumn, ?) as KeyTable on id = KeyTable.[KEY] ...

Where ? = needle
This works fine.
But when i add two more arguments to Containstable like this:
... inner join Containstable (fulltextTable, mycolumn, ?, ?, ?) as KeyTable on id = KeyTable.[KEY] ...

Where ? = needle (Search for), ? = LANGUAGE N'German' (Language), ? = 250 (Limit result to 250 rows)
I get this exception:
java.sql.SQLException: Argument data type nvarchar is invalid for argument 4 of CONTAINSTABLE function.

This works fine in SQL Server Management Studio.
Is this a Problem with the SQLServerDriver in Java?
Cheers
Per
Here is my Code - this works:
if (contains!=null && contains.length()!=0) {
    sql.append(" inner join Containstable( myFulltext, myColumn, ?) as KeyTable on id = KeyTable.[KEY]");

    elementTypes.add(Types.NVARCHAR);
    paramObject.add(contains);
    //elementTypes.add(Types.NVARCHAR);
    //paramObject.add("LANGUAGE N'German'");
    //elementTypes.add(Types.BIGINT);
    //paramObject.add(maxResults);
}

A: I suspect this is because the third 'parameter' to CONTAINSTABLE is not a normal, scalar parameter, it's a keyword (LANGUAGE) followed by a value.
Most likely JDBC is transforming LANGUAGE N'German' into 'LANGUAGE N''German''' and the resulting SQL is this, which is also invalid in SSMS:
...containstable(myTable, myColumn, 'needle', 'language N''German''', 250)
But of course it should be this:
...containstable(myTable, myColumn, 'needle', language N'German', 250)
You can confirm this guess by using SQL Profiler to trace the SQL actually being sent to the server. As for a solution, I don't know if JDBC will accept this:
...containstable(myTable, myColumn, ?, language ?, ?)
If it doesn't, you may have to use dynamic SQL to build a complete SQL string to execute, something like this (my quotes may not be completely correct, but you should get the idea):
set @sql = N'...containstable(myTable, myColumn, ''' + @search term + ''', language ''' + @language + ''', + cast(@rows as nvarchar(10)) + ')'
Unfortunately TSQL syntax is very inconsistent about where parameters are allowed and not, and this appears to be one such case.


text:
Q: Transform Async Task method target framework 4.5 to TargetFramework 2.0 I have SSO service that uses async Task<ActionResult> to get the URL
It works fine on my local environment but when I release on live I get following Error:

Server Error in '/XXXX Application.
"async void" Page events are unsupported in the current application
  configuration. To enable this, set the following configuration switch
  in Web.config:
   For more information, see
  http://go.microsoft.com/fwlink/?LinkId=252465.

I have researched on this and apparently Async Task feature was developed for 4.0-4.5 .net framework. There was some different patterns or methodologies to do this in previous .net framework.

A: First prize would obviously to push for .Net 4.5 to be installed or at least .Net 4. But since you're asking about .Net 2, this probably isn't an option.
If your call made to the server blocks until complete and the work on the server is async, you can make use of the Thread class to delegate work in different threads.
Here are some thoughts ways of achieving this:
No return types, No parameters
var ts = new ThreadStart(DoWorkAsync);
new Thread(ts).Start();
...
public void DoWorkAsync()
{
   // This happens on a different thread.
}

No return types, with parameters
int id = 1;
var pts = new ParameterizedThreadStart(DoWorkWithParamsAsync);
new Thread(pts).Start(id);
...
public void DoWorkWithParamsAsync(object obj)
{
    // This happens on a different thread.
    int id = (int)obj;
}

With return types (IAsyncResult)
You could use the BeginInvoke method an then use a specific delegate signature with a return type:
Func<int> returnsIntDel = DoWorkReturnIntAsync;
var asyncRes = returnsIntDel.BeginInvoke(null, null);
//... some other work on main thread here...
int returnedInt = returnsIntDel.EndInvoke(asyncRes);
Console.WriteLine("Done");
...
public int DoWorkReturnIntAsync()
{
    // This happens on a different thread.
    return 0;
}

Synchronizing between threads
If you run into any synchronization scenarios where Threads need to communicate or wait for each other, there are Synchronization Primitive class available for these scenarios (images from filterdCode blog).

*

*ManualResetEventSlim

*SemaphoreSlim

*CountdownEvent

*Barrier


text:
Q: what causes the weird "UNIQUE constraint failed: auth_user.username" error? I try to insert data in user model into other model by one to one relationship. In specific, I want insert username,email and password attributes of User into other models.In Addtional, I intend to create both User model and other model in one form. So, I override the save method in modelform. It works partially and be able to insert data in both models and databases, except throw a UNIQUE constraint failed: auth_user.username error.
In models.py
class Staff(models.Model):

  yes_or_no = ((True, 'Yes'),(False, 'No'))
  male_or_female = ((True,'Male'),(False,'Female'))

  user = models.OneToOneField(User, unique=True)

  gender = models.BooleanField(default = True, choices = male_or_female)
  birthday = models.DateField(default =None,blank = False, null = False)
  created = models.DateTimeField(default=datetime.now, blank=True)
  authorized = models.BooleanField(default=False,choices = yes_or_no)
  store_id = models.ForeignKey(Store,default=1)

  @property
  def name(self):
    return self.user.username
  @property
  def email(self):
    return self.user.email
  @property
  def password(self):
    return self.user.password
  @property
  def first_name(self):
    return self.user.first_name
  @property
  def last_name(self):
    return self.user.last_name

  def __str__(self):
    return self.user.username

In forms.py
 class StaffForm(forms.ModelForm):
    name = forms.CharField(max_length=100)
    email= forms.EmailField(max_length=100, required=True)
    password = forms.CharField(max_length=50)

    store_id = forms.ModelChoiceField(queryset = Store.objects.all(),empty_label="--------") # select values ?
    first_name = forms.CharField(required = True,max_length=100)
    last_name = forms.CharField(required = True,max_length=100)

    class Meta:
        model = Staff
        fields = ('gender','birthday','authorized','store_id')
        widgets = {'authorized':forms.RadioSelect,
                   'gender':forms.RadioSelect,
                    'birthday':SelectDateWidget(years=range(date.today().year-50,date.today().year))
        }

    def save(self,*args,**kwargs):
        Staff = super(StaffForm,self).save(commit=False)
        user = User.objects.create(
            username=self.cleaned_data['name'],
            first_name=self.cleaned_data['first_name'],
            last_name = self.cleaned_data['last_name'],
            email= self.cleaned_data['email'])
        user.set_password(self.cleaned_data['password'])
        if self.cleaned_data['authorized']:
            user.is_staff = True
        Staff.user = user
        Staff.save()

In views.py
@login_required(login_url='/dataInfo/login/')
def createstaff(request):

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = StaffForm(request.POST or None)
    # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            form.save()

            return HttpResponseRedirect('/dataInfo/staff_view/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = StaffForm()
    return render(request, 'dataInfo/create_staff.html', {'form': form})


text:
Q: how to access angularjs variable in other html page java script how to access angularjs variable from controler to other html page java script
controller
 $scope.names = [
                      {name:'Jani'} ,
              {name:'raaj'}
                      ];
               $scope.number = names.length;

i need to display use number in html page JavaScript please help in how to use it

A: function getAngularValue(){
 var number = {};
 number = angular.element(document.getElementById("YOUR_ANGULAR_PAGE_ID")).scope().number;
}


text:
Q: Swift: Create like and comment buttons like the Facebook and Twitter iOS apps Working on a  social networking iPhone app written in Swift and I'm trying to figure out how to create a like button and a comment button similar to the ones on the Facebook and Twitter iOS apps.
For example, for my current like button, I have a UIButton with a smiling emoticon as the image of the UIButton inside the prototype Cell. Just to the right of this button, I have a UILabel with the text "Like" (indicating that the smiling emoticon to the left is a like button).
How can one create a button that has the icon and the text together as one button so that the user can tap either on the Like icon part or the "Like" text part of the button which makes it easier for the user to tap the like button?
Screenshot: Facebook buttons example

Screenshot : Twitter buttons example

I took a screenshot of the Twitter buttons when my finger was pressing the like button. Notice how the like button here is greyed out (both the heart icon part and the number of likes). This is the effect I would like.
I appreciate any help. Thank you.

A: I'll only give you a basic idea of how to do this because your question is broad and did not show what you have tried.
Basically, create a UIButton subclass. Let's call it SocialButton.
Override the drawRect method in the SocialButton class. In the method, you should use UIGraphicsGetCurrentContext() to get a CGContext. Then call CGContextDrawImage to draw the image in a CGRect. This CGRect is the position that your image will go.
Here's some code to give you an idea:
class SocialButton: UIButton {
    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        CGContextDrawImage(context, someRect, UIImage(named: "someImage")?.CGImage)
    }
}

someRect is the rectangle that the image will be drawn in.
EDIT:
To add a social button to the storyboard, you need to add @IBDesignable on top of your class. And I think you should also add a property called image. This way people can set what image they want in the button. So now the class will look like this:
@IBDesignable
class SocialButton: UIButton {
    @IBInspectable // This is added so that you can change the image in interface builder
    var image: UIImage?

    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        CGContextDrawImage(context, someRect, self.image?.CGImage)
        // You can also set the tint, bg color and other stuff here.
    }
}

Now that's all you have to change in your class. On to the storyboard!
First, drag a UIButton to the view controller and select it:

Then, open the identity inspector on the right. If you don't know what it is, just click the ID card icon on the left side of Xcode.

Do you see that "Class" field? Just type "SocialButton" in there and press enter:

Switch to the property inspector(The one with a slider icon), you should see your custom button's image property:

You can select an image using the property inspector and if you have implemented drawRect correctly, you should see your image drawn on the left of the button now.

A: You can maybe also use Font Awesome to add custom icon then a text to a UIBUtton .
For example you can use :
buttonName.setFAText(prefixText: "follow me on ", icon: FAType.FATwitter, postfixText: ". Thanks!", size: 25, forState: .Normal, iconSize: 30)

to have your label and a twitter icon.
Hope this will help you !


text:
Q: How to divide 6.4 miles per hour into integer blocks I promise this is not a homework problem, but my brain cannot figure out the math to solve this problem that is relatable to a similar situation to my own:
You want to run on a treadmill at an average of 6.4 mph for 29 minutes. However, the treadmill can only go at an integer number of miles per hour, so you can set it to go at 5, 6, 7, etc. but not 6.4. You do not want to go any faster than 8 mph, and no slower than 4 mph. How do you divide the 29 minutes into time blocks, where each block is at a certain integer mph, such that by averaging each block you get 6.4 mph?

A: I am sure there are a lot of possible ways to solve this, and by no means the solution is unique:
My way by assuming that we're allowed to switch the speed at intervals we choose.
We want to have something like
$$
\frac{(x_1k_1+\ldots +x_nk_n)}{x}=6.4
$$
with $k_i\in\{4,5,6,7,8\}$ and $\sum x_i=x$. Clearly we want to have an integer at the RHS, so let's choose $x=10$ for now which gives us
$$
\frac{(x_1k_1+\ldots +x_nk_n)}{10}=6.4\iff (x_1k_1+\ldots +x_nk_n)=64
$$
this means, since we chose to partition $29$ minutes into $10$ parts, that we change the speed every $174$ seconds (we change it 10 times including the starting velocity). Now we just need to find a combination such that
$$
(x_1k_1+\ldots +x_nk_n)=64
$$
holds, which works for $x_1=8,k_1=6$ and $x_2=2,k_2=8$. After all this means, that we start with $6$mph and stay $8*174=1392$ seconds at this speed and then change it instantly to $8$ mph and stay like this for the remaining $2*174=348$ seconds which will give us an average speed of $6.4$mph.


text:
Q: Strategies to denest nested radicals $\sqrt{a+b\sqrt{c}}$ I have recently read some passage about nested radicals, I'm deeply impressed by them. Simple nested radicals $\sqrt{2+\sqrt{2}}$,$\sqrt{3-2\sqrt{2}}$ which the later can be denested into $1-\sqrt{2}$. This may be able to see through easily, but how can we denest such a complicated one $\sqrt{61-24\sqrt{5}}(=4-3\sqrt{5})$? And Is there any ways to judge if a radical in $\sqrt{a+b\sqrt{c}}$ form can be denested?
Mr. Srinivasa Ramanujan even suggested some CRAZY nested radicals such as:
$$\sqrt[3]{\sqrt{2}-1},\sqrt{\sqrt[3]{28}-\sqrt[3]{27}},\sqrt{\sqrt[3]{5}-\sqrt[3]{4}},
\sqrt[3]{\cos{\frac{2\pi}{7}}}+\sqrt[3]{\cos{\frac{4\pi}{7}}}+\sqrt[3]{\cos{\frac{8\pi}{7}}},\sqrt[6]{7\sqrt[3]{20}-19},...$$
Amazing, these all can be denested. I believe there must be some strategies to denest them, but I don't know how.
I'm a just a beginner, can anyone give me some ideas? Thank you.

A: One way of approaching this problem is by viewing it as a zero of an equation. Let me explain. Let's say you want to compute $\sqrt{x_0}$ where $x_0$ is a zero of some quadratic polynomial of the form $x^2-bx+1$. Now, one way to go is to note that if you have a zero of $x^2+ax+1$, then it will still be a zero if you multiply it with $x^2-ax+1$ which equals
$$x^4 + (2-a^2) x^2 + 1$$
Now the idea is to work backwards. So, in particular, if you can find you can find an $a$ such that $b=a^2-2$, then you can conclude that the square root of you polynomial is equal to one of the zeros of the polynomials $x^2-ax+1$ or $x^2+ax+1$. It is usually not too hard to find out which. If you found out which, you can rewrite your square root accordingly to the desired form :)
To conclude, one of the tricks is to find the right form of your polynomials such that you end up with something useful. This method will however require some puzzling.
Edit applying this method to the example $\sqrt{5+2\sqrt{6}}$, you will find that the polynomial you need (thus the one for which you want to calculate the square root of a zero) is $x^2-10x+1$. Then according to the above method (which you derive on the go), your $a=\sqrt{12}$ and then you just need to solve $x^2-ax+1=0$ which is the only possibility since for the other one, filling in a positive number will yield a positive number. Solving this equation by completing the square is not too difficult. It turns out that the zeros lie at around 0.5 and 3. Hence, it is not difficult to note you need the larger zero which turns out to be exactly given by $\sqrt{2}+\sqrt{3}$. Does that make sense?

A: There do exist general denesting algorithms employing Galois theory, but for the simple case of quadratic algebraic numbers we can employ a simple rule that I discovered as a teenager.

Simple Denesting Rule $\rm \ \ \color{blue}{subtract\ out}\ \sqrt{norm}\:,\ \ then\ \  \color{brown}{divide\ out}\ \sqrt{trace} $
Recall $\rm\: w = a + b\sqrt{n}\: $ has norm $\rm =\: w\:\cdot\: w' = (a + b\sqrt{n})\ \cdot\: (a - b\sqrt{n})\ =\: a^2 - n\, b^2 $
and, $ $ furthermore,  $\rm\ w\:$ has $ $ trace $\rm\: =\: w+w' =  (a + b\sqrt{n}) + (a - b\sqrt{n})\: =\:  2a$

Here $\:61-24\sqrt{5}\:$ has norm $= 29^2.\:$ $\rm\, \color{blue}{subtracting\ out}\ \sqrt{norm}\ = 29\ $ yields $\  32-24\sqrt{5}\:$
and this has $\rm\ \sqrt{trace}\: =\: 8,\ \ thus,\ \  \ \color{brown}{dividing \ it \ out}\, $ of this yields the sqrt: $\,\pm( 4\,-\,3\sqrt{5}).$

See here for a simple proof of the rule,  and see here for many examples of its use.

A: There is also another radical identity, which generalises $\sqrt{a+\sqrt b}$ even further: \begin{align*}\sqrt{a\pm \sqrt{b+\sqrt{c}}}&= \frac{1}{\sqrt{2}}\left\{\sqrt{a^2+\sqrt{\frac{a^2-b+\sqrt{(a^2-b)^2-c}}{2}}-\sqrt{\frac{a^2-b-\sqrt{(a^2-b)^2-c}}{2}}}\right. \nonumber\\&\quad\left.\pm\,\sqrt{a^2-\sqrt{\frac{a^2-b+\sqrt{(a^2-b)^2-c}}{2}}+\sqrt{\frac{a^2-b-\sqrt{(a^2-b)^2-c}}{2}}}\right\}\end{align*} such that the $\pm$ signs are not independent of each other.
We also have:
If $a^2+b^2=c^2$, then $$(a+b-c)^2=2(c-a)(c-b).$$ Therefore, by letting $a=\sqrt x$ and $b=\sqrt{c^2-x}$, it follows for all $c$ and $x$ such that $c\in \mathbb{R}\setminus \big({-\sqrt x}, \sqrt x\big)$, $$\sqrt{2\big(c-\sqrt x\big)\big(c-\sqrt{c^2-x}\big)}=\sqrt x + \sqrt{c^2-x} -c.$$ Interestingly, given that $$(a+x)^2+(b+y)^2-(a+y)^2-(b+x)^2=2(a-b)(x-y)$$ then if $a^2+b^2=c^2$, we also have $$(a+b-c)^2=(2c)^2+(a+b)^2-(b+c)^2-(a+c)^2.$$ Through one of Ramanujan's classic identities, $$\big\{\sqrt [3]{(a+b)^2}-\sqrt [3]{a^2-ab+b^2}\big\}^3=3\big(\sqrt [3]{a^3+b^3}-a\big)\big(\sqrt [3]{a^3+b^3}-b\big)$$ it can be found that if $a^3+b^3=c^3$, then $$(a+b-c)^3=3(a+b)(c-a)(c-b)$$
Therefore, again, for all $c$ and $x$ such that $c\in\mathbb{R}\setminus ({-\sqrt [3] x}, \sqrt [3] x)$, it follows
$$\sqrt [3]{3\big(\sqrt [3] x+\sqrt [3]{c^3-x}\big)\big(c-\sqrt [3] x\big)\big(c-\sqrt [3]{c^3-x}\big)}=\sqrt [3] x + \sqrt [3]{c^3-x}-c.$$ Unfortunately, due to Fermat's Last Theorem, there are no positive integer solutions for unique $a$, $b$ and $c$.

Try such substitutions yourself on the following one! :)
If $a^4+b^4=c^4$, then $$(a+b-c)^4=6(ab-ac-bc)^2-4\big\{a^3(c-b)+b^3(c-a)+c^3(a+b)\big\}$$

A: There are the following identities.
$$\sqrt{a+\sqrt{b}}=\sqrt{\frac{a+\sqrt{a^2-b}}{2}}+\sqrt{\frac{a-\sqrt{a^2-b}}{2}}$$ and
$$\sqrt{a-\sqrt{b}}=\sqrt{\frac{a+\sqrt{a^2-b}}{2}}-\sqrt{\frac{a-\sqrt{a^2-b}}{2}},$$
where all numbers under radicals are non-negatives.
For example:
$$\sqrt{5+2\sqrt6}=\sqrt{5+\sqrt{24}}=\sqrt{\frac{5+\sqrt{5^2-24}}{2}}+\sqrt{\frac{5-\sqrt{5^2-24}}{2}}=\sqrt3+\sqrt2.$$
This is interesting, when $a$ and $b$ are rationals and $a^2-b$ is a square of a rational number.
The first identity is true because
$$\left(\sqrt{\frac{a+\sqrt{a^2-b}}{2}}+\sqrt{\frac{a-\sqrt{a^2-b}}{2}}\right)^2=$$
$$=\frac{a+\sqrt{a^2-b}}{2}+\frac{a-\sqrt{a^2-b}}{2}+2\sqrt{\frac{a+\sqrt{a^2-b}}{2}}\cdot\sqrt{\frac{a-\sqrt{a^2-b}}{2}}=a+\sqrt{b}.$$

A: You can derive a formula for $\sqrt{a+b\sqrt{c}}$. You will have to assume that $\sqrt{a+b\sqrt{c}}$ can be rewritten as the sum of two surds (radicands). So $$\sqrt{a+b\sqrt{c}}=\sqrt{d}+\sqrt{e}$$
Squaring both sides yields $$a+b\sqrt{c}=d+e+2\sqrt{de}$$
From that, we can see that $a=d+e$ so $e=a-d$ and $b\sqrt{c}=2\sqrt{de}\rightarrow b^{2}c=4de$.
Substituting $e$ with $a-d$ gives $b^{2}c=4d(a-d)$. So $b^{2}c=4ad-4d^{2}$. Rearranging the terms gives us $4d^{2}-4ad+b^{2}c=0$
Using the Quadratic Equation, we have $$d=\frac {a\pm\sqrt{a^{2}-b^{2}c}}{2}$$
And since $a=d+e$, $e$ is the conjugate of $d$. So $e=\frac {a-\sqrt{a^{2}-b^{2}c}}{2}$ and $d=\frac {a+\sqrt{a^{2}-b^{2}c}}{2}.\,$  Thus
$$\sqrt{a+b\sqrt{c}}\,=\, \sqrt{\frac {a+\sqrt{a^{2}-b^{2}c}}{2}} +\sqrt{\frac {a-\sqrt{a^{2}-b^{2}c}}{2}}$$

A: (I will assume $b$ is not a square, since otherwise it would not be a nested radical.)
A nested radical can be denested if and only if there exist $u,v\in\mathbb{N}$ such that the nested radical is of the form $\sqrt{u^2+v\pm2u\sqrt{v}}$ in which case it is also equal to $|u\pm\sqrt{v}|$.
It's not hard to show that those expressions are equal, which means that all nested radicals of that form can indeed be denested.
For the other way, let's consider the following equality where $a,b,c,d,e\in\mathbb{N}$:
$$\sqrt{a\pm\sqrt{b}}=c\pm d\sqrt{e}$$
(Note that we can also write e.g. $\sqrt{3-2\sqrt{2}}$ in that form as $\sqrt{3-\sqrt{8}}$) If we square both sides, we get:
$$a\pm\sqrt{b}=c^2+ed^2\pm2cd\sqrt{e}$$
This suggests we pick $u=c$ and $v=ed^2$. Then $a\pm\sqrt{b}=u^2+v\pm2u\sqrt{v}$ as claimed.
This isn't quite the end of the story since preferably we'd also like to know that $a$ actually corresponds to $u^2+v$ and $b$ to $4u^2v$, i.e. that you can't have two equal nested radicals of different forms. Depending on how deep you want to go, you can either take that for granted for now or observe that $a\pm\sqrt{b}$ satisfies the polynomial relations $(x-a)^2-b=0$ and $(x-u^2-v)^2-4u^2v=0$ and it follows from that that the two polynomials must be equal (using e.g. the concept of minimal polynomials or explicitly dividing the one by the other with remainder taking into account that $a\pm\sqrt{b}$ will satisfy no linear relation) which gives us our correspondence.


text:
Q: Count how many cell string values in a column are found in an table-like database Spreadsheet's structure:

*

*A phrases bank in range B4:J24 in tab phrases bank (Row 4 is for headers). Let's call it bank range.

*A list of phrases in range J4:J in tab phrases. (Row 4 is for headers). Let's call it phases range.

Goal:
Check how many phrases in phases range are found in bank range.
Failed attempt:
=DCOUNTA(phrases!J4:J,1,B4:J24)

* found in phrases bank tab.
It returns all phrases in phases range.

A: For total Found
=arrayformula(sum(COUNTIF(B5:J24,phrases!J4:J)))

For Each Found
=arrayformula(COUNTIF(B5:J24,phrases!J4:J))


text:
Q: Run Windows Explorer beside my application with a specified Bounds I have this:
ShellExecute(Application.Handle, nil, PWideChar('explorer.exe'), PWideChar(ImagesDir), nil, SW_SHOWNORMAL);

where the variable ImagesDir is the directory of Images that I want to show by the Windows Explorer...
How can I run the Windows Explorer beside my application at a specified Bounds, for exemple like this?

A: when you open any File Explorer window (such as going to C:\ ), File Explorer has a specific saved window size that it opens with. So when you resize it, either horizontally and/or vertically, close it and re-open it again, it saves the size of the window, and the location within the Registry where this information is saved is this:
On my system, HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell\WinPos1366x768x96(1)..position, where position is left, right, top or bottom, gives the position of the window border in pixels.
I assume the name of the key depends on the screen resolution.here
and the code will be like that:
.....
const
   AMainKey = '\Software\Classes\Local
   Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell\';

var
  FrmMain: TFrmMain;
  ImagesDir: string;
  AWinPos_left, AWinPos_Top,
  AWinPos_Right, AWinPos_Bottom: string;

implementation
  Uses
    ShellApi, Registry;
  {$R *.dfm}

procedure ExploreDir_With_Bounds(AFile_Dir: string;ALeft, ATop, AWidth, AHieght: DWORD);
  FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
  BEGIN
    Result :=(ShellExecute(GetDesktopWindow,'open',PWideChar(Dir),'','',SW_SHOW)>32)
  END;
var
  ListNames, ListPosition: TStringList;
  I, AScreen_Width, AScreen_Hieght, APixelPI: Integer;
  AWinPos_Uses: string;
begin
  ListNames    := TStringList.Create;
  ListPosition := TStringList.Create;
  With TRegistry.Create Do
  Try
    RootKey := HKEY_CURRENT_USER;
    OpenKey(AMainKey,FALSE);
    GetValueNames(ListNames);

    AScreen_Width  := Screen.Width;
    AScreen_Hieght := Screen.Height;
    APixelPI := Screen.PixelsPerInch;
    AWinPos_Uses := 'WinPos'+AScreen_Width.ToString+'x'+AScreen_Hieght.ToString+'x'+APixelPI.ToString;

    for I := 0 to ListNames.Count - 1 do
    begin
      if Pos(AWinPos_Uses, ListNames[I]) <> 0 then
      begin
        ListPosition.Add(ListNames[I]);
      end;
    end;

    for I := 0 to ListPosition.Count - 1 do
    begin
      if (Pos('left', ListPosition[I]) <> 0) then
      begin
        AWinPos_left := ListPosition[I];
        Lbl_Left.Caption := AWinPos_left;
        Continue;
      end else
      if (Pos('top', ListPosition[I]) <> 0) then
      begin
        AWinPos_Top := ListPosition[I];
        Lbl_Top.Caption := AWinPos_Top;
        Continue;
      end else
      if (Pos('right', ListPosition[I]) <> 0) then
      begin
        AWinPos_Right := ListPosition[I];
        Lbl_Right.Caption := AWinPos_Right;
        Continue;
      end else
      if (Pos('bottom', ListPosition[I]) <> 0) then
      begin
        AWinPos_Bottom := ListPosition[I];
        Lbl_Bottom.Caption := AWinPos_Bottom;
      end;
    end;

    if (AWinPos_left <> '')and(AWinPos_Top <> '')and
      (AWinPos_Right <> '')and(AWinPos_Bottom <> '') then
    begin
      WriteInteger(AWinPos_left, ALeft);
      WriteInteger(AWinPos_Top, ATop);
      WriteInteger(AWinPos_Right, ALeft + AWidth);
      WriteInteger(AWinPos_Bottom, ATop + AHieght);
    end;

    CloseKey;
  Finally
    Free;
    ListNames.Free;
    ListPosition.Free;
  End;

  ExploreDirectory(AFile_Dir);
end;

procedure TFrmMain.FormCreate(Sender: TObject);
begin
  ImagesDir := TDirectory.GetParent(TDirectory.GetParent(ExtractFileDir(ParamStr(0))))+ '\My Images To Test';

  ExploreDir_With_Bounds(ImagesDir, (50 + Width)+10{Left}, 50{TOP},
                         Screen.Width - (Left + Width +20){width},
                         Screen.Height - 150{hieght});
end;

procedure TFrmMain.FormShow(Sender: TObject);
begin
  Left := 0;
  Top  := (Screen.WorkAreaHeight div 2)-(Height div 2);
end;

end.

the Result here

A: You can use the following function to open an explorer window and have it point to a specific directory.
USES Windows,ShellAPI;

FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
  BEGIN
    Result:=(ShellExecute(GetDesktopWindow,'open',PChar(Dir),'','',SW_SHOW)>32)
  END;

Note, however, that you can't (with this code) make the Explorer window "follow" your program, ie. the opened window is a completely autonomous window that has no link to your program, just as if the user had browsed to the directory himself. If you call this function again with a new directory, Explorer will open a new window with that directory (and keep the old one opened).
UPDATE:
If you want to be able to manipulate the explorer window after it is opened, you need to use the various interfaces that Explorer exposes. I have made a UNIT that allows you to do what you seek as well as returning the interface needed to be able to manipulate the window afterwards. It is heavily based on the code found in this answer:
Check if windows explorer already opened on given path
by Victoria
UNIT WindowsExplorer;

INTERFACE

USES Types,ShDocVw;

FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
FUNCTION OpenFolder(CONST Dir : STRING) : IWebBrowserApp; OVERLOAD;
FUNCTION OpenFolderAt(CONST Dir : STRING ; Left,Top,Width,Height : INTEGER) : IWebBrowserApp; OVERLOAD;
FUNCTION OpenFolderAt(CONST Dir : STRING ; CONST Rect : TRect) : IWebBrowserApp; OVERLOAD; INLINE;

IMPLEMENTATION

USES Windows,Variants,ShlObj,Ole2,OleAuto,ShellAPI,ActiveX,SysUtils;

FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
  BEGIN
    Result:=(ShellExecute(GetDesktopWindow,'open',PChar(Dir),'','',SW_SHOW)>32)
  END;

FUNCTION GetFolderIDList(CONST Dir : STRING) : PItemIDList;
  VAR
    ShellFolder : IShellFolder;
    Attributes  : ULONG;
    Count       : ULONG;

  BEGIN
    OleCheck(SHGetDesktopFolder(ShellFolder));
    Attributes:=SFGAO_FOLDER or SFGAO_STREAM;
    OleCheck(ShellFolder.ParseDisplayName(0,NIL,PWideChar(WideString(Dir)),Count,Result,Attributes));
    IF NOT ((Attributes AND SFGAO_FOLDER=SFGAO_FOLDER) AND (Attributes AND SFGAO_STREAM<>SFGAO_STREAM)) THEN BEGIN
      CoTaskMemFree(Result);
      Result:=NIL
    END
  END;

FUNCTION OpenFolder(CONST Dir : STRING ; OpenIfNotFound : BOOLEAN) : IWebBrowserApp; OVERLOAD;
  CONST
    IID_IServiceProvider: System.TGUID = '{6D5140C1-7436-11CE-8034-00AA006009FA}';

  VAR
    FolderID        : PItemIDList;
    ShellWindows    : IShellWindows;
    I               : INTEGER;
    WndIFace        : System.IDispatch;
    WebBrowserApp   : IWebBrowserApp;
    ServiceProvider : IServiceProvider;
    ShellBrowser    : IShellBrowser;
    ShellView       : IShellView;
    FolderView      : IFolderView;
    PersistFolder   : IPersistFolder2;
    CurFolderID     : PItemIDList;

  BEGIN
    FolderID:=GetFolderIDList(Dir);
    IF Assigned(FolderID) THEN TRY
      OleCheck(CoCreateInstance(CLASS_ShellWindows,NIL,CLSCTX_LOCAL_SERVER,IID_IShellWindows,ShellWindows));
      FOR I:=0 TO PRED(ShellWindows.Count) DO BEGIN
        WndIface:=ShellWindows.Item(VarAsType(I,VT_I4));
        IF Assigned(WndIface) AND
           Succeeded(WndIface.QueryInterface(IID_IWebBrowserApp,WebBrowserApp)) AND
           Succeeded(WebBrowserApp.QueryInterface(IID_IServiceProvider,ServiceProvider)) AND
           Succeeded(ServiceProvider.QueryService(SID_STopLevelBrowser,IID_IShellBrowser,ShellBrowser)) AND
           Succeeded(ShellBrowser.QueryActiveShellView(ShellView)) AND
           Succeeded(ShellView.QueryInterface(IID_IFolderView,FolderView)) AND
           Succeeded(FolderView.GetFolder(IID_IPersistFolder2,PersistFolder)) AND
           Succeeded(PersistFolder.GetCurFolder(CurFolderID)) AND
           ILIsEqual(FolderID,CurFolderID) THEN BEGIN
          IF IsIconic(WebBrowserApp.HWnd) THEN Win32Check(ShowWindow(WebBrowserApp.HWnd,SW_RESTORE));
          Win32Check(SetForegroundWindow(WebBrowserApp.HWnd));
          Exit(WebBrowserApp)
        END
      END
    FINALLY
      CoTaskMemFree(FolderID)
    END;
    Result:=NIL;
    IF OpenIfNotFound THEN BEGIN
      IF NOT ExploreDirectory(Dir) THEN EXIT;
      FOR I:=1 TO 20 DO BEGIN
        Result:=OpenFolder(Dir,FALSE);
        IF Assigned(Result) THEN EXIT;
        Sleep(100)
      END
    END
  END;

FUNCTION OpenFolder(CONST Dir : STRING) : IWebBrowserApp;
  BEGIN
    Result:=OpenFolder(Dir,TRUE)
  END;

FUNCTION OpenFolderAt(CONST Dir : STRING ; Left,Top,Width,Height : INTEGER) : IWebBrowserApp;
  BEGIN
    Result:=OpenFolder(Dir);
    IF Assigned(Result) THEN BEGIN
      Result.Left:=Left; Result.Top:=Top; Result.Width:=Width; Result.Height:=Height
    END
  END;

FUNCTION OpenFolderAt(CONST Dir : STRING ; CONST Rect : TRect) : IWebBrowserApp;
  BEGIN
    Result:=OpenFolderAt(Dir,Rect.Left,Rect.Top,Rect.Width,Rect.Height)
  END;

END.

It is made for use with Delphi Tokyo 10.2.3 so if you use an earlier version (you didn't specify Delphi version in your question), you may need to adapt the USES list to match.


text:
Q: How can I make a header file appear on every new project I'm very new to programming so hopefully I don't sound too dumb. I'm using visual studios to learn on and reading Bjarne Stroustrup's book "Programming Principles and Practice Using C++" and the book uses a header file called "std_lib_facilities.h" for every example. I've been copying the file into every single program manually and its getting kind of tedious. Is there any way to setup visual studios to were when I create a new project the header file will just automatically be there?

A: Yes, There is a way to add automatically the additional libraries and header files into every project you create.
Navigate the window into MSBulid\v4.0 by using the below command in run window
%localappdata%\Microsoft\MSBuild\v4.0
Then you can find the Microsoft.Cpp.Win32.User.props
Right click the Microsoft.Cpp.Win32.User.props  and open with notepad or notepad++
<ImportGroup Label="Property sheets"/>
    <PropertyGroup>
        <IncludePath> header file path </IncludePath>
    <LibraryPath> library Path </LibraryPath>
</PropertyGroup>

Add the above code in Microsoft.Cpp.Win32.User.props inside  tag.
And save the Microsoft.Cpp.Win32.User.props
Open the Visual Code in Admin
Have a nice day :)


text:
Q: How can I securely detect SSL in CakePHP behind an nginx reverse proxy? CakePHP (all versions that I've seen) check against $_SERVER['HTTPS'] to see whether a request has been made over HTTPS instead of plain HTTP.
I'm using nginx as a load balancer, behind which are the Apache application servers. Since the SSL connection terminates at the load balancer, $_SERVER['HTTPS'] is not set as far as CakePHP is concerned.
I'd like to find a secure way to detect HTTPS on the app servers.
So far, I've put this into my CakePHP configuration:
$request_headers = getallheaders();
if ( (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) || ( isset($request_headers['X-Forwarded-Proto']) && $request_headers['X-Forwarded-Proto'] == 'https' ) ) {

    $ssl = true;

    // overwrite environment vars (ugly) since CakePHP won't honour X-Forwarded-Proto
    $_SERVER['HTTPS'] = 'on';
    $_ENV['HTTPS'] = 'on';

} else {
    $ssl = false;
}

And then in the nginx configuration, I've used proxy_set_header X-Forwarded-Proto https; to add the flag to any requests between the load balancer and the back-end application servers.
This works perfectly fine, but anyone making a direct request to the app servers could fool them into thinking they are browsing over SSL when they're not. I'm not sure whether this is a security risk, but it doesn't seem like a good idea.
Is it a security risk? What's the better solution?
Since using X-Forwarded-Proto seems like something of a standard, the solution may be a good patch to be submitted to the CakePHP core, so I think any answer can legitimately involve editing core files too.

A: Add a request detector
Do not edit the core. If your intention is to submit a patch, don't rely on your patch until after it's accepted - Otherwise you're on a road to divergence and maintaining your own fork of CakePHP.
Once you determine your exact implementation logic you can use a request detector to honor it.
for example:
//AppController::beforeFilter
public function beforeFilter() {
    $this->request->addDetector('ssl', array(
        'env' => 'HTTP_X_FORWARDED_PROTO',
        'value' => 'https'
    ));
}

After this, your custom header will correctly be identified by cake as an ssl request.
Note that the keys of the $_SERVER global are normalized as all caps and underscore delimited i.e.:
$ curl --header "X-Forwarded-Proto:https" http:://yoursite.com

Will populate $_SERVER['HTTP_X_FORWARDED_PROTO'] - as such this is the key to check for.
Account for (in)security
Yes, it's something you should take care of - either disable direct
access to your webservers so that only via the ip of the loadbalancer will it respond at all; or modify your detector so that it does not return true for direct-access requests
irrespective of the value of the X-Forwarded-Proto header - as shown in the documentation you can use a callback to perform whatever logic required rather than simply testing the values of some environment variable.

A: mod_rpaf will let you do this.
This sets the HTTPS value in Apache to "on" based on the headers sent by nginx so Cake will work out of the box (as well as any other apps run in Apache).
It also corrects the values for REMOTE_ADDR, SERVER_PORT and HTTP_HOST.
Here is my example config:
<IfModule mod_rpaf.c>
    RPAF_Enable       On
    RPAF_ProxyIPs     127.0.0.1 10.0.0.0/24
    RPAF_SetHostName  On
    RPAF_SetHTTPS     On
    RPAF_SetPort      On
</IfModule>

# If mod_rewrite redirects then we lose the HTTPS status to REDIRECT_HTTPS.
# This resets it back. This happens with Cake's front controller
<IfModule setenvif_module>
    SetEnvIf REDIRECT_HTTPS on HTTPS=on
</IfModule>

A: I found the comment of AD7six - override the redirect() function - extremely helpful in my SSL-only setup since my app had some redirects going to http.
I just added the following to AppController.php so the redirect function always uses https:
function redirect($url, $status = NULL, $exit = true) {
    return parent::redirect(str_replace('http://', 'https://', Router::url($url, true)));
}


text:
Q: Searching for list of terms using Google in order to build a bag-of-words for a particular category I am having a hard time understanding the process of building a bag-of-words. This will be a multiclass classification supervised machine learning problem wherein a webpage or a piece of text is assigned to one category from multiple pre-defined categories. Now the method that I am familiar with when building a bag of words for a specific category (for example, 'Math') is to collect a lot of webpages that are related to Math. From there, I would perform some data processing (such as remove stop words and performing TF-IDF) to obtain the bag-of-words for the category 'Math'.
Question: Another method that I am thinking of is to instead search in google for something like 'List of terms related to Math' to build my bag-of-words. I would like to ask if this is method is okay?
Another question: In the context of this question, does bag-of-words and corpus mean the same thing?

A: To answer the second question first, they are not. A corpus is simply a set of documents. The bag of words assumption means, loosely, that the order of words in a document doesn't matter. It's applied in many language models, just about any that disregards grammar but maintains a count of words used.
To your primary question, I think you're interested in deriving predictive features for a particular class, and asking whether you can do that manually. (This seems to be how you're using the term "bag of words.") In principle sure, you could come up with a list of terms related to math or neurobiology and use those as features in a learning algorithm.
But there are methods like supervised topic models to do that for you, though the only implementation I'm aware of is an academic one written in C++. This would be a more principled way of deriving what you're interested in, and would save you a thousand Google searches.


text:
Q: C# Web API - POST Request doesn't get executed I am trying to send a POST request from my ASP.NET Core Web API Project but the request is never sent. The method gets executed with no errors but the request never gets sent out from the async method.
My Implementation:
public async void notify(String message)
{
    String url = "MY_WEBSERVICE_URL";
    var client = new HttpClient();
    client.BaseAddress = new Uri(url);
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
    request.Content = new StringContent("application/x-www-form-urlencoded;charset=UTF-8",
    Encoding.UTF8, "application/json");

    Byte[] byteArray = Encoding.UTF8.GetBytes("{\"text\":\"" + message + "\"}");
    request.Content.Headers.ContentLength = byteArray.Length;

    await client.SendAsync(request).ContinueWith(responseTask =>
    {
       Console.WriteLine("Response: {0}", responseTask.Result);
    });
}

Is this the proper way of making a POST request from a Core Web API project? Thank you in advance

A: First of all, there is a dedicated method PostAsync in the HttpClient class ( or even PostAsJsonAsync extension) which you can use to send POST requests without creating HttpRequstMessage manually.
Now about your code - I believe you want to post following JSON string:
{"text":"someMessage"}

You should set this string as a content of StringContent which you are sending:
var json = "{\"text\":\"" + message + "\"}";
request.Content = new StringContent(json, Encoding.UTF8, "application/json");

Currently you are trying to post mediatype string as a value to your API endpoint. Of course it cannot be deserialized into your model.
Note1: StringContent will automatically add Content-Length header with the appropriate value. You should not do that manually.
Note2: Unless this is an event handler, you should not use async void - use async Task instead.

Same task with PostAsJsonAsync usage will look like:
public async Task Notify(string message)
{
   var string url = "MY_WEBSERVICE_URL";
   var client = new HttpClient();
   client.BaseAddress = new Uri(url);
   var notification = new Notification { Text = message }; // use some model class
   var resonse = await client.PostAsJsonAsync("relativeAddress", notification);
   if (response.IsSuccessStatusCode)
   {
       var content = await response.Content.ReadAsStringAsync();
   }
}

In this case, your model will be automatically serialized into JSON, appropriate content will be created and POST request will be sent.

A: Try Adding [IgnoreAntiforgeryToken] on top of the Post Action like this


text:
Q: Playing an image sequence in WPF at 120FPS I'm trying to create a program that takes an image sequence and plays it at the desired framerate (up to 120 FPS).
So far, I have a class that the Source of an Image control is bound to. This class stores a list of file locations and can recall the file location of the next frame. It looks like this:
public class VideoViewer : INotifyPropertyChanged
{
    private string image;
    private List<string> imageLocs = new List<string>();
    private int imageIndex = 0;

    public event PropertyChangedEventHandler PropertyChanged;

    public string imageSource
    {
        get
        {
            return image;
        }
        set
        {
            image = value;
            OnPropertyChanged("imageSource");
        }
    }

    public List<string> imagesArray
    {
        get
        {
            return imageLocs;
        }
        set
        {
            imageLocs = value;
            OnPropertyChanged("imagesArray");
        }
    }

    public void NextFrame()
    {
        //If not on last frame
        if(imageIndex < (imageLocs.Count - 1))
        {
            //Add one to the index to select the next frame in the array
            imageIndex += 1;
            imageSource = imagesArray[imageIndex];

            //Update the image
            OnPropertyChanged("imageSource");
        }
        //If on the last frame of the array, reset to 0
        else if(imageIndex == (imageLocs.Count - 1))
        {
            imageIndex = 0;
            imageSource = imagesArray[imageIndex];
            OnPropertyChanged("imageSource");
        }
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

In my MainWindow I have 3 buttons, a browse button which loads the class, a play button that starts a DispatcherTimer which calls the NextFrame() method of my class every 1/120 seconds, and a stop button that stops the timer.
public partial class MainWindow : Window
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    VideoViewer vV = new VideoViewer();
    DispatcherTimer timer = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = vV;
    }

    private void PlayButton_Click(object sender, RoutedEventArgs e)
    {
        timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1/120) };
        timer.Tick += TimerTick;
        timer.Start();
    }

    private void PauseButton_Click(object sender, RoutedEventArgs e)
    {
        timer.Stop();
    }

    private void TimerTick(object sender, EventArgs e)
    {
        vV.NextFrame();
    }

    private void BrowseButton_Click(object sender, RoutedEventArgs e)
    {
        // Set the file dialog to filter for graphics files.
        this.openFileDialog1.Filter =
            "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|" +
            "All files (*.*)|*.*";

        // Allow the user to select multiple images.
        this.openFileDialog1.Multiselect = true;
        this.openFileDialog1.Title = "My Image Browser";

        DialogResult dr = this.openFileDialog1.ShowDialog();
        if (dr == System.Windows.Forms.DialogResult.OK)
        {
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                List<string> images = new List<string>();

                // Read the files
                foreach (String file in openFileDialog1.FileNames)
                {
                    images.Add(file);
                }

                vV.imagesArray = images;
            }
        }
    }
}

This works fine at lower framerates, but does not seem to play the video any faster than 30 FPS (for example i would expect a 30 FPS video to play at 4x speed when set to 120 FPS)
Is there something other than a DispatcherTimer I can use to achieve the desired effect?

A: The Interval property of the DispatcherTimer is unfortunately not precise enough.

*

*It will never fire off the "Tick" event any earlier than when the specified Interval is up, but...

*It is very likely that it will take 15-25ms longer than the interval because there is still other stuff to finish.

It might improve slightly if you use...
DispatcherTimer dt = new DispatcherTimer(DispatcherPriority.Send);

...to increase the priority level but nowhere near 120FPS (8.3ms interval).
Maybe this helps a little:
Instead of subscribing to the "Tick" event of a DispatcherTimer you can subscribe to...
System.Windows.Media.CompositionTarget.Rendering += DoSomething;

...and at least get the events fired at a pretty reliable 60FPS on a modern PC.


text:
Q: Create a .jar from a JavaFX file Maven with all java dependencies I am trying to compile a Jave project using maven into a single executable .jar but am recieveing one of two errors:
no main manifest attribute, in csci6461-1.0-SNAPSHOT.jar

or one pertaining to JavaFX
Error: JavaFX runtime components are missing, and are required to run this application

I need the file to be able to be ran directly by the user, what is the best way to approach this?
This is my pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.csci6461</groupId>
    <artifactId>csci6461</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>CSCI6461</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>5.8.0</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>17.0.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>17.0.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.codeartisans.javafx</groupId>
            <artifactId>javafx-maven-plugin</artifactId>
            <version>1.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.codeartisans.javafx</groupId>
            <artifactId>javafx-deployer-maven-plugin</artifactId>
            <version>1.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>16</source>
                    <target>16</target>
                </configuration>
            </plugin>

            <!-- Skip the tests run. -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.15</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>

            <!-- Sources generation -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.csci6461.ComputerSimulation</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id> <!-- this is used for inheritance merges -->
                        <phase>package</phase> <!-- bind to the packaging phase -->
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

I have also tried using an Ant build but the latter of the two errors still persist.


text:
Q: How to fix the binomial formula for a specific application/bounds difference I am trying to find a short form of the long sum
$$ \sum_{k=1}^{n-1} (-4)^k \binom{n}{n-k} 3^{n-k} $$,
which I can map somewhat awkwardly to the binomial formula $$ \sum_{k=0}^{n} \binom{n}{k} x^k y^{n-k} = (x+y)^n $$ by changing the bounds, getting $$\sum_{k=0}^{n} \binom{n}{k} (-4)^k * 3^{n-k} = (-4+3)^n = (-1)^n$$
How can I also accurately account for the fact that the original summation starts at $k=1$ and ends at $n-1$, and not $k=0$ and $n$?


text:
Q: C++ Return Auto Array Visual Studio shows me a error on auto**. Why?
My code:
auto** getMetaInfo(SQLHANDLE sqlStmtHandle)

{
    SQLCHAR colName[256];
    SQLSMALLINT colNameLen;
    SQLSMALLINT dataType;
    SQLSMALLINT numDecimalDigits;
    SQLSMALLINT allowsNullValues;
    SQLUINTEGER columnSize;
    SQLSMALLINT columns = getrows();
    auto retArray = new SQLCHAR[columns][2]();
    for (int i = 1; i <= columns; i++)
    {
        SQLRETURN  retCode = SQLDescribeColA(sqlStmtHandle, i, colName, 255,     &colNameLen, &dataType, &columnSize, &numDecimalDigits, &allowsNullValues);
        retArray[i][0] = dataType;
        retArray[i][1] = *colName;
    }
}

A: Compiler is unable to deduce the return type (note that 2D array is not a double pointer, see this answer for example). Put auto instead of auto**, add a return statement and it should work.


text:
Q: Adding Class Library Reference to WCF Service Library I'm working on my first web service, and I'm having trouble referencing another class library I have in my solution inside of my web service. Here is that service:
using MyDomain;

namespace WebServices
{
    public class AutomatedLogin : IAutomatedLogin
    {
        public Guid GetToken(string email)
        {
            //Code goes here
        }
    }
}

When I add a reference to MyDomain inside my WCF Service Library, intellisense recognizes the reference, but when I rebuild my solution, the compiler throws the following error:

The type or namespace name 'MyDomain' could not be found (are you missing a using directive or an assembly reference?)

Can anyone tell me why the compiler is ignoring the MyDomain reference when I try to rebuild my solution?

A: I was able to find a similar question:
WCF service library project can't find reference to other project
I changed the project's target framework from .NET Framework 4 Client Profile to .NET Framework 4 which seems to have fixed the compiling issue.


text:
Q: Two images with movement I am doing a personal project and now I have thought of placing two ships, one ship would have to be bouncing (ship2.png) without me controlling it and the other ship would have to handle it with the arrows on the keyboard (ship.png).
The problem is that when I want to add the image "ship2.png" it seems to be overwritten and no longer places the image "ship.png".
I have already loaded the image in the section this.loadImages = function()
The problem is in this part:  object.ship = new spaceship(200, 100,object.images["ship"]); if I add "ship2" it overwrites and no longer shows me "ship".


text:
Q: SQLAlchemy Misuse Causing Memory Leak? My program is sucking up a meg every few seconds. I read that python doesn't see curors in garbage collection, so I have a feeling that I might be doing something wrong with my use of pydbc and sqlalchemy and maybe not closing something somwhere?
#Set up SQL Connection
def connect():
        conn_string = 'DRIVER={FreeTDS};Server=...;Database=...;UID=...;PWD=...'
        return pyodbc.connect(conn_string)

metadata = MetaData()
e = create_engine('mssql://', creator=connect)
c = e.connect()
metadata.bind = c
log_table = Table('Log', metadata, autoload=True)

...
atexit.register(cleanup)
#Core Loop
line_c = 0
inserts = []
insert_size = 2000
while True:
        #line = sys.stdin.readline()
        line = reader.readline()
        line_c +=1
        m = line_regex.match(line)
        if m:
                fields = m.groupdict()
                ...
                inserts.append(fields)
                if line_c >= insert_size:
                        c.execute(log_table.insert(), inserts)
                        line_c = 0
                        inserts = []

Should I maybe move the metadata block or part of it to the insert block and close the connection each insert?
Edit:
Q: Does it every stabilize?

A: Only if you count Linux blowing away the process :-) (Graph does exclude Buffers/Cache from Memory Usage)

A: I would not necessarily blame SQLAlchemy. It could also be a problem of the underlaying driver. In general memory leaks are hard to detect. In any case you should ask on the SQLALchemy mailing list where the core developer Michael Bayer is responding on almost
every question...perhaps a better chance to get real help there...


text:
Q: Ensuring correct date/time we are creating a location-enabled app where users use this app to record certain events in the field.
The important part of the event data is when an event happened. This is no issue when user is online, but we also support situations when user is offline (by remembering & later syncing events).
There could be situations when users are offline and they change the time on the phone, so that event times are wrongly recorded.
So, what would be the best way to ensure we get a correct time, independent of user actions,  given that device could be offline. Some ideas:

*

*GPS time. Is it possible to acquire it?

*Tracking system time changes made by user?

*Any other idea?

Note: time does need second accuracy, approximately minute accuracy would be ok.
Note2: we are creating mobile apps for Android and iPhone, so I'm interested for generic solutions and also solutions that are specific to any of those two platforms.

A: I, personally, wouldn't worry so much about this scenario. The liklihood of someone intentionally changing the time on their Android (which periodically throughout the day syncs to a time server automatically) while offline seems low to me. That being said, the only way I could see compensating for this is to keep a service running in the background that keeps a running tally of the seconds passed since recording the location data offline. Once uploaded to your servers you could use the elapsed seconds to calculate a time offset from current UTC time. It's an awful lot to go through, but it would work.
GPS time is an interesting idea, but Android allows users of the SDK to send mock locations to their devices. I'm not sure you could reliably track changes to system time either, and even if you could you'd be capturing them after the fact without the current real time as context.

A: We use GPS times in our app for very similar reasons. Since our users are in different time zones and we want local times, we define from our server what time zone they are in at installation time (they don't move very far). Hadn't thought of the mock GPS locations, but you would need to be a fairly advanced user to do that.


text:
Q: is it possible to list all blocked tornado coroutines I have a "gateway" app written in tornado using @tornado.gen.coroutine to transfer information from one handler to another. I'm trying to do some debugging/status testing. What I'd like to be able to do is enumerate all of the currently blocked/waiting coroutines that are live at a given moment. Is this information accessible somewhere in tornado?

A: You talk about ioloop _handlers dict maybe. Try to add this in periodic callback:
def print_current_handlers():
    io_loop = ioloop.IOLoop.current()
    print io_loop._handlers

update: I've checked source code and now think that there is no simple way to trace current running gen.corouitines, A. Jesse Jiryu Davis is right!
But you can trace all "async" calls (yields) from coroutines - each yield from generator go into IOLoop.add_callback (http://www.tornadoweb.org/en/stable/ioloop.html#callbacks-and-timeouts)
So, by examining io_loop._callbacks you can see what yields are in ioloop right now.
Many interesting stuff is here :)  https://github.com/tornadoweb/tornado/blob/master/tornado/gen.py

A: No there isn't, but you could perhaps create your own decorator that wraps gen.coroutine, then updates a data structure when the coroutine begins.
import weakref
import functools

from tornado import gen
from tornado.ioloop import IOLoop

all_coroutines = weakref.WeakKeyDictionary()

def tracked_coroutine(fn):
    coro = gen.coroutine(fn)

    @functools.wraps(coro)
    def start(*args, **kwargs):
        future = coro(*args, **kwargs)
        all_coroutines[future] = str(fn)
        return future

    return start

@tracked_coroutine
def five_second_coroutine():
    yield gen.sleep(5)

@tracked_coroutine
def ten_second_coroutine():
    yield gen.sleep(10)

@gen.coroutine
def tracker():
    while True:
        running = list(all_coroutines.values())
        print(running)
        yield gen.sleep(1)

loop = IOLoop.current()
loop.spawn_callback(tracker)
loop.spawn_callback(five_second_coroutine)
loop.spawn_callback(ten_second_coroutine)
loop.start()

If you run this script for a few seconds you'll see two active coroutines, then one, then none.
Note the warning in the docs about the dictionary changing size, you should catch "RuntimeError" in "tracker" to deal with that problem.
This is a bit complex, you might get all you need much more simply by turning on Tornado's logging and using set_blocking_log_threshold.


text:
Q: 2-variable limit problem I can't solve some limits, and can't find resources online on how to solve this.
I can use double limits (replace X and Y at the same time) or sucessive limits, replacing one each variable separately.
If the limit doesn't exist, I have to show why.
Could someone help me out? Thank you very much!
Problems:
$$\lim_{x\to 0,y\to 0} \frac{3x - 2y}{2x + 3y}$$
$$\lim_{x\to 0,y\to 0} ((x ^ 2 + 2y)  \sin (\frac{1}{xy}))$$

A: If you have access to Mathematica, I find it very useful to look at the graph. Although this problem is very solvable on paper as well.
First problem:
Direct substitution won't work, because it's indeterminate. One method is to let t=x,t=y and find the limit of a single variable, t. This makes the limit (t)/(5t) = 1/5. This is effectively approaching the limit along the line x=y.
To try a different line, let t=-x,t=y (the line y=-x). From this approach, the limit is (-5t)/(t) = -5. Since these values are different, the function approaches a different value from different directions, and the limit does not exist. This method will only work to prove a limit's non-existence. You cannot prove that a limit exists with this methods, only disprove it.
Second Problem:
You can basically use direct substitution, just keep in mind that the sin(anything) must be within [-1,1]. As the values approach zero, the limit's upper and lower bounds also go to zero, so you can effectively use the squeeze/sandwich theorem, and then (0)(-1) <= answer <= (0)(1) and 0 <= answer <= 0

A: First limit does not exist, because if we consider 2 different sequences $(\frac{1}{n},\frac{1}{n})$ and $(\frac{1}{n},\frac{2}{n})$ which both converges to (0,0), then we have
$$\frac{3 \frac{1}{n} - 2\frac{1}{n}}{2\frac{1}{n} + 3\frac{1}{n}} = \frac{1}{5}$$
$$\frac{3 \frac{1}{n} - 2\frac{2}{n}}{2\frac{1}{n} + 3\frac{2}{n}} = -\frac{1}{8}$$
Second one most easy is to estimate:
$$\left | (x ^ 2 + 2y) \sin \left(\frac{1}{xy} \right) \right| \leqslant x^2 + 2|y| \to0, \text{ when } (x,y) \to (0,0)$$


text:
Q: Using Angularjs, How to parse the html elements to get the data model? For example, the html page already have a list of DIV containing some profile information such as address (including geo info), phone, and etc. I want to use angularjs to read/parse this information to generate data models and use them for other purpose such as showing on the map.
I am quite new to angularjs, so not sure if this can be done easily.
The purpose of doing this is for better search engine optimization. If using a html template and using angularjs to do the bind, such  data can not be indexed by the search engine.

A: Use data binding in angular JS..
For eg: http://plnkr.co/edit/c6MQ0pwMkxGXXqkJ4FXl?p=preview
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

Todo

{{remaining()}} of {{todos.length}} remaining
[ archive ]

<input type="checkbox" ng-model="todo.done">
{{todo.text}}

<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>

If you look into this you can see a simple example of the interaction between model and view and how the data binding takes place.
For more visit :http://angularjs.org/
And look in to their examples given below.


text:
Q: Database in Flutter which can synced online later on I am trying to create a Flutter app with a Database which is primarily offline on the device. Later on, the user should have the possibility to flip a switch and the database is synced online, so he can log in from a different device and has the same data.
I read a lot about using Firestore, and already implemented it in the app, but the problem is that it is always online and not really made for using it only offline.
I thought about using sqflite, but then I have the synchronization problem and read that the business logic behind a synchronization isn't trivial.
Is there an easy way to do that?


text:
Q: Alter URL using htaccess Need a htaccess redirect code which will insert CAE/index.php/ to the URLs.
The redirect code should check if this snippet is present or not in the URL. Only if it is not present, the code should be inserted.
Eg.
The following URL
http://localhost/dataPage

should be redirected as follows:
http://localhost/EWQ/index.php/dataPage

A: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((?!EWQ/index\.php/).*)$ EWQ/index.php/$1 [L,NC]


text:
Q: Arrange list items in grid What I want to do is to arrange the list items (coming from a binding) in a grid with columns. Here is my code:
<l:Grid
  defaultSpan="L3 M4 S6"
  class="sapUiSmallMarginTop"
>
  <m:List
    mode="None"
    items="{tickets>children}"
  >
    <m:CustomListItem>
      <m:HBox>
        <core:Icon
          size="2rem"
          src="sap-icon://circle-task-2"
          class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom color-green"
          visible="{= ${tickets>status} === 'resolved'}"
          tooltip="{i18n>ticket.status.resolved}"
        />
        <core:Icon
          size="2rem"
          src="sap-icon://circle-task-2"
          class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom color-red"
          visible="{= ${tickets>status} === 'open'}"
          tooltip="{i18n>ticket.status.open}"
        />
        <m:VBox class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom">
          <m:Link
            text="#{tickets>referenceNumber}"
            target="{tickets>id}"
            press="handleChildRecordPress"
          />
          <m:Label text="{
            path: 'tickets>unitID',
            formatter: '.formatUnit'
          }"/>
        </m:VBox>
      </m:HBox>
      <m:layoutData>
        <l:GridData span="L12 M12 S12" />
      </m:layoutData>
    </m:CustomListItem>
  </m:List>
</l:Grid>

But it only shows one item per row and not multiple. How can I display multiple items in a row?
This is how it looks now, what I want is to show like 3 or 4 items in a row (responsive would be nice)

A: UI5 1.60 introduces a new control named sap.f.GridListAPI that combines functionalities of sap.m.ListBase (e.g. growing) with the ability to display list items in a grid layout (display: grid in CSS internally).
<f:GridList xmlns:f="sap.f"
  class="sapUxAPObjectPageSubSectionAlignContent"
  items="..."
>
  <f:customLayout>
    <cssgrid:GridBoxLayout xmlns:cssgrid="sap.ui.layout.cssgrid" boxesPerRowConfig="XL7 L4 M3 S1" />
  </f:customLayout>
  <f:items>
    <!-- m.CustomListItem, m.StandardListItem, etc.. -->
  </f:items>
</f:GridList>

The custom layout GridBoxLayoutAPI enables displaying the grid items in a responsive way, which can be configured via boxPerRowConfig and boxMinWidth properties.

Source: https://ui5.sap.com/#/sample/sap.f.sample.GridListBoxContainer/preview

Note: sap.f.GridList currently has dependencies to sap.m, sap.f, and sap.ui.layout. Add them to the list of dependencies, e.g. in the app descriptor, so that those libraries can be loaded in parallel with other dependent libs asynchronously:
"sap.ui5": {
  "dependencies": {
    "libs": {
      "sap.ui.core": {},
      "sap.m": {},
      "sap.f": {},
      "sap.ui.layout": {}
    }
  }
}

A: I thing what you need is a sap.m.Table not a Grid, neither a List


text:
Q: How do you stop an application event from propagating to another instance of the same component? I'm currently building a native dynamic data table in lightning (not using any 3rd party libraries). For some features of the table to work, I had to use application events because component events won't work since the components firing the events are in different branches than the components handling the events.
While the application events work, if I put another data table component onto the same lightning page, doing any action that relies on application events will also trigger the same action on the other instances of the data table component.
Anyone have any ideas on how to contain the application events?

A: During the event bubble phase, use event.stopPropagation() to cause the component's root to be become the root node for the default phase. This means you'll need a handler at the top-level component to halt propagation beyond that component. See Application Event Propagation. It'll stop processing with the component that fired the event.
<aura:component ...>
<!-- root component -->
<aura:handler includeFacets="true" phase="bubble" name="c:appEvent" handler="{!c.containEvent}" />

// In controller
containEvent: function(component, event, helper) {
    event.stopPropagation();
}

A: Give each table an ID, e.g. just an integer, as a new attribute. In the event, include a field for the ID of the table it is meant for.
Now when the event is fired it will still activate handlers in all the tables. However, at the start of the controller code you can check if the table ID in the event matches the ID of the component currently handling the event. If not, don't continue the handling.


text:
Q: SQL - Select values from a table based on dates using incrementing dates I have a SQL table of dates (MM/DD format), targets, and levels, as such:
Date     Target     Level
10/2     1000       1
10/4     2000       1
10/7     2000       2

I want to use those dates as tiers, or checkpoints, for when to use the respective targets and levels. So, anything on or after those dates (until the next date) would use that target/level. Anything before the first date just uses the values from the first date.
I want to select a range of dates (a 5 week range of dates, with the start date and end date of the range being determined by the current day: 3 weeks back from today, to 2 weeks forward from today) and fill in the targets and levels accordingly, as such:
Date     Target     Level
10/1     1000       1
10/2     1000       1
10/3     1000       1
10/4     2000       1
10/5     2000       1
10/6     2000       1
10/7     2000       2
10/8     2000       2
...
11/5     2000       2

How do I go about:

*

*Selecting the range of dates (as efficiently as possible)

*Filling in the range of dates with the respective target/level from the appropriate date in my table?
Thank you.

A: You can do this using outer apply.  The following creates a list of dates using a recursive CTE:
with d as (
      select cast(getdate() as date) as dte
      union all
      select dateadd(day, -1, dte)
      from d
      where dte >= getdate() - 30
select d.dte, t.target, t.level
from d outer apply
     (select top 1 t.*
      from t
      where d.dte >= t.dte
      order by t.dte desc
     );

A: you can use a CTE to generate your 'missing' dates, then use a CROSS APPLY to obtain the target and level that was last active (by querying the TOP 1 DESC where the date is on or before current date) - finally I introduced 'maximum date' as a variable
DECLARE @MAXD as DATETIME = '20161105';

WITH DATS AS (SELECT MIN([Date]) D FROM dbo.YourTab
            UNION ALL
            SELECT dateadd(day,1,D) FROM DATS WHERE D < @MAXD)
select DATS.D, CA.Target, CA.Level from DATS
    CROSS APPLY
    (SELECT TOP 1 Y.Target, Y.Level FROM YourTab Y
                                     WHERE
                                          Y.[Date] <= DATS.D
                                     ORDER BY Y.Date DESC) CA
    option (maxrecursion 0);

I made a bit of a change with dates to go back 3 and forward two weeks - also I switched to outer apply to handle no data in force
DECLARE @MIND as DATETIME = dateadd(week,-3,cast(getdate() as date));
DECLARE @MAXD as DATETIME = dateadd(week, 5,@MIND);

WITH DATS AS (SELECT @MIND D
            UNION ALL
            SELECT dateadd(day,1,D) FROM DATS WHERE D < @MAXD)
select DATS.D, CA.Target, CA.Level from DATS
    OUTER APPLY
    (SELECT TOP 1 Y.Target, Y.Level FROM YourTab Y WHERE Y.[Date] <= DATS.D ORDER BY Y.Date DESC) CA
    ORDER BY DATS.D
    option (maxrecursion 0);

Final change - if there is no earlier value for the date - take first future row
DECLARE @MIND as DATETIME = dateadd(week,-3,cast(getdate() as date));
DECLARE @MAXD as DATETIME = dateadd(week, 5,@MIND);

WITH DATS AS (SELECT @MIND D
            UNION ALL
            SELECT dateadd(day,1,D) FROM DATS WHERE D < @MAXD)
select DATS.D, COALESCE(CA.Target, MQ.Target) Target , COALESCE(CA.Level, MQ.Level) Level from DATS
    OUTER APPLY
    (SELECT TOP 1 Y.Target, Y.Level FROM YourTab Y WHERE Y.[Date] <= DATS.D ORDER BY Y.Date DESC) CA

    OUTER APPLY
    (
        SELECT TOP 1 M.Target, M.Level FROM YourTab M ORDER BY M.[Date] ASC
    ) MQ
        ORDER BY DATS.D
    option (maxrecursion 0);

A: I don't know why you store dates as MM/DD but you need some conversion into right datatype. This could do a trick:
;WITH YourTable AS (
SELECT *
FROM (VALUES
('10/2', 1000, 1),
('10/4', 2000, 1),
('10/7', 2000, 2)
) as t([Date], [Target],  [Level])
), dates_cte AS ( --this CTE is generating dates you need
    SELECT DATEADD(week,-3,GETDATE()) as d --3 weeks back
    UNION ALL
    SELECT dateadd(day,1,d)
    FROM dates_cte
    WHERE d < DATEADD(week,2,GETDATE()) --2 weeks forward
)

SELECT  REPLACE(CONVERT(nvarchar(5),d,101),'/0','/') as [Date],
        COALESCE(t.[Target],t1.[Target]) [Target],
        COALESCE(t.[Level],t1.[Level]) [Level]
FROM dates_cte dc
OUTER APPLY ( --Here we got PREVIOUS values
    SELECT TOP 1 *
    FROM YourTable
    WHERE CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) <= dc.d
    ORDER BY CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) DESC
    ) t
OUTER APPLY ( --Here we got NEXT values and use them if there is no PREV
    SELECT TOP 1 *
    FROM YourTable
    WHERE CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) >= dc.d
    ORDER BY CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) ASC
    ) t1

Output:
Date    Target  Level
10/5    2000    1
10/6    2000    1
10/7    2000    2
10/8    2000    2
10/9    2000    2
10/10   2000    2
10/11   2000    2
10/12   2000    2
...
11/9    2000    2

EDIT
With Categories:
;WITH YourTable AS (
SELECT *
FROM (VALUES
('10/2', 1000, 1, 'A'),
('10/4', 3000, 1, 'B'),
('10/7', 2000, 2, 'A')
) as t([Date], [Target], [Level], [Category])
), dates_cte AS (
    SELECT DATEADD(week,-3,GETDATE()) as d
    UNION ALL
    SELECT dateadd(day,1,d)
    FROM dates_cte
    WHERE d < DATEADD(week,2,GETDATE())
)

SELECT  REPLACE(CONVERT(nvarchar(5),d,101),'/0','/') as [Date],
        COALESCE(t.[Target],t1.[Target]) [Target],
        COALESCE(t.[Level],t1.[Level]) [Level],
        c.Category
FROM dates_cte dc
CROSS JOIN (
    SELECT DISTINCT Category
    FROM YourTable
) c
OUTER APPLY (
    SELECT TOP 1 *
    FROM YourTable
    WHERE CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) <= dc.d
        AND c.Category = Category
    ORDER BY CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) DESC
    ) t
OUTER APPLY (
    SELECT TOP 1 *
    FROM YourTable
    WHERE CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) >= dc.d
        AND c.Category = Category
    ORDER BY CONVERT(datetime,REPLACE([Date],'/','/0')+'/2016',101) ASC
    ) t1
ORDER BY c.Category, d

A: Not sure if I'm over simplifying this, but:
select min(X.Date) Date_Range_Start, max(X.date) Date_Range_End
      , V.<value_date>
      , isnull(X.Target, 'Out of range') Target
      , isnull(X.Level, 'Out of range') Level
   from X --replace this with your table
   left join <value_table> V --table with dates to be assessed
          on V.<Date> between X.Date_Range_Start and X.Date_Range_End
group by Target, Level, V.<value_date>


text:
Q: f(x) = 1 for -0.5f(x) = 1 for -0.5< X <0.5
         otherwise 0.

I want to define this function and plot the function in MATLAB within the interval -10 to 10.

A: How about this
x = linspace(-10, 10, 1000);
fx = ( x > -0.5 ) & ( x < 0.5 );
figure;
plot( x, fx );


text:
Q: will x86 cpu perform an early end of multiplication when detects a zero-operand? ================Update=======================
Seems duplicate of Do modern cpus skip multiplications by zero?
But please allow me to reserve this post, because I didn't search out that post before my publish. And allow me to post my test result in the answer area.
==================Original Post=================
Take this function as example:
int mul(int a, int b, int c, int d){
    return a*b*c*d;
}

When cpu enters this function call:
int result = mul(0, 1, 2, 3);

(assume we don't allow the compiler do any optimization and the machine code appears exactly as the program order.)
I know nowadays x86 CPU has out-of-order execution, will it perform an early end of multiplication when he found he got a zero-operand?
Thanks!

A: No, a modern x86-64 CPU will not stop multiplying numbers just because one of them is zero.  Out of order execution isn't going to prevent any of the instructions from running, it just might allow some to be executed well, out of order.
This is easy to verify using the code you wrote.  Let's call it multiply.c:
int mul(int a, int b, int c, int d){
    return a * b * c * d;
}

int main() {
    for (int i = 0; i < 1e8; i++) {
        int result = mul(0, 1, 2, 3);
    }
}

Firstly verify that the code doesn't run any slower when the '0' is replaced with a '1':
gcc multiply.c -O0
time ./a.out

real    0m0.387s
user    0m0.378s
sys     0m0.002s

Re-running after changing the 0 to a 1 resulting in a real time of 0.384s, no statistical difference.
Next take a look at what assembly is being generated by gcc:
gcc -g -c -O0 multiply.c
otool -tvVX multiply.o

...

_mul:
    pushq   %rbp
    movq    %rsp, %rbp
    movl    %edi, -0x4(%rbp)
    movl    %esi, -0x8(%rbp)
    movl    %edx, -0xc(%rbp)
    movl    %ecx, -0x10(%rbp)
    movl    -0x4(%rbp), %ecx
    imull   -0x8(%rbp), %ecx
    imull   -0xc(%rbp), %ecx
    imull   -0x10(%rbp), %ecx
    movl    %ecx, %eax
    popq    %rbp
    retq
    nopw    %cs:_mul(%rax,%rax)

You can see the three separate multiplies, so they aren't being compiled away or anything of that nature.

A: @Douglas B. Staple
Thanks for you benchmark. I also did a similar test.
#include<stdio.h>
#include"../base/benchmark.h"

#define MAX (100 * 10000)
int product0;
int product1;
int zero = 0;
int one = 1;
int main(void){
    TSTAMP_INIT();
    long time0, time2;

                                                            TSTAMP();
    for(int i = 0; i < MAX; i++){
        product0 *=  zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero * zero ;
    }
                                                            TSTAMP(&time0);
    for(int i = 0; i < MAX; i++){
        product1 =  one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one * one ;

    }

                                                            TSTAMP(&time2);
    printf("%ld %ld\n", time0, time2);
    return 0;
}

Compile and Run:
$ gcc -o t t.c ../base/benchmark.c -O0
$ ./t
84828 74827

The time unit is us.
I have checked the assemble code, it's not optimized.
The reason I use a long multiplication expression inside the loop is that, I want to reduce the time cost proportion occupied by loop instruction.
It seems that the first loop body cost a little more time(84838us), i think it's because of the warm-up phase of CPU cache. I have reverse location of two loop bodies and get a similar result: still the former cost a little more time.
So I can get a same conclusion as you, and as other friends stated, multiplication on x86 is time-fixed.


text:
Q: ag-Grid javaScript, TypeError: rowData is undefined ag-Grid, following the official demo of javascript but using API like real world over hard-coded data. Note: no jQuery, just use the primitive plain XMLHttpRequest() for ajax.

*

*F12 verified API returns data in the same structure as demo, has children node inside, and gripOptions.rowData is assigned with the returned data.

*Tried instantiating rowData inside of gripOptions as
rowData: [],  got the same error
Or
rowData: {},  got ReferenceError: rowData is not defined.

HTML:

JavaScript ag-Grid

myAG.js:
var httpApi = new XMLHttpRequest();
var columnDefs = [
    { headerName: "Client Name", field: "ClientName", unSortIcon: true, cellRenderer: "group" },
    { headerName: "Division", field: "Division" },
    { headerName: "Others", field: "Others" }
];
var gridOptions = {
    columnDefs: columnDefs,
    getNodeChildDetails: getNodeChildDetails
};

function getNodeChildDetails(rowItem) {
    if (rowItem.ClientName) {
        return {
            group: true,

        // provide ag-Grid with the children of this group
            children: rowItem.children,

            // the key is used by the default group cellRenderer
            key: rowItem.ClientName
        };
    } else {
        return null;
    }
}

// wait for the document to be loaded, otherwise
// ag-Grid will not find the div in the document.
document.addEventListener("DOMContentLoaded", function () {
    $.ajax({
        type: "GET",
        url: "/api/myAG/Tree",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            gridOptions.rowData = data;
            var eGridDiv = document.querySelector('#myGrid');
            new agGrid.Grid(eGridDiv, gridOptions);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    })

});

Version:
ag-grid = v8.1.0
FireFox = 50.1.0
Error message:

F12 confirms data exists and assigned:

inside of ag-grid.js, the line it complains about but rowData has data:

A: See this answered post, basically an additional check is needed for the tree.
ag-Grid, try to make Tree Demo work using own data


text:
Q: convert from foreach to for loop below code working perfectly . but i need to convert it from foreach to for loop .please help me  to iteration by for loop. because i have to introduce some if else statement in entire code
@foreach (var item in ViewData["productSl_1"] as IEnumerable<Nazmulkp.Models.Product>)
{

@item.ProductName

Tk.@item.Price

}

Example:
I have to make sure if index number 2 than execute
"
Thank you

A: You do not need to convert your foreach to a for loop for adding a conditional css class. Simply add a counter variable to your code and use that for your if condition as needed.
For example, the below code will add the css class "col-md3" to the 3rd item in your collection.
@{ var counter = 0;}
@foreach (var item in YouCollectionHere)
{

@item.Name

    counter++;
}


text:
Q: how to prove the continious of proper integral with parameter $$\int_{0}^{\pi}{\frac{sin(x)}{x^\alpha (\pi - x)^\alpha}}$$
$\alpha \in (0;2)$
I used Abel's theorem for integral with parameter but it didn't helped.
The other idea was to divide to two integrals from 0 to $\frac{\pi}{2}$ and from $\frac{\pi}{2}$ to $\pi $ and use equivalent transformation like $sin(x) $~$ x$ (if x $\rightarrow$ $0$) and $sin(\pi - x)$ (if x $\rightarrow$ $\pi$) but it didn't help too because new integrals weren't easier
Does anybody have any ideas?

A: A possible idea would be to consider the  approximation $$\sin(x) \simeq \frac{16 (\pi -x) x}{5 \pi ^2-4 (\pi -x) x}\qquad (0\leq x\leq\pi)$$  proposed by Mahabhaskariya of Bhaskara I, a seventh-century Indian mathematician.

A: I have a proof: we divide this integral to
$$\int_{0}^{\frac{\pi}{2}}{\frac{sin(x)}{x^\alpha (\pi - x)^\alpha }} + \int_{\frac{\pi}{2}}^{\pi}{\frac{sin(x)}{x^\alpha (\pi - x)^\alpha }}$$
First integral converges uniformly and it's easy to proof it using Dirichlet for integrals with parameter.
Let's see the second: we have the problem point in $\pi$
I just got wrong using $\sin (\pi - x) $ when x $\rightarrow \pi$. I just have done it and then changed the variable [t = $\pi - x$] and changed the border of integration to from $0$ to $\frac{\pi}{2}$
then the second integral after the changing is:
$$\int_{0}^{\frac{\pi}{2}}{\frac{sin(t)}{(\pi - x)^\alpha  t^\alpha  } dt} $$
That integral is already converges uniformly as we said
And the original integral is converges uniformly like sum of two uniformly converging integrals.


text:
Q: API Platform and custom POST operation with custom body I hope I'm right to ask this. I've looked at (almost) all similar concern but I ain't satisfied yet.
I'm working on a User entity and for days (weeks actually) now i'm trying to POST a user with a custom body. Here's some part of my entity User :
/**
 * @ApiResource(
 *      normalizationContext={"groups"={"read"}},
 *      denormalizationContext={"groups"={"write"}},
 *      itemOperations={
 *          "get",
 *          "put",
 *          "delete",
 *          "get_active_user"={
 *              "method"="GET",
 *              "path"="/users/active/me",
 *              "controller"=UserReadAction::class,
 *              "defaults"={"_api_receive"=false},
 *              "swagger_context"={
 *                  "parameters"={
 *
 *                  }
 *              }
 *          },
 *      },
 *      collectionOperations={
 *          "change_password"={
 *              "method"="POST",
 *              "path"="/users/active/changepassword",
 *              "controller"=UserChangePasswordAction::class,
 *              "normalization_context"={"groups"={"afup"}},
 *              "defaults"={"_api_receive"=false},
 *              "swagger_context"={
 *                  "summary" = "Change user password",
 *                  "parameters"={
 *                      {
 *                          "name" = "User",
 *                          "in" = "body",
 *                          "schema" = {
 *                              "type" = "object",
 *                              "properties" = {
 *                                  "password" = {"type"="string"},
 *                                  "nom" = {"type"="string"},
 *                              }
 *                           },
 *                          "required" = "true",
 *                      }
 *                  },
 *              }
 *          }
 *      }
 * )
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="users")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"read", "write", "afup"})
     */
    private $id;

Here is the controller:
namespace App\Controller\SDK;

use App\Entity\User;
use App\Service\SDK\UserService;
use Symfony\Component\Security\Core\Security;

class UserChangePasswordAction
{
    public function __invoke(User $data)
    {
        var_dump($data);die;
    }
}

And the services.yaml (some part) file
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: false       # Allows optimizing the container by removing unused services; this also means
                            # fetching services directly from the container via $container->get() won't work.
                            # The best practice is to be explicit about your dependencies anyway.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller/*'
        tags: ['controller.service_arguments']

When I try this (see var_dump in controller), i get an error saying:

Cannot autowire argument $data of "App\Controller\SDK\UserChangePasswordAction()": it references class "App\Entity\User" no such service exists

I read the official doc and it seems that the _invoke method should automatically retrieve the entity. But it does not work for me.
Notice: I also defined a custom item operation "get_active_user" and it works fine.
Please I would like to understand :

*

*what I did wrong,

*how it actually works,

Thank you.
EDIT:
In the collectionOperation definition, i removed the following setting which means that we manually want to handle data (User) retrieval  :

*

*"defaults"={"_api_receive"=false},

Now, the controller returns an empty User entity, not an error. I still can't get the submitted data.

A: The edit of my question fix the concern. Actually, I just needed to remove this annotation from the POST opration definition :')

"defaults"={"_api_receive"=false},

Now, when I submit the data, I get them as on the following image :

This annotation is important when you write custom GET operation.

A: It is not working because that is a CollectionOperation. In this case, you can get the user through TokenStorageInterface
namespace App\Controller\SDK;

use App\Entity\User;
use App\Service\SDK\UserService;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class UserChangePasswordAction
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function __invoke(Request $request) //Get request if you want o keep args empty
    {

        var_dump($this->tokenStorage->getToken()->getUser());die;
    }
}


text:
Q: Error Message Uncaught TypeError: Cannot read properties of undefined Does anybody know why I get this error? I want to pass the setCookie function to ParseUserCookie but I get an error "Uncaught TypeError: Cannot read properties of undefined (reading 'setCookie')"
function TicTacToe(){
  const [cookie, setCookie] = useState(null);
  <button onClick={() => handleMultiplayerClick(setCookie)}>
  .....
  }

const handleMultiplayerClick = (props) => {
  promptUserCookie();
  let cookie = parseUserCookie(props.setCookie); //Cannot read properties
  ...
  }

Uncaught TypeError: Cannot read properties of undefined (reading 'setCookie')

A: first of all, handleMultiplayerClick is not a react component, it's a function, those are called parameters not props.
But you can call the parameters whatever you want, the problem is that you are dealing with the value as it is an object.
In functions, you can access the parameters like this:
function myFun(param1, param2){
    console.log(param1);
    console.log(param2):
}

But it will work your way if you pass an object instead of passing directly a value:
function myFun(props){
    console.log(props.param1);
}
myFun( { param1:10 } );

So either you do it like this:
function TicTacToe(){
  const [cookie, setCookie] = useState(null);
  <button onClick={() => handleMultiplayerClick(setCookie)}>
  .....
  }

const handleMultiplayerClick = (setCookie) => {
  promptUserCookie();
  let cookie = parseUserCookie(setCookie);
  ...
  }

Or like this:
function TicTacToe(){
  const [cookie, setCookie] = useState(null);
  <button onClick={() => handleMultiplayerClick( { setCookie } ) }>
  .....
  }

const handleMultiplayerClick = (params) => {
  promptUserCookie();
  let cookie = parseUserCookie(params.setCookie);
  ...
  }

A: So as to pass a function as a prop, you should wrap the button in a child component, like this:
export default function App() {
  const [cookie, setCookie] = useState(null);

  const handleMultiplayerClick = (updateCookie) => {
    console.log(updateCookie);
  };

  const ChildComp = (props) => {
    return (
      <button onClick={() => handleMultiplayerClick(props.updateCookie)}>
        setCookie
      </button>
    );
  };

  return (

      <ChildComp updateCookie={setCookie} />

Hello CodeSandbox

Start editing to see some magic happen!

  );
}

You can play a bit on the codesandbox here: https://codesandbox.io/s/props-to-child-elem-h2u5nr