text:
Q: How to aggregate the sum of a class model field in django I've been attempting unsuccessfully to show the total_net_interest on my dashboard. I think there is a problem with my strategy. Does anyone have a solution to this issue?
Model
class Investment(models.Model):

    PLAN_CHOICES = (
        ("Basic - Daily 2% for 182 Days", "Basic - Daily 2% for 182 Days"),
        ("Premium - Daily 4% for 365 Days", "Premium - Daily 4% for 365 Days"),
    )
    plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True)
    principal_amount = models.IntegerField(default=0, null=True)
    investment_id = models.CharField(max_length=10, null=True, blank=True)
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now=True, null=True)
    due_date = models.DateTimeField(null=True, blank=True)

    def daily_interest(self):
        if self.plan == "Basic - Daily 2% for 182 Days":
            return self.principal_amount * 365 * 0.02/2/182
        else:
            return self.principal_amount * 365 * 0.04/365

    def net_interest(self):
        if self.plan == "Basic - Daily 2% for 182 Days":
            return self.principal_amount * 365 * 0.02/2
        else:
            return self.principal_amount * 365 * 0.04

    def total_net_interest(self):
        return self.Investment.aggregate(total_net_interest=Sum('net_interest'))['total_net_interest']

A: As pointed out in the comments, you can't aggregate using a model method - however, you could add net_interest to the queryset using annotation and then aggregate the annotated field.
Django .aggregate() on .annotate()
You will likely need to use Case and When to apply your logic from that method.
As an aside, your model PLAN_CHOICES has both values copied, a better way of writing this would be something like this:

PLAN_BASIC = "basic"
PLAN_PREMIUM = "premium"

PLAN_CHOICES = (
        (PLAN_BASIC, "Basic - Daily 2% for 182 Days"),
        (PLAN_PREMIUM, "Premium - Daily 4% for 365 Days")
)

This means that only "basic" and "premium" are stored in the database, but it will still show the verbose strings that you have entered. You can then do something like Investment.PLAN_BASIC or self.PLAN_BASIC, depending on the context, to ensure you aren't hard coding strings in multiple places.

A: You have to annotate the interests in a queryset to aggregate on this annotations:
from django.db.models import Case, F, FloatField, Q, Sum, When

total = (Investment
         .objects
         .annotate(net=Case(When(Q(plan='Basic - Daily 2% for 182 Days'),
                                 then=F('principal_amount') * 365 * 0.01),
                            default=F('principal_amount') * 365 * 0.04,
                            output_field=FloatField))
         .aggregate(total=Sum('net')))['total']


text:
Q: UILabel autolayout - stretch horizontal then vertical I have a UILabel. I've set trailing and leading space constraints, also I've added align Y center constraint. I've set Lines count to zero.

My goal is to stretch UILabel to some maximum width and then add new line. With given constraints I have following result:

I need first label to be not wider than P

A: You should use prefferedMaxLayoutWidth in that case. You can read more about this here.
You should use something like:
self.team1Label.preferredMaxLayoutWidth = 20; // or other value in PT

redpajama_set_name: RedPajamaStackExchange


text:
Q: SVG filter with feImage and feBlend, multiply blend mode not working as expected I am trying to create an SVG where black or white squares are overlayed on an image using various blend modes. I'm using a filter with an feImage primitive for the picture, making it partially transparent with feColorMatrix, and blending it with the square with feBlend. The normal blend mode works as I would expect it to, but multiply does not. Here's what I'm getting:

Here's a jsfiddle with the svg code
For multiplying with white (bottom-middle square), I expected it not to lighten the image at all, regardless of opacity, since multiplying with white is basically like multiplying by 1. For black (middle-top square), I expect it to darken the image according to its transparency. These are the things that happen when I play around in GIMP.
The SVG spec has the formulae for various blend modes here, if you're wondering (I can't post more than 2 links with my current reputation, sorry).
www.w3.org/TR/SVG/filters.html#feBlendElement
What I think the problem is:
In my filter, I'm actually applying opacity to the feImage, not the SourceGraphic, simply because I couldn't figure out how to do it the other way around, despite much experimentation. Ideally it would be the squares that were partially transparent, and were then overlayed on the image. Setting in="SourceGraphic" for the feColorMatrix doesn't work right, nor does setting the opacity attribute on the rects themselves (they seem to blend with the default white svg background before blending with the image). I'm sure there's some simple solution, but I just can't find it.
Please tell me if anything's unclear. Any assistance is appreciated :)

A: For the love of god, add explicit ins and results to your filters. Otherwise it's like trying to push spaghetti. This is what you're looking to do:
    <filter color-interpolation-filters="sRGB" x="-1.0" y="-1.0" width="3.0"
        xmlns:xlink="http://www.w3.org/1999/xlink" xlink:type="simple"
        xlink:actuate="onLoad" height="3.0"
        xlink:show="other" id="blend-square-multiply">
        <feImage result="raw photo" x="0" y="0" width="522" height="530"
                 xlink:href="http://wallpapersus.com/wallpapers/2012/11/Pirates-Of-The-Caribbean-On-Stranger-Tides-05-2048x2048.jpg"/>
        <feComposite result="photo clip" in="raw photo" in2="SourceGraphic" operator="in"/>
        <feColorMatrix in="SourceGraphic" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 .5 0" type="matrix" result="color-trans"/>
        <feBlend mode="multiply" in="photo clip" in2="color-trans"/>
    </filter>

Fiddle with some edits to make it clear what I was editing: http://jsfiddle.net/Wu96x/

A: Isn't it just appearing lightened because you are placing a partially transparent image over a white background?  As you say, the multiply-by-white will be having no effect.


text:
Q: Showing $\sum_{n=1}^\infty\frac1{n^2}\left(1+\frac1{2^2}+\cdots+\frac1{n^2}\right)=\frac{7\pi^4}{360}$ Help me calculate the amount in a simpler way:
\begin{aligned}
\mathcal{S}&=\sum\limits_{n=1}^{\infty }\frac{1}{n^2}\left ( 1+\frac{1}{2^2}+\ldots+\frac{1}{n^2}  \right )=\sum\limits_{n=1}^{\infty }\frac{H^{\left ( 2 \right )}_n}{n^2}=-\sum\limits_{n=1}^{\infty }H^{\left ( 2 \right )}_n\int\limits_{0}^{1}x^{n-1}\ln xdx=&&\\
        &=-\int\limits_{0}^{1}\frac{\ln x}{x}\sum\limits_{n=1}^{\infty }H^{\left ( 2 \right )}_nx^ndx=\int\limits_{0}^{1}\frac{\ln x}{x}\frac{\operatorname{Li}_2x}{1-x}dx=-\int\limits_{0}^{1}\left ( \frac{1}{x}+\frac{1}{1-x} \right )\ln x\operatorname{Li}_2xdx=&&\\
        &=-\int\limits_{0}^{1}\frac{\ln x\operatorname{Li}_2x}{x}dx-\int\limits_{0}^{1}\frac{\ln x\operatorname{Li}_2x}{1-x}dx=&&\\
        &=-\frac{\ln^2 \operatorname{Li}_2x}{2}\Bigg|_0^1-\frac{1}{2}\int\limits_{0}^{1}\ln^2 x\cdot \frac{\ln \left ( 1-x \right )}{x}dx+\ln x\operatorname{Li}_2x\ln \left ( 1-x \right )\Bigg|_0^1-&&\\
&-\int\limits_{0}^{1}\ln \left ( 1-x \right )\left ( \frac{\operatorname{Li}_2x}{x}-\frac{\ln x\ln \left ( 1-x \right )}{x} \right )dx=&&\\
        &=-\frac{1}{2}\int\limits_{0}^{1}\frac{\ln^2 x\ln \left ( 1-x \right )}{x}dx+\int\limits_{0}^{1}\frac{\ln^2 \left ( 1-x \right )\ln x}{x}dx+\int\limits_{0}^{1}\operatorname{Li}_2xd\left ( \operatorname{Li}_2x \right )=&&\\
        &=\frac{1}{2}\sum\limits_{n=1}^{\infty }\frac{1}{n}\int\limits_{0}^{1}x^{n-1}\ln^2 xdx+2\sum\limits_{n=1}^{\infty }\left ( \frac{H_n}{n}-\frac{1}{n^2} \right )\int\limits_{0}^{1}x^{n-1}\ln x+\frac{\operatorname{Li}^2_2x}{2}\Bigg|_0^1=&&\\
        &=\frac{1}{2}\sum\limits_{n=1}^{\infty }\frac{1}{n}\cdot \frac{2}{n^3}+2\sum\limits_{n=1}^{\infty }\left ( \frac{H_n}{n}-\frac{1}{n^2} \right )\left ( -\frac{1}{n^2} \right )+\frac{\pi^4}{72}=&&\\
        &=\zeta \left ( 4 \right )-2\sum\limits_{n=1}^{\infty }\left ( \frac{H_n}{n^3}-\frac{1}{n^4} \right )+\frac{\pi^4}{72}=\frac{\pi^4}{90}-2\left ( \frac{\pi^4}{72}-\frac{\pi^4}{90} \right )+\frac{\pi^4}{72}=\frac{\pi^4}{30}-\frac{\pi^4}{72}=\frac{7\pi^4}{360}
\end{aligned}

A: You don't need any integrals.
$$S=\sum_i \sum_{j<=i} 1/(i^2 j^2)= \sum_i \sum_j 1/(2i^2 j^2) + \sum_i 1/(2i^4) =(\zeta(2)^2 +\zeta(4))/2= (\pi^4/36+\pi^4/90)/2=7\pi^4/360$$


text:
Q: How can I link to a particular image in a lightbox slideshow? I think I may be way in over my head here...
I'm using a WP custom post type and attachments in conjunction with FancyBox to create a slideshow/gallery.  Nothing fancy, I don't think.  You can see it here: http://photo.convoke.info/galleries/test-gallery/
Except, I want to be able to link to a particular image.  So, in that particular gallery, there are two images.  I'd like to be able to give someone a link like http://photo.convoke.info/galleries/test-gallery#1 and have it open up the gallery page with the first image already open in the lightbox. #2 for the second image, etc.
Is this possible?
It doesn't have to be #1... could be any sort of identifier. I'm pretty noob at javascript/jQuery stuff, so please forgive me... I tried googling around but couldn't find anything of use.
Thanks!

A: You need to do two things either with pure js or jquery.
1) when you click an image, set the window.location.hash to your desired value. (or use Jquery history plugin, or use html5 history object, take your pick). This will put the hash in the URL.
 <img onclick='setHash(this.id)' ...

where setHash is your function to add the hash. Then on pageload/hash change you will want a handler to invoke the lightbox with the proper image based on the hash. Usually i just make the id of my image match and use that to pass around. But there might be a bettwe way like convoke said from within the fancybox thingy.

A: You can hand out URLs with a query string to accomplish this easily enough.
http://photo.convoke.info/galleries/test-gallery?fancybox=1

Then using something like the code found here (credit):
function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

you can easily check for / do something if that value exists.  In your $(document).ready() check for the value, and if it exists, trigger the $.fancybox.jumpto( [index] ) method.
You can expand on / make this as complex as you want, for instance if you had multiple galleries on a page, you could also include another key/value in the URL to indicate which gallery.
http://photo.convoke.info/galleries/test-gallery?fbgallery=fanexpo&fbphoto=1

A: Whelp, after a few weeks of mucking around, I finally figured it all out.  I needed a few functions:
 $(document).ready(function() {
               if (window.location.hash) { // if there is a hash
                       $.fancybox.open($('.fancybox'), {index : parseInt(location.hash.substring(1))});
               }
       });

This badboy checks for a hash, and opens the image corresponding to said hash using fancy box ONLY WHEN THE PAGE IS LOADED.
function sethash(id)
{
   top.document.location.hash = id;
}

This little guy is called by the links to each image in the gallery markup.  It sets tthe hash of the page equal to the index of whatever image you've clicked on.
Image

This isn't REAL code, but you get the idea. I have a variable called count that I use to index each image in the gallery.  This number corresponds to the index of the image in the fancybox slideshow (i.e. it starts at 0 for the first image in the gallery)
It was a lot of work, but it's finally working (almost) perfectly.  The last thing I'm going to try is to get the hash to change/update when you click on the previous/next arrows in fancybox.  But frankly, if that doesn't work, I don't really care.


text:
Q: How to set up an alert list panel in Grafana? I've seen the following widget from Grafana demo page:

And I can't understand how to do this. I've added a couple of alerts to my dashboard, yet I don't see how do I make them visible in "Alert List" widget I've added before.

A: They should show up automatically. It takes a few seconds before the alert is run and you have to save the dashboard and refresh the page. I just tested this locally and it worked.
The other thing to check is what options are chosen on the Options tab. Have you checked one of the filtering options that is hiding your alert or are there more alerts than 10 which is the default max:


text:
Q: Convert Map of maps into Lists using Java 8 Streams I have a map:
Map<String, Map<Integer, List<Integer>>>
e.g. Map<Name, Map<Id, List<ReferenceId>>>

Outcome:
List<Id>
List<ReferenceId>

I wanna convert this map into two list of Integers. One list contains inner-map keys, and other contains inner-map value (i.e. List<Integer>)
Can anyone tell me how to do this in Java 8 using streams?
I tried this way but got Cast Exception, can not convert String to Integer.
map.values().stream()
    .map(m -> m.entrySet()
    .stream()
    .map(e -> e.getKey())
    .collect(Collectors.toList()))
    .flatMap(l -> l.stream())
    .collect(Collectors.toList());

A: There is no way, how your code
List<Integer> list = map.values().stream()
    .map(m -> m.entrySet().stream()
            .map(e -> e.getKey())
            .collect(Collectors.toList()))
    .flatMap(l -> l.stream())
    .collect(Collectors.toList());

can produce a ClassCastException, unless you managed to insert objects of wrong type into the source map via unchecked operation(s) before the Stream operation. Such a situation is called heap pollution and you should compile your entire code with all warnings enabled (javac: use option -Xlint:unchecked)  and solve them.
But note that your code is unnecessarily complicated. The chain, .entrySet().stream().map(e -> e.getKey()) is streaming over the entries and mapping to the keys, so you can stream over the keys in the first place, i.e. .keySet().stream(). Then, you are collecting the stream into a List, just to invoke .stream() in the subequent flatMap step, so you can simply use the stream you already have instead:
List<Integer> list = map.values().stream()
    .flatMap(m -> m.keySet().stream())
    .collect(Collectors.toList());

Alternatively, you can let the collector do all the work:
List<Integer> list = map.values().stream()
    .collect(ArrayList::new, (l,m) -> l.addAll(m.keySet()), List::addAll);

Getting the values instead of the keys works similar, but requires another flatMap step to get the List elements:
List<Integer> list = map.values().stream()
    .flatMap(m -> m.values().stream().flatMap(List::stream))
    .collect(Collectors.toList());

which is equivalent to
List<Integer> list = map.values().stream()
    .flatMap(m -> m.values().stream())
    .flatMap(List::stream)
    .collect(Collectors.toList());

Again, there's the alternative of letting the collector do all the work:
List<Integer> list = map.values().stream()
    .collect(ArrayList::new, (l,m)->m.values().forEach(l::addAll), List::addAll);

or
List<Integer> list = map.values().stream()
    .collect(ArrayList::new, (l,m)->m.forEach((k,v)->l.addAll(v)), List::addAll);

A: If your value is like Map<String,Object>. And your Object is like Map<String,Object>:
 Set<String> mapKeys = myMap.entryset()    //Set<Entry<String,Object>>
.stream()                                  //Stream<Entry<String,Object>>
.map(m->(Map<String,Object>) m.getValue()) //Stream<Map<String,Object>>
.map(Map::keySet)                          //Stream<Set<String>>
.flatMap(l->l.stream())                    //Stream<String>
.collect(Collectors.toSet())

it works

A: Map<String, Map<Integer, List<Integer>>> map = ...

List<Integer> keys = map.values()       // Collection<Map<Integer, List<Integer>>>
        .stream()                       // Stream<Map<Integer, List<Integer>>>
        .map(Map::keySet)               // Stream<Set<Integer>>
        .flatMap(Set::stream)           // Stream<Integer>
        .collect(Collectors.toList());  // List<Integer>

List<Integer> values = map.values()     // Collection<Map<Integer, List<Integer>>>
        .stream()                       // Stream<Map<Integer, List<Integer>>>
        .map(Map::values)               // Stream<Collection<List<Integer>>>
        .flatMap(Collection::stream)    // Stream<List<Integer>>
        .flatMap(List::stream)          // Stream<Integer>
        .collect(Collectors.toList());  // List<Integer>

A: Adding for one more working scenario
 Map<Integer, List<Integer>> existingPacakagesMap = // having value {123=[111, 222, 333], 987=[444, 555, 666]}

Retrieving logic
 List<Integer>   ListOfAllPacakages= existingPacakagesMap.values().stream().flatMap(List::stream).collect(Collectors.toList());

Result will be

ListOfAllPacakages=  [111, 222, 333, 444, 555, 666]


text:
Q: Помогите составить код с операторами switch,break,goto Сейчас делаю задачу из интернета,основная цель используя оператор switch, составить программу для получения таблицы значений функции У для целочисленных значений аргумента Х из интервала(-10;15).
Когда Х(7,9,11), У=sqrt(fabs(x-10))
Когда Х(6,8,10,12),  У=pow(tan(x/5),2)
Когда Х(-2,5), У=2*sin(x/p)
Во всех остальных случаях У=exp(x+2)
Я бы хотел что бы в ответ выводились все варианты X и У + сократить код. Как это можно сделать?
P.S. За ошибки сильно не пинайте,пожалуйста. 2 неделю обучаюсь.
    #include<math.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
    int x,y,p;
    switch(-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
    {
    case 7:
    cout <<"X=7,y=sqrt(fabs(x-10))";
    case 11:
    cout <<"X=11,y=sqrt(fabs(x-10))";
    case 9:
    cout <<"X=9,y=sqrt(fabs(x-10))";
    case 6:
    cout <<"X=6,y=pow(tan(x/5),2)";
    case 8:
    cout <<"X=8,y=pow(tan(x/5),2)";
    case 10:
    cout <<"X=10,y=pow(tan(x/5),2)";
    case 12:
    cout <<"X=12,y=pow(tan(x/5),2)";
    case -2:
    cout <<"X=-2,y=2*sin(x/p)";
    case 5:
    cout <<"X=5,y=2*sin(x/p)";
    default:
    cout <<"X=!(-10...15),y=exp(x+2)";
    }
    getchar();
}

A:   #include<math.h>
  #include<stdio.h>
  #include<iostream>

  using namespace std;

  void main()
  {
     int x,y;
     cin>>x;
     switch(x)
     {
       case 7:
       case 9:
       case 11:
         y=sqrt(fabs(x-10));
         cout<<"x= "<<x<<"y=sqrt(fabs("<<x<<"-10))="<<y;
         break;
       case 6:
       case 8:
       case 10:
       case 12:
          y=pow(tan(x/5),2)
          cout<<"x= "<<x<<"y=pow(tan("<<x<<"/5),2)="<<y;
          break;
       case -2:
       case 5:
          y=2*sin(x/p);cout<<y;
          break;
       default:
         y=exp(x+2);cout<<y;
         break;
     }
     getchar();
  }

A: У вас непонятно, что такое p, далее, x действительно должен быть целым, но y - double. Если позарез нужен switch - то, например, так (еще раз обратите внимание на p):
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;
int main()
{

    double p = 1.0; // ???;  <-- Тут надо определить ваше p
                    // Чтоб компилировалось, я дал ему значение 1
    cout << "  x       y\n-----------------\n";
    for(int x = -10; x <= 15; ++x)
    {
        double y;
        switch(x)
        {
        case  7:
        case  9:
        case 11: y = sqrt(fabs(x-10)); break;
        case  6:
        case  8:
        case 10:
        case 12: y = tan(x/5.0); y *= y; break;
        case -2:
        case  5: y = 2*sin(x/p); break;
        default: y = exp(x+2);
        }
        cout << setw(3) << x << "  " << setprecision(7) << setw(12) << y << endl;
    }
}

P.S. Для goto места не нашел, разве что цикл через него вручную делать...


text:
Q: where have all my decorations gone? where have all my decorations gone?  I had decorated 12 levels yesterday morning.  When I went back to check my game that afternoon I only had one that was decorated... whats going on?

A: The Emperor will remove the decorations.  He feels they don't truly represent the deadly implications of the Death Star.


text:
Q: Prove that there are infinitely many critical points and they are all local (and absolute) minima on $x^2+4y^2-4xy+2$ I am studying for a fast approaching Calc 3 midterm exam and ran into this problem in the textbook.

Show that $f(x,y) = x^2+4y^2-4xy+2$ has an infinite number of critical points and that $D = 0$ at each one. Then show that $f$ has a local (and absolute) minimum at each critical point.

So I am able to solve the two partial derivatives to get $f_x=2x-4y$ and $f_y=8y-4x$ and that I can solve both equations for $f_x=f_y=0$ which is true for all points. I also can see that this is is true for all values: $$D = (f_{xx})(f_{yy})-(f_{xy})^2 = 0$$
However, I dont know how to go about determining that all of the critical points are local and absolute minimums. I believe that I was only taught the 2nd derivative test where you compare the value of $D$ to $f_{xx}$.
Any ideas? Thanks!

A: Note that
$$f(x,y)=(x-2y)^2+2\ .$$
So at any point where $x=2y$ (and there are infinitely many such points) the value of $f(x,y)$ is $2$, and for any other point the value is greater than $2$.  So these points are local and absolute minimum points.


text:
Q: .htaccess Remove PHP get data from URL Well I'm making profile pages so right now it looks like this
http://example.com/random/?user=Robert

What I want to do is remove ?user= from the URL so the page appears as
http://example.com/random/Robert

Iv'e searched and I can't find anything working for me.
Thanks!

A: Based on http://statichtml.com/2010/mod-rewrite-baseon-on-query-string.html this should do the trick:
RewriteCond %{QUERY_STRING} ^user=(.*)$    [NC]
RewriteRule ^random$ random/$1             [NC,L,R=301]

A: The first step is to make all of your links in this form http://example.com/random/Robert, then in the htaccess file in your document root, add:
RewriteEngine On
RewriteRule ^random/(.+)$ /random/?user=$1 [L]

But to handle 301 redirects to your old URLs, you can include this:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /random/\?user=([^\ ]+)
RewriteRule ^random/$ /random/%1 [R=301,L]


text:
Q: what is the purpose of using 2 .then in http requests? Please explain me the following code snippet.. I'm trying to send a PUT request to edit single region ...
I want to get explained how the Success action is fired with 2 .then s.....and why to use 2 .then s?
const editRegion = createLogic({
  type: types.EDIT_REGION,
  latest: true,
  debounce: 1000,

  process({ MockHTTPClient, getState, action }, dispatch, done) {
    let HTTPClient;
    if (MockHTTPClient) {
      HTTPClient = MockHTTPClient;
    } else {
      HTTPClient = API;
    }

    let object = action.payload;

    HTTPClient.Put(endPoints.EDIT_REGIONS, object)
      .then(resp => resp.data)
      .then(data => dispatch(actions.editRegionSuccess(data)))

      .catch(err => {
        var errorMessage;
        if (err.response && err.response.status == 400) {
          errorMessage = err.response && err.response.data.errormessage;
        }
        dispatch(
          actions.editRegionFailed({
            title: "Error!",
            message: err
          })
        );
      })
      .then(() => done());
  }
});


text:
Q: How interpret the dual lattice $\Gamma^*$? In the book Eigenvalues in Riemannian Geometry of Isaac Chavel page $28$ - $29$, they talk about the lattice $\Gamma$  and it is defined as $$\Gamma = \left\{\sum_{j=1}^n \alpha^j v_j : \alpha^j \in \mathbb{Z}, j=1,\dots, n\right\}.$$ If I take the canonical basis (simplifying the problem) $v_1=(1,0)$, $v_2=(0,\sqrt{2})$, then I obtain $\Gamma=\begin{pmatrix}
  1 & 0  \\
  0 & \sqrt{2}
 \end{pmatrix}\mathbb{Z}^2$. Now, it is possible to associate to the lattice $\Gamma,$ the dual lattice, $\Gamma^*$, given by $$\Gamma^*=\{y \in \mathbb{R}^n : \langle x,y\rangle \in \mathbb{Z} \text{ for all } x \in \Gamma\}.$$
Questions : Does it exist a way to interpret the dual lattice $\Gamma^*$ graphically, a sketch? How should we interpret this concept in the resolution of the spectrum on the torus?
Thanks for your help!


text:
Q: trouble creating table using foreign key create table department
(
dept_name varchar(20),
building varchar(20),
budget numeric(12, 2),
primary key(dept_name)
);

This is table that i created before...
now i am writing this:
create table course
(
course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
foreign key (dept_name) references department
);

an it shows :

ERROR 1005 (HY000): Can't create table 'satyarth.course' (errno: 150)

A: You're missing a portion of the FOREIGN KEY requirement, as you cannot simply refer to another table:
foreign key (dept_name) references department(dept_name)

A: Add the reference table field name PFB
create table course(course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
FOREIGN KEY (`dept_name`) REFERENCES `department` (`dept_name`)
);


text:
Q: Transfer a BitmapData object from an AS2 swf to a parent AS3 swf via SWFBridge I need to transfer a BitmapData object created in an AS2 swf to an AS3 swf. I'm using gskinner's SWFBridge  to establish a two way communication between both flash movies.
The AS3 movie loads the AS2 swf which works completely standalone and lets the user manipulate MovieClips and finally generate an image from the composition he creates. I need the AS3 movie to receive this image (bitmapData), do some fancy image processing stuff AS2 isn't able to do and send the new image back to the AS2 movie.
So here's the code
AS2 swf:
var userCompo_mc:MovieClip = container.createEmptyMovieClip("userCompo_mc",10);
var image:BitmapData = new BitmapData(userCompo_mc._width, userCompo_mc._height);
finalCompo.attachBitmap(image); // Just to make sure the final bitmap is right
image.draw(userCompo_mc, compo.title);

//Send the image to the AS3 movie
sb1.send("imageTransfer",image);

AS3 swf:
function imageTransfer(bitmapData:BitmapData, title:String):void
{
    var bmp:Bitmap = new Bitmap(bitmapData);
    this.addChild(bmp);
    trace(title); // --> returns the right title
    trace(bitmapData); // --> returns null
}

I think using something like copyPixel32(), saving everything into an array and then passing it to AS3 would do the trick but it's really a performance hog.
Also, I'm not allowed to convert the AS2 swf into AS3 code.
Any suggestions?
Thanks you!

A: It seems like the as2 movie adds some decorations/movieclips to a an image.
After that you draw it and send attempt to send it to as3.
Since looping though all the pixels is slow, as you mention, I imagine it's faster to draw the as2 content from the as3 movie.
e.g.
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loaded);
loader.load(new URLRequest('yourAS2Movie.swf'),new LoaderContext(true));

function loaded(event:Event):void{
    var as2Clip:AVM1Movie = AVM1Movie(loader.content);
    var bd:BitmapData = new BitmapData(as2Clip.width,as2Clip.height,false,0);
    bd.draw(as2Clip);
    addChild(new Bitmap(bd));
}

In this snippet the as2 content is drawn on load. In your case you would trigger/call a function that draws the as2 content via SWFBridge, after the as2 movie is ready/setup for what you need.
This works assuming you want to display the as2 content inside the as3 movie, which means you will load the as2 movie anyway. If not, either you load the as2 content, but don't add it to the display list, which means you'll be loading the as2 movie. Otherwise, you could try to save your final bitmap from the as2 movie using a server side language(like php for example), then trigger a function in the as3 movie, via SWFBridge, that will load the previously saved image.
HTH


text:
Q: Right widget completely visible in Flutter I want to have two widgets next each other whereas the right widget is always completely visible. In this case, the two icons are not completely visible.

This is my source code approach but it isn't working with overflow: TextOverflow.ellipsis.
My intention of the widgets would be that the texts on the left side are ending with

...

if their are to long. How can I make the widget 2 always completely visible?
new Row(children: <Widget>[
        // ### Widget 1 ###
        new Column(children: <Widget>[
            new Text("A very long strings sassaasasasasasasssss", overflow: TextOverflow.ellipsis),
            new Text("Another very long string skaskajsakaskjsa", overflow: TextOverflow.ellipsis),
        ]),

          // ### Widget 2 ###
          /* should be visible in full size on the right in every situation */
          new Expanded(child:
            new Row(
                children: <Widget>[
                  new Container(
                    child: new IconButton(icon: new Icon(Icons.check, color: Colors.green, size: 35.0), onPressed: () async {
                    }),
                    margin: new EdgeInsets.only(right: 10.0),
                  ),
                  new IconButton(icon: new Icon(Icons.remove, color: Colors.red, size: 35.0), onPressed: () async {
                  }),
                ],
                mainAxisSize: MainAxisSize.min
            )
          ),
        ]
      ),

A: You can use a ListTile with its implemented trailing which simply adds a widget at the end of the row:
ListTile(
    title: Widget1,
    trailing: new Row(
        children: <Widget> [
            IconButton,
            IconButton
        ]
    ),
)

A: The thing is your Text widgets are inside Column widget, which is resize according to it's childs(in this case Text widgets). So, overflow: TextOverflow.ellipsis will not do anything here, until you wrap your text widgets in Column widget.
One way to fix this is to wrap Column widget using a Flexible widget and use flex property as you want.
Fixed code should look like below:
new Row(children: <Widget>[
  // ### Widget 1 ###
  new Flexible(  // newly added
    flex: 2,  // newly added
    child: new Column(
      mainAxisSize: MainAxisSize.min, // newly added
      crossAxisAlignment: CrossAxisAlignment.start,  // newly added
      children: <Widget>[
        new Text("A very long strings sassaasasasasasasssss",
            overflow: TextOverflow.ellipsis),
        new Text("Another very long string skaskajsakaskjsa",
            overflow: TextOverflow.ellipsis),
      ],
    ),
  ),

  // ### Widget 2 ###
  /* should be visible in full size on the right in every situation */
  new Expanded(
    child: new Row(
    //mainAxisSize: MainAxisSize.min, // coomented because will not do anything here
    children: <Widget>[
      new Container(
        child: new IconButton(
            icon: new Icon(Icons.check,
                color: Colors.green, size: 35.0),
            onPressed: () async {}),
        margin: new EdgeInsets.only(right: 10.0),
      ),
      new IconButton(
          icon: new Icon(Icons.remove, color: Colors.red, size: 35.0),
          onPressed: () async {}),
    ],
  )),
]),


text:
Q: Displaying Unicode Drawing Characters in Python I have figured out how to use the characters I need but it works differently in the console on linux versus the windows console.  I want to figure out if there is a way to resolve this where I can make it work on both or at least check to see what system it is running on and call the right code.
This is using the Coding Ground terminal at http://www.tutorialspoint.com/execute_python_online.php
It uses Fedora Release 21 and Python v2.7.5.  This is my initial code:
# Unicode Test
print u'\u2554'

This gives me this error:
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print u'\u2554'
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2554' in position 0: ordinal not in range(128)

On Windows 7 console using Python 2.7.9 this runs correctly and prints the '╔' character. To make it run correctly on the linux terminal I have to use
# Unicode Test
print u'\u2554'.encode('UTF-8')

Unfortunately this code will not run correctly under the Windows console. If I use print u'\u2554'.encode('UTF-8') on Windows I get b'\xe2\x95\x94'
Any ideas on how I can make it run on both systems with out having to maintain different code for each console?

A: You need to change the default encoding of your terminal in linux, on terminal click right then fromTerminal select Set Character Encoding then select Unicode (UTF-8). for more info read http://www.ianbicking.org/illusive-setdefaultencoding.html


text:
Q: Huge eps file in Export with ListPlot and Filling I'm trying to export and eps file from a plot which contains a ListPlot with Filling
n = 1024;
x = Table[N[xdum], {xdum, 0, 1, 1/n}];
y = Cos[2 \[Pi] x];
ListPlot[{x, y}\[Transpose], PlotRange -> {{0, 1}, {-1, 1}},
Filling -> 0]

the dimension of the file is huge. Does anyone have some idea to overcome this problem? I was trying to use Rasterize and then Show, but I can not get the right image scaling.

A: This works,
  plot=ListPlot[{x, y}\[Transpose], PlotRange -> {{0, 1}, {-1, 1}},
    Filling -> 0];
  Export[ "test.eps"  , Rasterize[plot, ImageSize -> 1000]];

The file size is reduced from 140k ( hardly "huge" ) to 30k, with a noticeable loss of quality.
If you are concerned with the displayed size of the figure that is normally dealt with in whatever application you use to import the eps.


text:
Q: How to trigger airflow dag manually? I have beening working on Airflow for a while for no problem withe the scheduler but now I have encountered a problem.
Bascially I have a script and dag ready for a task, but the task doesn't run periodically. Instead it needs to be activated at random time. (External parties will tell us it's time and we will run it. This may happen for many times in the following months.)
Is there anyway to trigger the dag manually? Any other directions/suggestions are welcomed as well.
Thanks.

A: So a dag can be triggered by following ways:

*

*Using the REST API Reference(see documentation)
endpoint-
> POST   /api/experimental/dags/<DAG_ID>/dag_runs

*

*Using Curl:

curl -X POST
http://localhost:8080/api/experimental/dags/<DAG_ID>/dag_runs
-H 'Cache-Control: no-cache'
-H 'Content-Type: application/json'
-d '{"conf":"{"key":"value"}"}'

*Using Python requests:

   import requests
   response = requests.post(url, data=json.dumps(data), headers=headers)

*Using the trigger DAG option present in the UI as mentioned by @Daniel

A: You have a number of options here:

*

*UI: Click the "Trigger DAG" button either on the main DAG or a specific DAG.

*CLI: Run airflow trigger_dag <dag_id>, see docs in https://airflow.apache.org/docs/stable/cli.html#trigger_dag. Note that later versions of airflow use the syntaxairflow dags trigger <dag_id>

*API: Call POST /api/experimental/dags/<dag_id>/dag_runs, see docs in https://airflow.apache.org/docs/stable/api.html#post--api-experimental-dags--DAG_ID--dag_runs.

*Operator: Use the TriggerDagRunOperator, see docs in https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/operators/trigger_dagrun/index.html#airflow.operators.trigger_dagrun.TriggerDagRunOperator and an example in https://github.com/apache/airflow/blob/master/airflow/example_dags/example_trigger_controller_dag.py.

You'll probably go with the UI or CLI if this is truly going to be 100% manual. The API or Operator would be options if you are looking to let the external party indirectly trigger it themselves. Remember to set schedule_interval=None on the DAG.

A: Airflow has API. The method you need is POST /api/experimental/dags/<DAG_ID>/dag_runs. With this method you also could pass config params for the dag run.
We use Jenkins to trigger dags manually. If you are using Jenkins you could check our jenkins pipeine library.

A: The examples given from other answers use the "experimental" API. This REST API is deprecated since version 2.0. Please consider using the stable REST API.
Using method POST dags/<DAG_ID>/dagRuns.
curl -X POST 'http://localhost:8080/api/v1/dags/<DAG_ID>/dagRuns' \
    --header 'accept: application/json' \
    --header 'Content-Type: application/json' \
    --user '<user>:<password>' \   # If authentication is used
    --data '{}'


text:
Q: Не отображается повторно drop down menu Возникла проблема при использовании bootstrap шаблона.
Есть navbar на котором стоит drop down menu, при первом нажатии оно отображается, а при следующих - нет. В чём может быть проблема? Для работы использую Laravel, файл app.js гружу через defer для работы списка, хотя он возможно не причём.

      @guest

{{ __('Login') }}

{{ __('Register') }}

      @else

                  {{ Auth::user()->name }}

                      {{ __('Edit Profile') }}

                      {{ __('Add card') }}

                      {{ __('Logout') }}

                  <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                      @csrf
                  </form>

      @endguest

A: Решил проблему, убрав выпадающий список (заменил на ссылки в самом баре), видимо сам шаблон не поддерживает нормально этот drop down ведь загружал скрипты с jquery и другие с оф. сайта bootstrap. Рандомность отображения этого меню зашкаливает, после обновления он кликабелен 3 раза, потом 5, потом 6 и так далее.


text:
Q: R - Importing multiple xlsx files with a for loop I'm having some trouble writing a function to read in multiple .xlsx files as separate data frames in R with a for loop. When I run the function nothing happens. No Errors, but no data frames are loaded into R either. When I take the assign piece out of the function and manually change the input from the for loop to an example the assign function works. Here is an example of the code:
library(readxl)
Load<-function(File_Path,Samp){
  setwd(File_Path)
  for (i in 1:length(Samp)){
    assign(paste("Sample_",Samp[i],sep = ""),read_excel(paste("Sample_",Samp[i],".xlsx",sep = "")))
  }
}
Load(File_Path = "~/Desktop/Test",Samp = "A") # Doesn't Work

#When this piece is taken out of the loop and the Sample ("A") replaced it works.
assign(paste("Sample_","A",sep = ""),read_excel(paste("Sample_","A",".xlsx",sep = ""))) # Does Work

In reality there is a long list of samples to load and want to do so by assigning a list to "Samp" such as c("A","C","D"). Thanks up front for any assistance.

A: You can fix your problem by adding inherits=TRUE to assign


text:
Q: Capacitors in Series - common node
I'm a bit confused on the sign of charges in circuits like these.
The bottom (negative) plate of C1 has -Q charge and the top plate (positive) of C2 has +Q charge. However, these two plates are at the same node, so they are the same plate essentially.
How can they have a different charge each???

A: The +/- represents the voltage relative only to the capacitor's other plate only.
If I am standing on your head, our feet are always below our heads, but that doesn't mean my feet and your head can't be at the same height.
The voltage potential at the bottom plate of C1 is not different than the potential in the top plate of C2. This is different than the charge on each plate.
If I have a large and small air tank and connect them together, their pressure (voltage) will be the same but their air volume (charge) won't be. In the same way, the larger plate of a larger cap needs more charge to produce the same voltage than a smaller plate.

A: It is an electrostatic behavior as shown below,

Does this make sense? Comparing to

A: The C1 and C2 definitely share a common node. The charge on lower plate of C1 will be negative with respect to the top plate of the C1. The same plate can be treated as positive when the lower plate of C2 is taken as reference.

A: Just remember that in electronics, when you see this type of notation, it means "with respect to the other side of the device". So the pluses on C1 are in comparison to the minuses on C1, not necessarily anything else. By looking at the design of the circuit, however, it is implied that the plus side of C1 is positive in comparison to the plus or the minus side of C2, for example.

A:
The bottom (negative) plate of C1 has -Q charge and the top plate (positive) of C2 has +Q charge. However, these two plates are at the same node, so they are the same plate essentially.
How can they have a different charge each???

In electrostatics, a conductive material will be an equipotential (the potential will be the same throughout its volume).
That doesn't mean that the charge in the material will be uniformly distributed.
If (like in this case) there's an external electric field, the charge will distribute unevenly. In fact, the charge has to re-distribute for the object to remain an equipotential.
In this case you have a metallic object (two plates joined by a wire), so the potential is the same throughout the object. But some negative charge has moved to the lower plate part of the object, leaving a net positive charge on the upper plate part of the object. This is necessary or else the whole object wouldn't be at the same potential.


text:
Q: How do I shuffle items in an array, using value as audio source in React? I fetched an array of songs from an API ,mapped over it and  used the string in the array as audio source. Currently I'm trying to add a shuffle functionality to my audio player web app but I don't know where to begin.

A: You can use Math.random() function which returns a floating-point number between 0 and less than 1 then multiply it by the length of your array and pass that number to Math.floor() function and use that final number result as the index of your array of songs.

const songs = ['1st song','2nd song','3rd song', '4th song']

const getRandomSong = max => {
  return songs[Math.floor(Math.random() * max)];
}

const randomSong = document.querySelector('.randomSong');
const btnRandomizer = document.querySelector('.btnRandomizer');
btnRandomizer.addEventListener('click', () => randomSong.textContent = getRandomSong(songs.length))
<button class='btnRandomizer'>Randomize</button>

Random song:

NOTE: this example above can seem like its "stuck" at some point, but that's just the way it works for example it can result number 2 twice or 10 or more times in a row.
That's why below I've created another example where I'm storing that randomized value(randomNum) to a global variable (in the outer scope)(prevNum).

const songs = ['1st song', '2nd song', '3rd song', '4th song']

let prevNum;
const getRandomSong = max => {
  const randomNum = Math.floor(Math.random() * max)
  if (prevNum === randomNum) {
    let newRandomNum = randomNum === 0 ? randomNum + 1 : randomNum - 1
    prevNum = newRandomNum;
    return songs[newRandomNum];
  } else {
    prevNum = randomNum;
    return songs[randomNum];
  }
}

const randomSong = document.querySelector('.randomSong');
const btnRandomizer = document.querySelector('.btnRandomizer');
btnRandomizer.addEventListener('click', () => randomSong.textContent = getRandomSong(songs.length))
<button class='btnRandomizer'>Randomize</button>

Random song:

Further explanation if you are interested is the part of initializing newRandomNum using the ternary operator as to avoid possible issue if you were to simply use +1 or -1 you may encounter a case scenario where you are trying to access an element above the index of the last element in your array or an index below 0 which in both cases would resolve to undefined.


text:
Q: ECS get image from QUAY.io and spin ec2Spot: Infinitely waiting for task to start - desiredCount = 1, pendingCount = 0 I've set up pipeline which talks to ECS and spins EC2Spot instance.
Getting stuck on following message
PRIMARY  task ******:5 - runningCount = 0 , desiredCount = 1,  pendingCount = 0

Which basically means that I'm waiting for task to start, but something is off in a set up and it never gets started. Any suggestions on where to look?
Note:

*

*This is a testing app which spins up a browser so no ports required

*No load balancer

*Possibly quay.io integration miss, but cant figure out with no logs

*CloudTrail log is empty with only success messaged upon taskDefinition create and update
Thanks

A: About 8 hours of hammering head of the wall and this issue was solved.
Long time ago, by this fella - https://stackoverflow.com/a/36533601/5332494
Steps that It took me to figure it out.

*

*Look in the CloudTrail => Event history => Even name column(UpdateService) => click on View event => Find error message(was unable to place a task because no container instance met all of its requirements. Reason: No Container Instances were found in your cluster. For more information, see the Troubleshooting section of the Amazon ECS Developer Guide) there which will take you to https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-event-messages.html#service-event-messages-1

*Page in a link above specifies possible issues you are having if you got same message as I(see step 1). First option on that page:

No container instances were found in your cluster

took me to https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_container_instance.html

*That's where I've added docker instance to my ecs cluster and finally was able to add ec2 Spot instance through codefresh pipeline talking to ecs.

Notes:
Ecs had to talk to QUAY.io to pull docker image from their private registry. And all I had to do is create secret in AWS secret manager with default following format
{ "username": "your-Quay-Username",
  "password": "your-Quay-password"
}

That's it :)


text:
Q: Msocaf Report error in memory management /spdispose check I have a piece of code on which when I am running MSoCaf, its giving a error under memory management/spdisposechaeck. But there is no
particular description of error and its saying "Call to Microsoft.SharePoint.Administration.SPSiteCollection.get_Item and no variable to catch return value" as resolution. Can anyone please tell me what would be the expected cause of the error?
Thanks in advance

A: After doing some poc I found the answer.
rootsite = SPContext.Current.Web.Site.WebApplication.Sites[0].Url;
this type of line where a site is opened by not disposed properly msocaf gives the above mentioned error.


text:
Q: When to define SDD(System Sequence Diagram) operations System->Actor? I am having some trouble understanding how to make System Sequence Diagrams, as I don't fully grasp why in some cases one should define operations for System -> Actor and in others don't. Here is an example:
Let's assume the System is a Cinema Ticket Store and the Actor is a client that wants to buy a ticket.
1) The User tells the System that wants to buy some tickets, stating his client number.
2) The System confirms that the given client number is valid.
3) The User tells the System the movie that wants to see.
4) The System shows the set of available sessions and seats for that movie.
5) The System asks the user which session/seat he wants.
6) The User tells the System the chosen session/seat.

This would be converted to:
a) -----> tellClientNumber(clientNumber)
b) <----- validClientNumber
c) -----> tellMovieToSee(movie)
d) <----- showsAvailableSeatsHours
e) -----> tellSystemChosenSessionSeat(session, seat)

I know that when we are dealing with SDD's we are still far away from coding. But I can't help trying to imagine how it how it would have been had I to convert it right away to code:
I can understand 1) and 2). It's like if it was a C#/Java method with the following signature:
boolean tellClientNumber(clientNumber)

so I put both on the SDD.
Then, we have the pair 3) 4). I can imagine that as something as:
SomeDataStructureThatHoldsAvailableSessionsSeats tellSystemMovieToSee(movie)

Now, the problem:
From what I've come to understand, my lecturer says that we shouldn't make an operation on the SDD for 5) as we should only show operations from the Actor to the System and when the System is either presenting us data (as in c)) or validating sent data (such as in b)).
I find this odd, as if I try to imagine this like a DOS app where you have to put your input sequencially, it makes sense to make an arrow even for 5). Why is this wrong? How should I try to visualize this?
Thanks

A: You haven't defined what your system is, and you're not being clear what stage of design you are in, so it's a little hard to answer.
If you instead imagine something like the systems for booking trains on the web, the screen which shows the times just has checkboxes next to them for the user to select which one they want, rather than the system prompting the user - the user initiates the next step on receipt of the data. So it is perfectly possible for a user interface to allow the user to select from just the data without an extra prompting.
If you are doing preliminary design of a system, try and avoid making assumptions about user interfaces, and only include essential use cases. You'd only need the 'print a prompt for the user' use  case if you were designing the DOS UI component; it wouldn't be a use case in a web based system.
So the problem isn't that you have some use cases with interactions between the user and system and some with none. The problem is that some of your use cases are assuming a particular UI implementation detail which is not essential for the system to function, and should not be in the top-level design.


text:
Q: What's the general way to remove "The name xxx does not exist" error when we recompile unity3d C# dll? As we know there are multiple ways to decompile Unity3d DLL files to reverse engineering the C# source code via ( dotpeek, ILSpy and Reflector )
Example: [Target File] Unity3D_Game_RootPath/Managed/Assembly-CSharp.dll

*

*Assembly-CSharp.dll  => (one of the above tools) => Export/Save to .sln

*C# project file extention .sln => open in visualStudio

*Switch to "Solution Explorer" to check and add all necessary References
(libraries to be included, like System, UnityEngine.dll, UnityEngineUI.dll, etc....)

*Passing Step 3 will remove most of the reference Errors (red hightlights in IDE)

However, usually the decompiled source code still contains a lot of error patterns below:
Example:

iTween.<>f__switch$mapA == null

error type I  :  the name 'xxx' does not exit   (CS1513)
error type II :  Unexpected character '$'
would like to know what is the cause of the above general errors through the decompile process mentioned above and what would be a general way to remove them.
The Final Goal of the above process is try removing recompile errors and successfully recompile the source code generated from C# decompile Tools ( dotpeek, ILSpy and Reflector ) into runable dll to replace the old one.


text:
Q: Firebase real-time-database structure doubts I am new to nosql and firebase real-time-database and I have a question about the structure of database.
1,
For example if I structured my database in this way
user-
     user1-
           info-
                followers-
                           user2
                           user3
                           user4
           posts-
                 ...

If i access the follower information user using :
ref.child('users').child('user1').child('info').child('followers')
firebase will only download the child nodes of follwers right? It will not download the other nodes to the user, is that correct?
2,
If I retrieve data using :
ref.queryOrdered(byChild:"index").queryStarting(atValue:start).queryEnding(atValue: end)
Only data between the starting index and the end index will be downloaded to the user end right?

A: *

*Yes

*Yes. That's how it's defined according the documentation for queryStarting() and queryEnding().  Note that the start and end values are inclusive, meaning any records with values that are equal to the start and end values will be part of the results.


text:
Q: About finding a Stack Exchange society for empowering a women's rights society I am a member of a Clubhouse club which is working on feminism and social support for women and girls in a traditional society. In this club people have friendly discussions about the societal problems of Iran and share their view points for solving these problems.
The leader of this club is a lovely girl who gives us valuable energy and time to take care of the club members.
During the months I have been in this club, I have seen her attempts to help people and give them information, but I know managing a 1k member club is so hard and, as women's rights activities in the dictatorial government of Iran, I have seen some threats and pressure on her network and friends, especially those residing in Iran.
So if possible, I need to find some SE site to ask about useful strategies for empowering her network, to decrease the pressure on her and give new resources and backups as support for women's social activities.
One of these support is finding some English community to ask questions about those challenges.
Also, if possible, I would like to know about other alternative Internet websites instead of SE sites.

A: The whole Stack Exchange network is open to you.
Money questions could be asked on https://money.stackexchange.com, for legal issues on https://law.stackexchange.com, for travel issues on https://travel.stackexchange.com, for programming on Stack Overflow, for information security on https://security.stackexchange.com.
There are also sites about psychology (https://psychology.stackexchange.com), interpersonal skills (https://interpersonal.stackexchange.com) or everyday life hacks (https://lifehacks.stackexchange.com). There is a site about politics (https://politics.stackexchange.com) and they have an activism tag.
And for education there is for example https://matheducators.stackexchange.com.
I could imagine them all to be helpful for you to overcome the challenges you might face. The best is probably to use them all.
However, the question must always be on-topic on the respective site and typically the community aspect of the single sites is not so emphasized. It's more transactional, like question and answer to question only. The chat functionality on the respective sites might more closely resemble a community...

A: We have a site dedicated to Community Building which might be a good fit. Please check their Help Center to make sure it fits, and it's best to avoid questions which are too open ended. And it's one of the quietest sites in the network, so don't be too disappointed if you don't receive a good answer.


text:
Q: Does the ObjectDataSource just really suck? I've never had the need to really ever use any of the .NET Data sources other than the SiteMap datasource however I'm trying to take advantage of the built in CRUD operations on a control which needs to be assigned a data source to correctly work.
As I've been working through information online about implementing the ObjectDataSource and its related classes I've realized what was so glaringly unsettling about it, the fact it drives off basically a static class that is supposed to magically be able to handle the CRUD operations of a type. Once this dawned on me I couldn't see anyway to correctly design these adapters so they don't bleed concern like a hemophiliac.
The only ideas I've come up with is if the class leverages the Service Locator pattern inside each of it's operations to get the correct class for doing the actual CRUD. Which would be somewhat doable by just using .Resolve from an inversion of control container, however this seems like then I would just be shifting the concern to an even less obvious place by needing to do lots of magic with my IOC framework to always resolve the correct instance of the data proxy.
All I really need the adapter to do is to mediate calls to apply CRUD operations to ViewState backed IList<MyBizObject>.
After doing some more pondering on this as I've been writing the question I started to think about how I use the Model-View-Presenter pattern for logic separation my first solution I see is since my Presenter class has a property for my View on it that I could use Container.Resolve<Presenter>() which would give me access to my View which would give me access to my ViewState backed field and to create a class for each presenter that needs it's view to have an ObjectDataSource.
Does anyone else have any input or alternatives than my last thoughts on this?

A: To answer my own question, yes it just really sucks. However with service locator pattern it's possible to expose your stateful page viewstate or any other type of stateful repository to a stateless object datasource provider class.


text:
Q: Rails notice using unobtrusive javascript I need write some unobtrusive javascript code to show the jquery gritter message.
I need to show it when I create a

element in my page
This is the code to create te gritter dialog:
$.gritter.add({
    title: 'The title',
    text: notice text here...,
    class_name: 'gritter-success'
});


text:
Q: Replace newlines with a space in all files in a directory - Python I have about 4000 txt files in a directory. I'd like to replace newlines with spaces in each file using a for loop. Actually, the script works for that purpose but when I save the file, it doesn't get saved or it gets saved with newlines again. Here is my script;
import glob
path = "path_to_files/*.txt"
for file in glob.glob(path):
    with open(file, "r+") as f:
        data = f.read().replace('\n', ' ')
        f.write(data)

As I said I'm able to replace the newlines with a space, but at the end, it doesn't get saved. I also don't get any errors.

A: To further elaborate my comment ("It's almost always a bad idea to open a file in the 'r+' mode (because of the way the current position is handled). Open a file for reading, read the data, replace the newlines, open the same file file for writing, write the data"):
for file in glob.glob(path):
    with open(file) as f:
        data = f.read().replace('\n', ' ')
    with open(file, "w") as f:
        f.write(data)

A: You need to reset file position to 0 with seek and then truncate the leftover with truncate after you finishing writing the replacement string.
import glob
path = "path_to_files/*.txt"
for file in glob.glob(path):
    with open(file, "r+") as f:
        data = f.read().replace('\n', ' ')
        f.seek(0)
        f.write(data)
        f.truncate()


text:
Q: Javascript FileReader hangs at readyState 1 (using react-dropzone) Using the wonderful react-dropzone module I am attempting to read a dropped file with a FileReader before placing it in the redux store and sending it to the server. However, the events on the reader never trigger and I can't find out why not. Hope someone can help.
For curiosity, here's the onDrop handler I give the react-dropzone component:
const onDrop = (accepted, rejected) => {
        if(rejected.length > 0) {
            return console.error('Dropzone rejected:', rejected)
        }

        onChange(accepted[0])
    }

Here's my current onChange function:
const onChange = (file) => {

    file instanceof Blob === true
    file instanceof File === true

    var reader = new FileReader()

    reader.onload((event) => {
        console.log(event)
    })

    reader.onerror((event) => {
        console.log(event)
    })

    reader.readAsText(file)
}

Looking at the documentation and many posts on stackoverflow, the above should be right. The reader indeed changes its readyState to 1 and result to "". Yet, when I log the reader it never continues to readyState 2 nor does it ever trigger any events, also no error event.
Could there be somehting wrong with the file?

A: Looks like a typo: should be .onload instead of .onLoad.
example from the docs (note the = sign):
reader.onload = function(event) {
    // The file's text will be printed here
    console.log(event.target.result)
  };

A: According to the docs, onload is a property of the FileReader:
var reader = new FileReader();

reader.onload = event => {
    console.log(event)
};

reader.readAsText(file);


text:
Q: How to center text without using any layout? import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextBoundsType;
import javafx.stage.Stage;

public class HorizontalTextAlignment extends javafx.application.Application {

    @Override
    public void start(Stage stage) {
        var rectangle = new Rectangle(600, 100, Color.TURQUOISE);
        var text = new Text(rectangle.getWidth() / 2, rectangle.getHeight() / 2, "TEXT");
        text.setBoundsType(TextBoundsType.VISUAL);
        text.setFont(new Font(100));
        text.setTextAlignment(TextAlignment.CENTER);
        text.setTextOrigin(VPos.CENTER);
        stage.setScene(new Scene(new Pane(rectangle, text)));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I would need to center the text without using any layout. As you may notice, while vertical alignment works, horizontal doesn't. Of course, this could be solved by a simple calculation.
// You need to change the horizontal position of the text for this to work.
var text = new Text(rectangle.getLayoutX(), rectangle.getHeight() / 2, "TEXT");
...
var rectangleWidth = rectangle.getWidth();
var textWidth = text.getLayoutBounds().getWidth();
text.setLayoutX((rectangleWidth - textWidth) / 2);

The problem is, although it's not easy to see in the picture that it's not exactly in the middle.
This is good to see if you only change the initialization.
var text = new Text(rectangle.getLayoutX(), rectangle.getHeight() / 2, "TEXT");

However, this cannot be solved by simply subtracting the desired value (in this case -2) from the horizontal position, because when I change the text.

It is necessary to subtract 9. And that is the problem. I can never know in advance how much must be deducted from the horizontal position.
How do I solve this, please?
Thank you

A: If are not forced to use those specific Nodes, I would use Label instead of Text and StackPane instead of Pane:
Rectangle rectangle = new Rectangle(600, 100, Color.TURQUOISE);

Label label = new Label("TEXT");
label.setAlignment(Pos.CENTER);
label.setFont(new Font(100));

StackPane.setAlignment(label, Pos.CENTER);
StackPane.setAlignment(rectangle, Pos.CENTER);

StackPane pane = new StackPane(rectangle, label);

pane.prefWidthProperty().bind(rectangle.widthProperty());
pane.prefHeightProperty().bind(rectangle.heightProperty());

stage.setScene(new Scene(pane));
stage.show();

Update
Given that you cannot use StackPane, here is a solution completely out of the box.
You can create a new Shape subtracting the Text from a Rectangle. Then you will have two Rectangles, one with the text transparent and another one for the background (that will give color to the text).
The benefit of these approach is that you end with two Shapes with the same bounds and will be easier to layout in the Scene.
import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextBoundsType;
import javafx.stage.Stage;

public class App extends Application {

    @Override
    public void start(Stage stage) {

        Rectangle rectangle = new Rectangle(600, 100);

        Text text = new Text("TEXT");

        text.setTextAlignment(TextAlignment.CENTER);
        text.setBoundsType(TextBoundsType.VISUAL);
        text.setFont(new Font(100));
        text.setTextOrigin(VPos.CENTER);

        text.setX(rectangle.getWidth() / 2 - text.getLayoutBounds().getWidth() / 2);
        text.setY(rectangle.getHeight() / 2);

        Shape shape = Shape.subtract(rectangle, text);

        shape.setFill(Color.TURQUOISE);

        shape.layoutXProperty().bind(rectangle.layoutXProperty());
        shape.layoutYProperty().bind(rectangle.layoutYProperty());
        shape.translateXProperty().bind(rectangle.translateXProperty());
        shape.translateYProperty().bind(rectangle.translateYProperty());

        stage.setScene(new Scene(new Pane(rectangle, shape)));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

A: This could all be accomplished much more easily by using a StackPane (e.g. as shown in @Oboe's answer). Using the appropriate layout should always be your first choice. However, the rest of my answer shows how to do it manually.

The x and y properties define the origin point of the text node. The x-coordinate determines where the left side of the text starts. However, the y-coordinate can be customized somewhat via the textOrigin property.
                   X (always)
                   |
Y (VPos.TOP)-------╔════════════════════════════════╗
                   ║                                ║
Y (VPos.CENTER)----║          Text Node             ║
                   ║                                ║
Y (VPos.BOTTOM)----╚════════════════════════════════╝

Note: There's also VPos.BASELINE (the default) but I don't know how to visualize that.
As you can see, when you set the x property to rectangle.getWidth() / 2 you are aligning the left side of the text node with the horizontal center of the rectangle. If you want to align the horizontal center of the text node with the horizontal center of the rectangle you have to take the width of the text node into account. Here's an example:
import javafx.application.Application;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextBoundsType;
import javafx.stage.Stage;

public class App extends Application {

  @Override
  public void start(Stage stage) {
    var rectangle = new Rectangle(600, 100, Color.TURQUOISE);

    var text = new Text("TEXT");
    text.setBoundsType(TextBoundsType.VISUAL);
    text.setFont(new Font(100));
    text.setTextAlignment(TextAlignment.CENTER);
    text.setTextOrigin(VPos.CENTER);

    // WARNING: Assumes Rectangle is at (0, 0)
    text.setX(rectangle.getWidth() / 2 - text.getLayoutBounds().getWidth() / 2);
    text.setY(rectangle.getHeight() / 2);

    stage.setScene(new Scene(new Pane(rectangle, text)));
    stage.show();
  }
}

Notice that I set the x property after setting everything else (e.g. font, text, etc.). That's necessary for the resulting text's width to be known. Of course, this is not responsive; if the the dimensions of the rectangle or text change you have to manually recompute the new x value. The ideal solution, when we ignore layouts, is to use a bindings. Something like:
// WARNING: Assumes Rectangle is at (0, 0)
text.xProperty()
    .bind(
        Bindings.createDoubleBinding(
            () -> rectangle.getWidth() / 2 - text.getLayoutBounds().getWidth() / 2,
            rectangle.widthProperty(),
            text.layoutBoundsProperty()));

Unfortunately, changing the x property changes the layout bounds of the text and the above leads to a StackOverflowError. The same is true of the text's bounds-in-local (this is a characteristic of shapes). There is a solution though if you don't mind positioning the text via its layoutX and layoutY properties:
// WARNING: Assumes Rectangle is at (0, 0)

// leave text.x = 0 and text.y = 0
text.layoutXProperty()
    .bind(
        Bindings.createDoubleBinding(
            () -> rectangle.getWidth() / 2 - text.getLayoutBounds().getWidth() / 2,
            rectangle.widthProperty(),
            text.layoutBoundsProperty()));
// assumes textOrigin = VPos.CENTER
text.layoutYProperty().bind(rectangle.heightProperty().divide(2));

Note the layoutX and layoutY properties come from Node. They're used by layouts to position their children. But since you're not using a layout which automatically positions its children you can safely set them manually. There's also the translateX and translateY properties. These add onto the layout properties. For example, ignoring other things, the final x-position will be layoutX + translateX (similar for the final y-position); for a Text node the final x-position would be x + layoutX + translateX (again, similar for the final y-position).
You may have noticed that all my examples warn about assuming the rectangle is at the origin of its parent. To fix that issue you simply have to add the rectangles x and y positions to the text's layout position.

A: Instead of a Text object, you can use a Label with its alignment set to center the text.  Then you just need to force the Label's minimum width to match the parent's width (which is, roughly, mimicking what some layouts do):
@Override
public void start(Stage stage) {
    var rectangle = new Rectangle(600, 100, Color.TURQUOISE);
    var text = new Label("TEXT");
    text.setFont(new Font(100));
    text.setAlignment(Pos.CENTER);
    Pane pane = new Pane(rectangle, text);
    text.minWidthProperty().bind(pane.widthProperty());
    text.minHeightProperty().bind(pane.heightProperty());
    stage.setScene(new Scene(pane));
    stage.show();
}


text:
Q: need help writing a sql query with multiple join conditions i have a sql query currently with a multiple inner join
select game_id, start_time_utc, t.name from games g
inner join teams t
on g.home_team_id = t.team_id
or g.away_team_id = t.team_id

the problem is i want t.name for both the home_team_id and the away_team_id however it is just giving the first instance with his home_team_id
how do i modify the sql query so i get back both the home team name and the away team name

A: You need to join the table twice.
select game_id, start_time_utc, t.name as home_team_name, t2.name as away_team_name
from games g
inner join teams t on g.home_team_id = t.team_id
inner join teams t2 on g.away_team_id = t2.team_id

A: You could select each team name using a correlated subquery:
select g.game_id, g.start_time_utc,
    (select name from teams t where t.team_id=g.home_team_id) HomeTeam,
    (select name from teams t where t.team_id=g.away_team_id) AwayTeam
from games g;


text:
Q: How do I make [\makeindex] work fully on my WinXP system (works on a different system) I cannot create glossaries on my WinXP setup of MiKTeX 2.8, which I installed about half a year ago together with a TeXnicCenter from a distribution that I downloaded from TUG. The document does compile correctly on my friend's LaTeX setup (on a Linux computer), so as far as I can tell the code is correct, but something is wrong with my compiler. The following three lines appear in the Output Window of TeXnicCenter:

Couldn't find input index file C:\Test-mapp\Testfil nor
C:\Test-mapp\Testfil.idx.

Usage: C:\Program Files\MiKTeX 2.8\miktex\bin\makeindex.exe
[-ilqrcgLT] [-s sty] [-t log] [p num] [idx0 ix1 ...]

Scanning style file
C:/Test-mapp/Testfil.ist...........................done (27 attributes
redefined, 0 ignored).

In my document, I have the following lines:
\usepackage{glossaries} % this is in the preamble

\makeglossaries % also in the preamble

\printglossaries % in one of the sections of the document

Since the document compiles on my friend's system, I am quite sure that the problem is with my compiler, not the LaTeX code. Do you have any suggestions on what is happening or what I can do to solve this? Other functions of the glossaries package do work also on my system, like for example the use of abbreviations, so I do have the package installed. It is only \makeindex that does not work.
edit:
Thank you for your input. The code below does not generate any glossaries on my system, and I believe it should.
\documentclass{article}

\usepackage{glossaries}

\newacronym{SEM}{SEM}{scanning electron microscope}

\newacronym{TEM}{TEM}{transmission electron microscopy}

\newacronym{UHV}{UHV}{ultra-high vacuum}

\makeglossaries

\begin{document}

\section{First Section}

\label{Intro}

Intro

\section{List of variables}

\label{LoV}

\printglossaries

\end{document}

A: Paulo is correct in the comments above. You need an external program (makeglossaries or makeindex) to generate the glossary data. Also, you failed to use any of your acronyms in your document, so they were never put in the glossary list. The following document works:
\documentclass{article}
\usepackage{glossaries}

\newacronym{SEM}{SEM}{scanning electron microscope}
\newacronym{TEM}{TEM}{transmission electron microscopy}
\newacronym{UHV}{UHV}{ultra-high vacuum}

\makeglossaries

\begin{document}
\section{First Section} \label{Intro}

Intro. At some point, we used a \gls{SEM}.

\section{List of variables} \label{LoV}

\printglossaries
\end{document}

with the a TeXnicCenter build profile similar to the following (adjust paths to makeindex as needed -- I just copied an existing build profile to make this one):

Make sure that Makeindex runs from TeXnicCenter, and has the arguments

"%tm".glo -t "%tm".glg -s "%tm".ist -o "%tm".gls

yielding a PDF


text:
Q: Why is it incorrect to integrate both sides of $\frac{dy}{dx}=y$ to get $y=\frac{y^2}{2}+c$? I know that when we have the D.E. $\frac{dy}{dx}=y$, we divide by $y$, and after integration we get the answer we all know. Supposedly, integrating both sides of an equation should return a true statement about the function at hand. But, when we integrate directly $$\frac{dy}{dx}=y$$
we get
$$y=\frac{y^2}{2}+c$$ which is not true for $y=e^x$.
What is the error in integrating both sides of the equation?
When I have $\frac{dy}{y}=dt$ I am also integrating on different variables on each side.

A: To integrate the right side properly with respect to $y$, you need to treat $x$ as if it were dependent on $y$.
$$\frac{dy}{dx} = y \implies \frac{dx(y)}{dy} = \frac1y \implies \int \frac{dx(y)}{dy}\,dy = \int\frac{dy}y \implies x(y) = \ln|y| + C$$
Then solving for $y$ as a function of $x$,
$$x = \ln|y(x)| + C \implies \ln|y(x)| = x+C \implies y(x) = e^{x+C} = Ce^x$$

A: On the RHS you will get integration of $y$ with respect to $x$ but how can you integrate $y$ with respect to $x$ unless you can express $y$ as a function of $x$.

A: The integration process  $\int f\ dx$ encountered here (while solving an ODE) precisely requires $f$  to be the function in variable $x$. The things like $\int f(y)dx$ or $\int f(y)dx$ is meaningless; unless $f$ is a function of two variables $x$ and $y$ which you generally encounter in solving a partial differential equation.

A: $$\frac{dy}{dx}=y$$
Detail steps of integration :
$$\int \frac{dy}{dx}dx=\int y\:dx$$
$$\int dy=\int y\:dx$$
$$y=\int y\:dx$$
Your mistake is to write $\quad \int y\:dx=\frac12 y^2+c\quad$ which is false
because $\quad  \frac12 y^2+c=\int y\:dy\quad$ which is not $\int y\:dx$ .
$$\boxed{\int y\:dx\neq \int y\:dy}$$
You can correctly integrate in expressing $\int y(x)dx$ or alternatively $\int x(y)dy$. How to correctly proceed is already shown in the other answers. No need to repeat it here.

A: A rigorous way to solve this ODE is the following:
$$
y'(x)=y(x) \quad\Longleftrightarrow\quad
\mathrm{e}^{-x}y'(x)-\mathrm{e}^{-x}y(x)=0
\quad\Longleftrightarrow\quad
\big(\mathrm{e}^{-x}y(x)\big)'=0
$$
which means that the function $\mathrm{e}^{-x}y(x)$ is constant, i.e., there exists a $c\in\mathbb R$, such that
$$
\mathrm{e}^{-x}y(x)=c \quad\Longleftrightarrow\quad
y(x)=c\,\mathrm{e}^{-x}.
$$


text:
Q: How to check if a date is between other dates? I get two dates from GET
$start = $_GET['start'];
$end = $_GET['end'];

I then convert them into dates:
$start  = \DateTime::createFromFormat('d-m-yy', $start);
$end  = \DateTime::createFromFormat('d-m-yy', $end);

If I var_dump them I get
object(DateTime)#8260 (3) { ["date"]=> string(26) "2019-02-01 18:05:42.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
object(DateTime)#7967 (3) { ["date"]=> string(26) "2019-02-05 18:05:42.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

I then loop my posts and in a custom field I have a date, which is a string, therefore I convert it into a date:
foreach($posts as $post) {
   $myDate = \DateTime::createFromFormat('d-m-yy', usp_get_meta(false,'usp-custom-80'));

And if I vur_dump that I get
object(DateTime)#8457 (3) { ["date"]=> string(26) "2000-03-20 18:07:28.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

Then I finally do:
if ( ( $myDate >= $start) && ( $myDate <= $end) ) {
....

But I don't get the correct results as if that conditions isn't working at all

A: You can try that:
if ( ( $myDate->getTimestamp() >= $start->getTimestamp()) && ( $myDate->getTimestamp() <= $end->getTimestamp()) )

A: You can compare seconds from Unix epoch start.
if ( ($start->format('U') <= $myDate->format('U'))
    && ( $myDate->format('U') <= $end->format('U'))) {
    // date is between start and end
}


text:
Q: Finding differentiability of a function. Help? $ f(x) = |x| + |x+1| + |x-2|$
I need to find if this is differentiable at x=1.
How do I solve a question like above to find differentiability?
Now I have come across two different formulas to find left hand derivative.
$\lim\limits_{h \to 0} \frac{f(x-h) - f(x)}{-h}$
$\lim\limits_{h \to 0-} \frac{f(x+h) - f(x)}{h}$
Which one of the above is correct one?
If both are correct, how is that possible?

A: We don't need to find left hand derivatives in this question. We just need to analyse the given function for $x=1+h$ with $h$ small. So
$$f\left(1+h\right)=\left\lvert1+h\right\rvert+\left\lvert2+h\right\rvert+\left\lvert-1+h\right\rvert$$
Since $h$ is small, $1+h,2+h$ will be positive and $-1+h$ will be negative. So, using the definition of absolute value,
we have
$$f\left(1+h\right)=1+h+2+h-\left(-1+h\right)=4+h=f\left(1\right)+h$$
So we see that $$\frac{f\left(1+h\right)-f\left(1\right)}h=1$$ for all small $h$. So when we take the limit $h\to0$, the limit exists, and so $f$ is differentiable at $x=1$. Now, the definition of left hand derivative is
$$\lim\limits_{h\to0^+}\frac{f\left(x-h\right)-f\left(x\right)}h$$ where $h\to0^+$ means take the limit $h\to0$ from the positive direaction. However, taking $h\to0$ from positive direction is same as taking $-h\to0$ along negative. So we can rewrite as
$$\lim\limits_{-h\to0^-}\frac{f\left(x+\left(-h\right)\right)-f\left(x\right)}h$$
Now, renaming $-h$ as $h$, we obtain the second definition
$$\lim\limits_{h\to0^-}\frac{f\left(x+h\right)-f\left(x\right)}h$$
Sence your two definitions of left hand derivative are equal. however, we do not need that to answer this question.

A: Since the absolute value is defined by cases,
$$|x|=\left\{\begin{array}{ll}
x & \text{if }x\geq 0;\\
-x & \text{if }x\lt 0,
\end{array}\right.$$
$$|x+1|=\left\{\begin{array}{ll}
x+1 & \text{if }x\geq -1;\\
-x-1 & \text{if }x\lt -1,
\end{array}\right.$$
$$|x-2|=\left\{\begin{array}{ll}
x-2 & \text{if }x\geq 2;\\
2-x & \text{if }x\lt 2,
\end{array}\right.$$
near $x=1$ we have
$$f(x)=x+(x+1)+(2-x)=x+3.$$
To find if $f(x)$ is differentiable at $x=1$, use the definition of the derivative:
$$\lim_{h\to 0}\frac{f(x+h)-f(x)}{h},$$
$$\text{at x=1:}\quad\lim_{h\to 0}\frac{f(1+h)-f(1)}{h},$$
$$\lim_{h\to 0}\frac{(4+h)-4}{h}=1.$$
Therefore, $f(x)$ is differentiable as $x=1$ since we have shown that $f'(1)=1$.


text:
Q: Suggest some efficient algorithm in linear time You have an array A of length N consisting of positive integers. Let's consider N vertical segments (parallel to y axis) on the plane, the i-th segment connects the points (i, 0) and (i, Ai).
You have Q queries of following two types:
+ i X : Ai += X
? i L R: Let's consider R - L + 1 rays which are parallel to x axis. The j-th ray eminates at point (i - 0.5, L+ j - 1.5) and extends to the right infinitely long parallel to x axis. You have to print the number of the segments that will be shot by some ray. If a ray shoots a segment then it stops at that point and does't extend further.
Note that all the queries of the second type are independent of each other.
Code I tried produces right result but not much efficient:
int main()
{
    int T;
    int k;
    cin>>T;
    long int N,Q;
    for(k=0;k<T;k++)
    {
        cin>>N>>Q;
        vector<long int> v;
        v.push_back(-1);
        long int i=0,p;
        for(i=0;i<N;i++)
        {
            cin>>p;
            v.push_back(p);
        }
        for(long int j=0;j<Q;j++)
        {
            char c1;
            cin>>c1;
            if(c1=='+')
            {
                long int i;
                int X;
                cin>>i>>X;
                v[i] = v[i] + X;
            }
            else
            {
                long int L,R,i;
                cin>>i>>L>>R;
                long int count=0,max=-100000;
                for(long int l=i;l<=N;l++)
                {
                    if(v[l]>=L && v[l]>max)
                    {
                        max=v[l];
                        count++;
                        if(max>=R)
                            break;
                    }
                }
                cout<<count<<endl;
            }
        }
    }
}

T is here no of test cases.N is total no of elements in the array. Q is the no of queries on that array.  So what I need is a better algorithm to do the same job that I did.


text:
Q: node nx env vars work with serve not build I'm assuming there's something simple I'm missing because I'm new to this tool.
I'm using "nx": "14.8.2",
I have apps/api/.env with NX_API_PORT=5000
This works when I use the api:serve command, but run the built code from a dev build to test it with node dist/apps/api/main.js the api port is undefined and my || fallbackPort is used.
I tried some of the other .env file naming patterns from their docs but no luck.
I would rather use the environment.ts files from apps/app-name/src/environments, but I have a libs/shared/api/data-access lib that exports methods to call my apps/api, so this lib needs the apps/api env vars to build the base url differently between dev and prod.


text:
Q: Django Rest Framework - How to test ViewSet? I'm having trouble testing a ViewSet:
class ViewSetTest(TestCase):
    def test_view_set(self):
        factory = APIRequestFactory()
        view = CatViewSet.as_view()
        cat = Cat(name="bob")
        cat.save()

        request = factory.get(reverse('cat-detail', args=(cat.pk,)))
        response = view(request)

I'm trying to replicate the syntax here:
http://www.django-rest-framework.org/api-guide/testing#forcing-authentication
But I think their AccountDetail view is different from my ViewSet, so I'm getting this error from the last line:
AttributeError: 'NoneType' object has no attributes 'items'

Is there a correct syntax here or am I mixing up concepts? My APIClient tests work, but I'm using the factory here because I would eventually like to add "request.user = some_user". Thanks in advance!
Oh and the client test works fine:
def test_client_view(self):
    response = APIClient().get(reverse('cat-detail', args=(cat.pk,)))
    self.assertEqual(response.status_code, 200)

A: I think it's your last line. You need to call the CatViewSet as_view(). I would go with:
response = view(request)

given that you already defined view = CatViewSet.as_view()
EDIT:
Can you show your views.py? Specifically, what kind of ViewSet did you use? I'm digging through the DRF code and it looks like you may not have any actions mapped to your ViewSet, which is triggering the error.

A: I think I found the correct syntax, but not sure if it is conventional (still new to Django):
def test_view_set(self):
    request = APIRequestFactory().get("")
    cat_detail = CatViewSet.as_view({'get': 'retrieve'})
    cat = Cat.objects.create(name="bob")
    response = cat_detail(request, pk=cat.pk)
    self.assertEqual(response.status_code, 200)

So now this passes and I can assign request.user, which allows me to customize the retrieve method under CatViewSet to consider the user.

A: I had the same issue, and was able to find a solution.
Looking at the source code, it looks like the view expects there to be an argument 'actions' that has a method items ( so, a dict ).
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/viewsets.py#L69
This is where the error you're getting is coming from.  You'll have to specify the argument actions with a dict containing the allowed actions for that viewset, and then you'll be able to test the viewset properly.
The general mapping goes:
{
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
}

http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers
In your case you'll want {'get': 'retrieve'}
Like so:
class ViewSetTest(TestCase):
    def test_view_set(self):
        factory = APIRequestFactory()
        view = CatViewSet.as_view(actions={'get': 'retrieve'}) # <-- Changed line
        cat = Cat(name="bob")
        cat.save()

        request = factory.get(reverse('cat-detail', args=(cat.pk,)))
        response = view(request)

EDIT: You'll actually need to specify the required actions.  Changed code and comments to reflect this.

A: I found a way to do this without needing to manually create the right viewset and give it an action mapping:
from django.core.urlresolvers import reverse, resolve
...
url = reverse('cat-list')
req = factory.get(url)
view = resolve(url).func
response = view(req)
response.render()

A: I needed to get this working with force authentication, and finally got it, here is what my test case looks like:
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from django.db.models.query import QuerySet
from rest_framework.test import force_authenticate
from django.contrib.auth.models import User

from config_app.models import Config
from config_app.apps import ConfigAppConfig
from config_app.views import ConfigViewSet

class ViewsTestCase(TestCase):
    def setUp(self):
        # Create a test instance
        self.config = Config.objects.create(
            ads='{"frequency": 1, "site_id": 1, "network_id": 1}',
            keys={}, methods={}, sections=[], web_app='{"image": 1, "label": 1, "url": 1}',
            subscriptions=[], name='test name', build='test build', version='1.0test', device='desktop',
            platform='android', client_id=None)

        # Create auth user for views using api request factory
        self.username = 'config_tester'
        self.password = 'goldenstandard'
        self.user = User.objects.create_superuser(self.username, 'test@example.com', self.password)

    def tearDown(self):
        pass

    @classmethod
    def setup_class(cls):
        """setup_class() before any methods in this class"""
        pass

    @classmethod
    def teardown_class(cls):
        """teardown_class() after any methods in this class"""
        pass

    def shortDescription(self):
        return None

    def test_view_set1(self):
        """
        No auth example
        """
        api_request = APIRequestFactory().get("")
        detail_view = ConfigViewSet.as_view({'get': 'retrieve'})
        response = detail_view(api_request, pk=self.config.pk)
        self.assertEqual(response.status_code, 401)

    def test_view_set2(self):
        """
        Auth using force_authenticate
        """
        factory = APIRequestFactory()
        user = User.objects.get(username=self.username)
        detail_view = ConfigViewSet.as_view({'get': 'retrieve'})

        # Make an authenticated request to the view...
        api_request = factory.get('')
        force_authenticate(api_request, user=user)
        response = detail_view(api_request, pk=self.config.pk)
        self.assertEqual(response.status_code, 200)

I'm using this with the django-nose test runner and it seems to be working well. Hope it helps those that have auth enabled on their viewsets.


text:
Q: No DOM, Use regex contain betwen tag div Not use DOM, i have content in tag div and i want get only string or string and tag  inside tag .
Ex:
1.
Lorem kid lasjdfdl asjf asdl f
// true
2.
Lorem kid lasjdfdl asjf asdl f
// true
3.
Lorem
kid
 lasjdfdl asjf asdl f
// false

My regex code is /
([^<]+)<\/div>/ but true for 1. I want true for 1 and 2.
Any one please help me, Thanks

A: See Demo
^
(((?!<\/?div>).)*)<\/div>


text:
Q: How to load a CSS style sheet So I basically got my own whole css layout and I want to change the layout of my magento frontend. I've looked into this post: https://stackoverflow.com/questions/17050668/how-to-apply-css-to-magento-cms-page but it's not loading my css in. I did this:
I added to Custom Layout Update XML:
<reference name="head">
<action method="addCss"></action>
</reference>

and in my html editor I got this:

Css just in case:
.header{
width:80%;
margin-left:10%;
height:15%;

/*border-radius:12px; */
background-color:white;
}

.header_2{
width:80%;
margin-left:10%;
height:5%;
background-color:grey;
font-size:200%;
}

My style.css is in this directory:/skin/frontend/default/csstest I also tried to put it in: skin/frontend/default/default/css
Am I forgetting something?

A: Better use this syntax:
<reference name="head">
    <action method="addItem">
        <type>skin_css</type>
        <name>csstest/style.css</name>
    </action>
</reference>

A: Just curious, why are you not using a local xml and local css combo.  Also, have you updated your configuration to pull from the right design package and themes?
Its in System > General > Design >
Package should be where the files is loaded from initially.  Normally set to default theme package.  And theme is if you have created a new theme folder.  This needs to match exactly where you are loading you templates / skins / layouts and all lower case.
Lastly, I think your syntax is slightly wrong for the xml file.  Here is some more info about local xml and syntax.
https://stackoverflow.com/questions/25156808/magento-custom-css-overridden-by-parent-css-using-local-xml


text:
Q: How to determine page generation time with Struts 2? I'm using Struts 2 and I'd like to determine the page generation time without an external profiler. I can easily profile the actions execute() method, but I don't know how to include the time spent before (in dispatchers, interceptors...) and after (time taken by the servlet corresponding to the view ("jsp time")).
Is there simple way to do this ? And if there isn't, how could I, at least, profile the "jsp time" (maybe a tag I'm not aware of ?) ? I think it would be accurate enough to just take in account action time + jsp time.

A: You could use Filters before and after the call to get the time when the request comes in and the response goes out.  No profiler needed.  And you can configure the Filters in your web.xml to apply to particular URLs.
It's coarse-grained but effective.


text:
Q: Injecting modules in extended controller(ES6) causes Unknown provider error I have a controller class ModalCtrl and I want to create a child class ModalCtrlChild extends ModalCtrl. Problem is when I try to do that i get an unknown provider error in any of the modules injected in ModalCtrl.
I used this generator to build the project and it uses NgInject behind the scenes to inject the dependencies, I suspect there's something funny happening there.
ModalCtrl:
export default class ModalCtrl {
  static get UID(){
    return "ModalCtrl"
  }
  ... // all my ModalCtrl methods here

 /* @ngInject */
  constructor(ngDialog, PreoModalType, OutletService, $q, $timeout, VenueService) {
    "ngInject";
    ... // ModalCtrl constructor logic initing variables
  }
}

ModalCtrlChild:
import ModalCtrl from '../../preoModal.controller';

export default class ModalCtrlChild  extends ModalCtrl{
  static get UID(){
    return "modalCtrlChild"
  }

  /* @ngInject */
  constructor() {
    // "ngInject";
    console.log("in super constructor");
    super();
  }
}

Error:
Error: [$injector:modulerr] Failed to instantiate module function ModalCtrlChild() due to:
Error: [$injector:unpr] Unknown provider: ngDialog
http://errors.angularjs.org/1.5.3/$injector/unpr?p0=ngDialog

And ngDialog is DEFINITELY imported and working. If delete extends ModalCtrl from ModalCtrlChild I don't get any errors and my code runs fine but I'm not able to get the inheritance I need. Any ideas appreciated.
EDIT
I had tried eenagy's answer before posting the question, that doesn't work either, as the problem seems to be in the child class injects, not in the parent's class injects.
sourdoughdetzel, tried your suggestion:

*

*Removed annotation and dependencies from ModalCtrlChild

*Removed annotation and dependencies from ModalCtrl but left them in child

Got the exact same error:
Error: [$injector:modulerr] Failed to instantiate module function PreoModalController_Form() due to:
Error: [$injector:unpr] Unknown provider: ngDialog

I suspect this has to do with the way babel is constructing the extended class and is not allowing ngInject to do it's work. I'm trying to work out a way of doing manual injections here, which should solve the problem and prove that this is the issue as I do not know enough about how babel's work to fix this.

A: My guess is that ngInject is not doing what it is supposed to be doing behind the scenes when you call "super()" from a subclass' constructor. I wasn't seeing much on ngInject when searching around, but it may be getting short-circuited because of the manual call to the constructor that is happening.
If you take the dependencies into the ModalCtrlChild controller and uncomment the "ngInject" string, then pass them along to the super() call, does it work as expected?

A: The error message actually tells you what missing.
Unknown provider: ngDialog

You need to declare your dependencies in your subclass too.
So instead of this
import ModalCtrl from '../../preoModal.controller';

export default class ModalCtrlChild  extends ModalCtrl{
  static get UID(){
    return "modalCtrlChild"
  }

  /* @ngInject */
  constructor() {
    // "ngInject";
    console.log("in super constructor");
    super();
  }
}

You need to pass the parameters in.
import ModalCtrl from '../../preoModal.controller';

export default class ModalCtrlChild  extends ModalCtrl{
  static get UID(){
    return "modalCtrlChild"
  }

  /* @ngInject */
  constructor(ngDialog, PreoModalType, OutletService, $q, $timeout, VenueService) {
    // "ngInject";
    console.log("in super constructor");
    super(ngDialog, PreoModalType, OutletService, $q, $timeout, VenueService);
  }
}

There is no way that ngInject would know what dependencies are needed. How should it know? In the real world there could be dozens of subclasses of ngDialog which matches the contract and passable as a parameter. You need to specify which one is needed so it can pass it in.
As a example imagine if you have a subclass of ngDialog called ngPopupDialog.
And your example subclass. The following could be used instead of ngDialog, and would match the super.
import ModalCtrl from '../../preoModal.controller';

export default class ModalCtrlChild  extends ModalCtrl{
  static get UID(){
    return "modalCtrlChild"
  }

  /* @ngInject */
  constructor(ngPopupDialog, PreoModalType, OutletService, $q, $timeout, VenueService) {
    // "ngInject";
    console.log("in super constructor");
    super(ngPopupDialog, PreoModalType, OutletService, $q, $timeout, VenueService);
  }
}