text:
Q: How to soft delete many to many relation with Django In my Django project, all entities deleted by the user must be soft deleted by setting the current datetime to deleted_at property. My model looks like this: Trip <-> TripDestination <-> Destination (many to many relation). In other words, a Trip can have multiple destinations.
When I delete a Trip, the SoftDeleteManager filters out all the deleted trip. However, if I request all the destinations of a trip (using get_object_or_404(Trip, pk = id)), I also get the deleted ones (i.e. TripDestination models with deleted_at == null OR deleted_at != null). I really don't understand why since all my models inherit from LifeTimeTracking and are using the SoftDeleteManager.
Can someone please help me to understand why the SoftDeleteManager isn't working for n:m relation?
class SoftDeleteManager(models.Manager):
    def get_query_set(self):
        query_set = super(SoftDeleteManager, self).get_query_set()
        return query_set.filter(deleted_at__isnull = True)

class LifeTimeTrackingModel(models.Model):
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    deleted_at = models.DateTimeField(null = True)

    objects = SoftDeleteManager()
    all_objects = models.Manager()

    class Meta:
        abstract = True

class Destination(LifeTimeTrackingModel):
    city_name = models.CharField(max_length = 45)

class Trip(LifeTimeTrackingModel):
    name = models.CharField(max_length = 250)
    destinations = models.ManyToManyField(Destination, through = 'TripDestination')

class TripDestination(LifeTimeTrackingModel):
    trip = models.ForeignKey(Trip)
    destination = models.ForeignKey(Destination)

Resolution
I filed the bug 17746 in Django Bug DB. Thanks to Caspar for his help on this.

A: It looks like this behaviour comes from the ManyToManyField choosing to use its own manager, which the Related objects reference mentions, because when I try making up some of my own instances & try soft-deleting them using your model code (via the manage.py shell) everything works as intended.
Unfortunately it doesn't mention how you can override the model manager. I spent about 15 minutes searching through the ManyToManyField source but haven't tracked down where it instantiates its manager (looking in django/db/models/fields/related.py).
To get the behaviour you are after, you should specify use_for_related_fields = True on your SoftDeleteManager class as specified by the documentation on controlling automatic managers:
class SoftDeleteManager(models.Manager):
    use_for_related_fields = True

    def get_query_set(self):
        query_set = super(SoftDeleteManager, self).get_query_set()
        return query_set.filter(deleted_at__isnull = True)

This works as expected: I'm able to define a Trip with 2 Destinations, each through a TripDestination, and if I set a Destination's deleted_at value to datetime.datetime.now() then that Destination no longer appears in the list given by mytrip.destinations.all(), which is what you are after near as I can tell.
However, the docs also specifically say do not filter the query set by overriding get_query_set() on a manager used for related fields, so if you run into problems later, bear this in mind as a possible cause.

A: To enable filtering by deleted_at field of Destinantion and Trip models setting use_for_related_fields = True for SoftDeleteManager class is enough. As per Caspar's answer this does not return deleted Destinations for trip_object.destinations.all().
However from your comments we can see you would like to filter out Destinations that are linked to Trip via a TripDestination object with a set deleted_at field, a.k.a. soft delete on a through instance.
Let's clarify the way managers work. Related managers are the managers of the remote model, not of a through model.
trip_object.destinantions.some_method() calls default Destination manager.
destinantion_object.trip_set.some_method() calls default Trip manager.
TripDestination manager is not called at any time.
You can call it with trip_object.destinantions.through.objects.some_method(), if you really want to. Now, what I would do is add an Instance method Trip.get_destinations and a similar Destination.get_trips that filters out deleted connections.
If you insist on using the manager to do the filtering it gets more complicated:
class DestinationManager(models.Manager):
    use_for_related_fields = True

    def get_query_set(self):
        query_set = super(DestinationManager, self).get_query_set()
        if hasattr(self, "through"):
            through_objects = self.through.objects.filter(
                destination_id=query_set.filter(**self.core_filters).get().id,
                trip_id=self._fk_val,
                deleted_at__isnull=True)
            query_set = query_set.filter(
                id__in=through_objects.values("destination_id"))

        return query_set.filter(deleted_at__isnull = True)

The same would have to be done for TripManager as they would differ. You may check the performance and look at django/db/models/fields/related.py for reference.
Modifying the get_queryset method of the default manager may hamper the ability to backup the database and the documentation discourages it. Writing a Trip.get_destinations method is the alternative.


text:
Q: How to Sort Data by checkbox selection in jQuery If I have an array var item[]; and populate it with data:
var item = {title: displayTitle, DateDecription: dateDisplay, Date: new Date(eventDate), Region: region,}
                    data.push(item);

How can I sort this data by checkbox selection? for example Region may be "ALL","SF","SCV",or "OEB" if I have a checkbox for each of these possible regions how can I sort it by selection? By if statement? for each loop? Any advice would be greatly appreciated. Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scheme Adding Terms from lists I am writing a scheme program for performing operations on polynomials. I am currently working on a method that combines all like terms. For example, if I have the polynomial: 1x^2 + 2x^2 + 4x^3, the function should combine the likes terms 1x^2 and 2x^2 and output the final polynomial 3x^2 + 4x^3. It uses recursion.
I first sort the polynomial. Then, if the length is zero, do nothing. I have another function I call that checks if the exponents are equal, if they are, then I add the two terms, and go through the list.
Problem I am having is:
When I check if two terms are equal, I add them together. Once I do this, I can't figure out how to add this to the original list and pass that list in when making the recursive call. I know I am supposed to use "cons" to add to the front of a list. I know I am supposed to use cdr(cdr list) in order to skip the two terms that I added already.
How do I make a new list inside the function to add to the original list?. This is what I have done so far. Some of it does not work. (was trying out different things) The part I am stuck on is when I create 'a' and 'b' and print them. Instead of printing them, I want to put them in a list so that I can cons it with the original list. The commented out portion with the 'cons' stuff in the middle ( semicolon for comment) is what I tried so far. This is how my list is defined. First term is coefficient and second term is the exponent. Example:  (2 3) Coeff = 2, expon = 3
    (define p1 '((2 3)(3 2)(5 2)))

    (define (simplify p)
    (sort p GT)
    (cond [(= (length p) 0) (print 0)]
    [(= (length p) 1) (printpoly p)]
    [
     (if(EQExp? (car p) (cadr p))
     (let([a (+ (coeff (car p)) (coeff (cadr p)))])
     (let([b (expon (cadr p))])
     (print a)
     (display "x^")
     (print b)
       (printpoly(car([list '((a b))])))
     ; (printpoly y)
     ; (cons (cons ('(a) '(expon (cdr p)))) p)
     ; (cons  y p)
     ;(print (expon (car p)))
     (set! p (cdr p))
     (simplify p)
         )
       ;)
     )
     (if(> (length p) 1)
      ((printTerm (car p))
      (display " + ")
      (set! p (cdr p))
      (simplify p))
      ((=(length p) 1)
       (set! p (cdr p))
       (simplify p)
      )
      )
     )
     ]
     [else
     (set! p (cdr p))
     (simplify p)
     ]
     )
     )

A: Polynomial operations can be complicated, so it is important to break the task up into many small operations. In particular you need to have a separate function that prints a polynomial. Below you will see how simplify can replace the two terms with the same exponent. What's missing is a function for printing polynomials.
(define the-zero-polynomial '())

(define (exponent t) ; t stands for term
  (second t))

(define (coef t) ; t
  (first t))

(define (same-degree? t1 t2)
  (or (equal? t1 t2)
      (and (not (null? t1)) (not (null? t2))
           (= (exponent t1) (exponent t2)))))

(define p1 '((2 3) (3 2) (5 2)))

(define (simplify p) ; p is unsorted
  (simplify-sorted (sort p GT)))

(define (simplify-sorted p)
  (cond
    [(= (length p) 0) the-zero-polynomial]
    [(= (length p) 1) p]
    [else
     ; now p = (list t1 t2 t ...)
     (let ([t1 (first p)] [t2 (second p)])
       (cond
         [(same-degree? t1 t2)
          ; same degree, replace (list t1 t2 t ...)
          ; with                 (list t1+t2 t ...)
           (let ([t1+t2 (list (+ (coef t1) (coef t2))
                              (exponent t1))])
             (simplify-sorted (cons t1+t2 (cddr p))))]
         [else
          (cons t1 (simplify (cdr p)))]))]))


text:
Q: SELECT DISTINCT With WHERE Clause is VERY SLOW vs. SELECT DISTINCT with INNER JOIN AND Clause We have a production stored procedure that executes in 2-3 seconds everywhere except one client's environment.
Their environment appears healthy with 24 cores, 64 GB RAM and is nowhere near capacity. The SQL Server is 2008 r2 SP2.
I have restored the DB in my testing environment and the sproc returns in 2 seconds, but takes 20-50 minutes in the client's environment.
Today I setup a new instance of SQL Server on the same server and it also takes 20-50 minutes to execute the stored procedure.
Our DBA found the problem statement and devised a workaround.
Original:
--This returns in 30 minutes.
SELECT DISTINCT
          P.ProjectID, P.ProjectName
FROM DocumentRoute DR

LEFT JOIN Routes R
ON R.RouteID = DR.RouteID

INNER JOIN Documents D
ON D.DocumentID = DR.DocumentID
AND D.Status = 1

INNER JOIN Files F
ON F.FileID = D.FileID
AND F.Status = 1

INNER JOIN Projects P
ON P.ProjectID = F.ProjectID
AND P.Status = 1

LEFT OUTER JOIN Users U
ON U.UserID = DR.UserID

WHERE DR.Status = 1

Original Execution Plan here: http://screencast.com/t/xGcRIE9o
Workaround:
--This returns in 2 seconds.
SELECT DISTINCT
          P.ProjectID, P.ProjectName
FROM DocumentRoute DR

LEFT JOIN Routes R
ON R.RouteID = DR.RouteID
AND DR.Status = 1

INNER JOIN Documents D
ON D.DocumentID = DR.DocumentID
AND D.Status = 1

INNER JOIN Files F
ON F.FileID = D.FileID
AND F.Status = 1

INNER JOIN Projects P
ON P.ProjectID = F.ProjectID
AND P.Status = 1

LEFT OUTER JOIN Users U
ON U.UserID = DR.UserID

Revised Execution Plan here: http://screencast.com/t/Fqg90w6NDyZd
What in the client's environment could possibly account for the massive difference in execution time?
Additional info: When I got the execution plans from the client, the problem statement by itself finished in 17 seconds, but the entire sproc has been running for 15+ minutes and will probably take another 15 to finish.

A: The first problem is that these two queries do not have the same meaning and can return different results. The first query will only produce DocumentRoute rows where Status = 1. The second query will produce all DocumentRoute rows, and where the Status is null or is not equal to 1, will not perform the join to Routes.
The second problem is that if you are just selecting columns from the Projects table using DISTINCT, the LEFT JOINs can't possibly change the query in any way--so you may as well remove them.
Finally, without giving us some idea of the execution plan for both queries, and possibly some more details about the structure of the tables involved, no one is going to be able to definitively give you an answer about what is going on. Furthermore, the execution plan within your environment (where it takes 2 seconds) is not going to be helpful. We have to know the execution plan in the environment where it is running slowly.
To get an execution plan, run SET STATISTICS XML ON; first, run the desired query, and see the execution plan shown in a result set given after the result set of the query itself.
Some thoughts on what could be causing the problem:

*

*Are statistics set to update automatically? If not, the server could choose a poor plan.

*What is the fragmentation of the tables involved in the query?

*Does the client database server have its tempdb files set up properly--if there is more than one, are they all the same size?

A: With the advice of @ErikE, I scrutinized the client's execution plans for the multiple statements within the stored procedure and I noticed several parallelism operators.
So knowing that they had 24 processors on the server vs. 1 on mine, the light bulb lit up and I decided to try MAXDOP of 1 and behold, the execution time went from 45 minutes to 2 seconds.
sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
GO

sp_configure 'max degree of parallelism', 1;
GO
RECONFIGURE WITH OVERRIDE


text:
Q: Modal window css help please On this page, http://www.behance.net/signup, if you click "login", their modal window comes up.
I have already got a modal window in place, but cannot find which css they're using to style the border and everything within their modal window.
There's a lot of css and code there :( any help please extracting the styles for everything modal window related from there?

A: default.css and fancybox.css
Learn how to use your browser's developer tools. In FF with Firebug or Chrome by default you can right click an element and choose inspect. This will show you a history of the css as well as what lines are contributing to each effect, the rules hierarchy and more.
Here is a youtube video on using the Chrome developer tools.

A: It the class with id site-left-column. It seems to be on line 94 of fancybox.css. Learn to use firebug like tools from which you can easily figure out yourself.


text:
Q: Can random variables can be dependent if their squares are independent? Given two random variables X and Y. It is known that $X^2$ and $Y^2$ are independent. Is it possible for X and Y to be dependent?

A: Yes. Here is an example. A pair of coins, say the left and right coin, is flipped repeatedly. The RV $L$ takes the value $1$ if the left coin comes up heads, and $-1$ if it comes up tails. Similarly, the RV $R$ is $1$ if the right coin says heads and $-1$ if tails. We assume all coin tosses are independent, with heads and tails equally likely. Now define $X:=L+1$ and $Y:=L(R+1)$. Clearly $X^2$ and $Y^2$ are independent. However, $Y$ can only be $-2$ or $2$ (each with probability $\frac14$) when, respectively, $X=0$ or $X=2$ (each with probability $\frac12$).

A: Here is a simple counterexample. Let $X$ and $Y$ be discrete random variables with joint probability mass function $p(x,y)=P(X=x,Y=y)$ defined as $p(-1,0)=p(0,-1)=p(0,0)=p(1,1)=\frac14$, otherwise $p(x,y)=0$. Plainly $X$ and $Y$ are dependent, while $X^2$ and $Y^2$ are independent.


text:
Q: Convert function base view to class based view (DRF) can someone help me convert this function component to class based view (rest framework concrete view)?
I tried converting but landed with errors where serializer is false.
Product image is required in the query.
class Product(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    stock = models.IntegerField()
    is_available = models.BooleanField(default=True)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

class ProductImage(models.Model):
    image = models.ImageField(upload_to=get_upload_path)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images")

def store(request, category_slug):
    cat = None
    products = None

if category_slug != None:
    cat = get_object_or_404(Category, slug=category_slug)
    products = Product.objects.filter(category=cat)
    product_count = products.count()
else:
    products = Product.objects.filter(is_available=True)
    products.count()

context = {
    'products': products,
    'product_count': product_count
}
return render(request, 'store.html', context)

what i tried with rest framework.
Serializers:
class ProductImageSerializer(serializers.ModelSerializer):
    class Meta: model = ProductImage
    fields = ('image',)

class ProductSerializer(serializers.ModelSerializer):
    product_images = ProductImageSerializer(many=True, read_only=True)

    class Meta:
        model = Product
        fields = "__all__"

    def create(self, validated_data):
        profile_data = validated_data.pop('product_images')
        product = Product.objects.create(**validated_data)
    return product

View:
I tried with concrete views, product is filtered by category.
class Store(generics.ListCreateAPIView):
    queryset = Product.objects.filter(is_available=True)
    serializer_class = ProductSerializer
    lookup_field = 'category_slug'
    lookup_url_kwarg = 'category_slug'

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        cat_slug = self.kwargs.get('category_slug')
        products = None

        if cat_slug is not None:
           category = get_object_or_404(Category, slug=cat_slug)
           products = queryset.filter(category=category, is_available=True)
        else:
           products = queryset.filter(is_available=True)
        if products.count() == 1:
           serializer = ProductSerializer(data=products.first())
        elif products.count() > 1:
           serializer = ProductSerializer(data=products, many=True)

    if not serializer.is_valid():
        print(serializer.errors)

    data = serializer.data
    return Response(data, status=status.HTTP_200_OK)

any help is appreciated.


text:
Q: Is wpf touch screen specific? I have developed a application for a client who uses windows 7 home premium x64 with touchscreen. when i deploy application after some time the application crashed.when i tried to debug in client system the error is Recursive call to the automation peer api after some research in internet i found out this article Click On The Link
When i debug in client system it shows error in different pages. is their any other way to fix this problem. Kindly Help?

A: Some how i have found out a solution. when i stop the tablet input service from the windows services the application runs fine. so i have integrated code in windows loaded to stop the service and in windows closed i have integrated the code to start the service. i know it is not the correct solution but for the time being till microsoft release a patch of .net framework.


text:
Q: How to replace (.) dots by (·) interpuncts in PHP? There's a French typographic rule to write properly some words in a genderless way, by adding an (·) interpunct between letters.
A few authors on my website are however typing a simple (.) dot instead.
As a solution, I'd like to create a function to replace in PHP strings each dots which are placed between two lowercase letters by interpuncts. But my PHP skills are rather limited… Here is what I'm looking for:
REPLACE THIS:
$string = "T.N.T.: Chargé.e des livreur.se.s."
BY THIS:
$string = "T.N.T.: Chargé·e des livreur·se·s."
Could someone help me please?
Thank you.

A: Use the preg_replace with pattern to dynamically match 3 groups - two lowercase letters (including special French letters) and dot between, and use the first and third captured group in replacement, along with intepunct:
$string = "T.N.T.: Chargé.e des livreur.se.s.";
$pattern = '/([a-zàâçéèêëîïôûùüÿñæœ])(\.)([a-zàâçéèêëîïôûùüÿñæœ])/';
$replacement = '$1·$3'; //captured first and third group, and interpunct in the middle

//results in "T.N.T.: Chargé·e des livreur·se·s."
$string_replaced = preg_replace($pattern, $replacement, $string);

More about preg_replace:
https://www.php.net/manual/en/function.preg-replace.php

A: You could use str_replace() if you know the grammar rules surrounding the dots you want to replace. (for instance, if everything between éand e is concerned, then you can do :
$bodytag = str_replace("é.e", "é·e", $sourceText);

But you will always risk some side effects. For instance if there is an acronym you don't want to be replaced with this pattern. I don't think there is any magic way to avoid this.
More specifically

I'd like to create a function to replace in PHP strings each dots which are placed between two lowercase letters by interpuncts.

This can be achieved with preg_replace() and the appropriate REGEX
See this post


text:
Q: How to search in the Maps app? There seems to be no search bar in the Maps app. Even right-clicking brings up a menu without a search option. How do I search for locations in the Maps app?

A: To search on Maps:

*

*Bring up the Charms bar by either swiping in from the right of your screen or moving to the top-right or bottom-right corner of your screen (or pressing Windows+C) then select the Search option:

*Enter your search into the Search box provided and hit Enter:

*Additional results can be found using the Search results button that appears in the top left after returning to the map:

*Clicking this brings up the additional results and refining option:

A: Move the cursor to top-right corner or press WinC.
There is a Search option on it.


text:
Q: Receive raw response data using axios I am trying to receive the raw response data, not the response headers or body. As an example, an image here shows the tab where this data is found:

Now, I am trying to receive this data when making an HTTP Request using `Axios`. Is this even possible?
I have tried searching online for about 2 hours, as this was a huge problem I was facing. I tried other sites, including stack overflow, to get the correct answer. If possible, could you please answer my question if you know? Thanks in advance.
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?user=username&passwd=password'
function axiosTest() {
    return axios.post(url).then((r) => {
        console.log(r)
    })
}

A: I'm pretty sure you must access the data property in the response object r. Also - since you are using the reddit API - make sure you are providing api_type in the request url (api_type=json for instance):
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?api_type=json&user=username&passwd=password'
function axiosTest() {
    return axios.post(url).then((r) => {
        console.log(r.data)
        return r.data;
    })
}

For anyone reading this: Just to clarify, the api_type parameter in the request url is specific to the reddit API and most likely won't work any other API.


text:
Q: No OpenID endpoint found I am trying to use the DotNetOpenId library to add OpenID support on a test website. For some reason it keeps giving me the following error when running on Firefox. Keep in mind that I am using localhost as I am testing it on my local machine.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;

namespace TableSorterDemo
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var openid = new OpenIdRelyingParty();
            if (openid.GetResponse() != null)
            {
                switch (openid.GetResponse().Status)
                {
                    case AuthenticationStatus.Authenticated:
                        var fetch = openid.GetResponse().GetExtension(typeof(ClaimsResponse)) as ClaimsResponse;
                        var nick = fetch.Nickname;
                        var email = fetch.Email;

                        break;
                }
            }
        }

        protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e)
        {
            var openid = new OpenIdRelyingParty();
            if(openid.GetResponse() != null)
            {
                switch(openid.GetResponse().Status)
                {
                    case AuthenticationStatus.Authenticated:
                        var fetch = openid.GetResponse().GetExtension(typeof (ClaimsResponse)) as ClaimsResponse;
                        var nick = fetch.Nickname;
                        var email = fetch.Email;

                        break;
                }
            }

        }

        protected void OpenIdLogin1_LoggingIn(object sender, OpenIdEventArgs e)
        {
            var openid = new OpenIdRelyingParty();
            var req = openid.CreateRequest(OpenIdLogin1.Text);
            var fetch = new ClaimsRequest();
            fetch.Email = DemandLevel.Require;
            fetch.Nickname = DemandLevel.Require;
            req.AddExtension(fetch);
            req.RedirectToProvider();
            return;
        }

    }
}

Also, if I run the same page in Chrome then I get the following:
Login failed: This message has already been processed. This could indicate a replay attack in progress.

A: The replay attack detection results from you calling GetResponse() twice.  You must not do that.  Instead, assign the result of just one call to GetResponse() to a local variable, and then check it against null and use it otherwise.
Regarding you "No OpenID endpoint found" error, are you testing against a localhost OpenID as well or an OpenID hosted by an external party like Yahoo?

A: In my case as I was using a proxy to connect to the internet, I resolved by adding the following configuration to the web.config.
<system.net>
 <defaultProxy useDefaultCredentials="true">
  <proxy autoDetect="True" usesystemdefault="True" />
 </defaultProxy>
</system.net>

A: Its worth noting that the 'No OpenID endpoint found' error message may not be a true description of what the issue is.
For myself it was because I was using my gmail email address but actually you need to create an OpenId account you will then get an id in the format .myopenid.com/
Enter that Id into the form and it should work correctly.

A: Check the web.config in your client app.
There is a section
                    <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
                <!--<add name="localhost" />-->

So as it says - uncomment to
<add name="localhost" />


text:
Q: Jquery: if element is hidden, do action? Hello I searched a bit on the internet, but didn't find what I actualy were looking for.
But anyway, what I'm looking for is some like if a element is hidden then it's gonna do an action, and then if the element is visible it's gonna do another action. In this case I'm building an show/hide menu, when you click the menu icon (with the class ".toggle") it's gonna change the opacity to 1, and when you hide the menu the icon opacity will change to 0.6 again.
Here's my code anyway:
$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
$(".sidebar_menu").animate({width: "toggle"}, 200);
// Here's where the code I can't figure out is gonna be.
});

Hope you guys wanna help me, it would be nice! Thank you.

A: this works for hidden and visible elements:
$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
  $(".sidebar_menu").animate({width: "toggle"}, 200,
    function() {
      if($(this).is(':visible')){
        $(".toggle").css({opacity: 1});
      } else if ($(this).is(':hidden')) {
        $(".toggle").css({opacity: 0.6});
      };
    })
  });
});

Edit: with .toggle()
$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
  $(".sidebar_menu").toggle('slow',
    function() {
      if($(this).is(':visible')){
        $(".toggle").css({opacity: 1});
      } else if ($(this).is(':hidden')) {
        $(".toggle").css({opacity: 0.6});
      };
    })
  });
});

Here you see a small example: FIDDLE


text:
Q: Referencing resource ID from the support library in XML file importing an xml file that uses a resource id created in the v7 supoort library.
The imported xml file contains the following  id but it does not use the "@id+," as if it were just created:
android:id="@id/activity_chooser_view_content"
At the following link it shows that in v7 appCompat Support library the id has been created (3rd line down after end of comments section):
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r1/frameworks/support/v7/appcompat/res/layout/abc_activity_chooser_view.xml
 android:id="@+id/activity_chooser_view_content"

What would i Have to do in order to get Android or Android Studio to find the id?
I get the following errors:
Error:(2, 51) No resource found that matches the given name (at 'id' with value '@id/activity_chooser_view_content').

Error:(8, 64) No resource found that matches the given name (at 'id' with value '@id/image').

I am compiling the following reference libraries:
compile 'com.android.support:support-annotations:23.1.0'
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'

compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:support-v13:25.0.0'

A: In order to reference an ID from the SDK, you need @android:id/<name>
Alternatively, you error means that since you have @id and not @+id, you are trying to reference an existing ID from your own app's resources, not create a new one.
Or maybe you should try something like
View rootView = LayoutInflater.from(getContext()).inflate(android.R.layout.abc_activity_chooser_view);
View x = rootView.findViewById(android.R.id.<name>);

Worth mentioning ...

Internal layouts are not meant to be used directly and are subject to change at any time, which may break your code in the future. The better solution is to create your own layout or use a public framework widget with similar functionality. Use of an internal widget is done at your own risk

https://stackoverflow.com/a/39318656/2308683


text:
Q: What's wrong with this DFS implementation? I'm not sure what's wrong with the following depth-first-search code. The expected vs program output is included at the end. I obtained the expected output by running code from geeksforgeeks (s/o to them). Any help would be appreciated.
Here's my code:
class Node:
    def __init__(self, val):
        self._val = val
        self._chdrn = []

class Nary:

    def __init__(self, n: int):
        self._n = n
        self._root = None

    def insert(self, val: int):
        nn = Node(val)
        if not self._root:
            self._root = nn
        else:
            def recur(parent: Node):
                print("Parent: ", parent._val)
                if len(parent._chdrn) < self._n:
                    parent._chdrn.append(nn)
                    return 1
                else:
                    for chdl in parent._chdrn:
                        ret = recur(chdl)
                        if ret == 1:
                            break
            parent = self._root
            recur(parent)

    def dfs(self):
        def _dfs(node: Node):
            if not node: return
            print(node._val, end=' ')
            for chld in node._chdrn:
                # print("current child = ", chld._val)
                _dfs(chld)
        _dfs(self._root)

Tree  = Nary(3)
for i in range(10): Tree.insert(i)
Tree.dfs()

#

Expected output: 0 1 4 5 6 2 7 8 9 3
Program output: 0 1 4 7 8 9 5 6 2 7 8 9 3

A: Nothing wring with your DFS code. Your tree construction with the insert method is wrong.
You need to return in the recursive case when looping through children in recur. Otherwise the same node will get inserted under multiple parents.
class Node:
    def __init__(self, val):
        self._val = val
        self._chdrn = []

class Nary:

    def __init__(self, n: int):
        self._n = n
        self._root = None

    def insert(self, val: int):
        print(f"Inserting {val}")
        nn = Node(val)
        if not self._root:
            self._root = nn
        else:
            def recur(parent: Node):
                if len(parent._chdrn) < self._n:
                    print(f"Added under parent: {parent._val}")
                    parent._chdrn.append(nn)
                    return 1
                else:
                    for chdl in parent._chdrn:
                        ret = recur(chdl)
                        if ret == 1:
                            return 1  # not just break

            parent = self._root
            recur(parent)

    def dfs(self):
        def _dfs(node: Node):
            if not node: return
            print(node._val, end=' ')
            for chld in node._chdrn:
                # print("current child = ", chld._val)
                _dfs(chld)

        _dfs(self._root)

Tree = Nary(3)
for i in range(10): Tree.insert(i)
Tree.dfs()

BTW the correct DFS order for this tree is:
0 1 4 7 8 9 5 6 2 3

You should draw out the tree and manually do a DFS to verify.


text:
Q: google.oauth2.credentials.Credentials fails with valid token I'm trying to list my YouTube channels via Python 3.6, given (and this is important) an EXISTING access token and some valid API key. It works well with curl and returns a valid JSON response:
curl 'https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true&key=API_KEY' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer ACCESS_TOKEN'

response:
{
    "kind": "youtube#channelListResponse",
    "etag": "\"xxxxxxxxx\"",
    "pageInfo": {...},
    "items": [...]
}

If I remove the Authorization header, I get the expected error:
{
    "error": {
        "errors": [
            {
                "domain": "youtube.parameter",
                "reason": "authorizationRequired",
                "message": "The request uses the mine parameter but is not properly authorized.",
                "locationType": "parameter",
                "location": "mine"
            }
        ],
        "code": 401,
        "message": "The request uses the mine parameter but is not properly authorized."
    }
}

Now, I try to do the same with the Google Python library (because I need it for more complex operations and code control), but it doesn't work. I get the same error as if I did not pass any access token. Any ideas what I'm doing wrong? Here is my Python code (note the access token is given to the code, I MUST use it as-is):
import argparse
import google.oauth2.credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def get_authenticated_service(options):
  creds = google.oauth2.credentials.Credentials(options.access_token)
  return build('youtube', 'v3', credentials=creds, developerKey=options.api_key)

def list_channels(youtube, options):
  request = youtube.channels().list(part="snippet", mine=True)
  response = request.execute()
  print(response)

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--api_key', required=True)
  parser.add_argument('--access_token', required=True)
  args = parser.parse_args()
  youtube = get_authenticated_service(args)
  try:
    list_channels(youtube, args)
  except HttpError as e:
    print('An HTTP error {0} occurred:\n{1}'.format(e.resp.status, e.content))

I run it like so:
python3 test.py --api_key MY_API_KEY --access_token MY_ACCESS_TOKEN

A: I think that your script works. Actually, in my environment, I could confirm that your script worked.
In your case, you have already been retrieved the access token. I think that when the access token can be used for using Youtube Data API, in this case, the script works without using the API key.
Reference:

*

*Channels: list


text:
Q: GetComponent requires that the requested component 'AudioSource[]' derives from MonoBehaviour or Component or is an interface I implemented IBM Watson's Speech-to-Text, so when I say "jump"/"anger", my character will player an audio clip. However I'm getting this error, which is preventing the character to react to my voice trigger.
Error Message:
Unity Exception ArgumentException: GetComponent requires that the requested component 'AudioSource[]' derives from MonoBehaviour or Component or is an interface.

My CharacterController.cs:
   using UnityEngine;

    public class CharacterController : MonoBehaviour
    {

        // Use this for initialization

        public Animator anim;

        public AudioSource[] _audio;

        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {

            anim = GetComponent<Animator>();
            _audio = GetComponent<AudioSource[]>();
        }

        public void CharacterActions(string ActionCommands)
        {
            ActionCommands = ActionCommands.Trim();
            switch (ActionCommands)
            {
                case "jump":
                    anim.Play("jump", -1, 0f);
                    _audio[0].Play();
                    break;
                case "anger":
                    anim.Play("rage", -1, 0f);
                    _audio[1].Play();
                    break;

                default:
                    anim.Play("idle", -1, 0f);
                    break;

            }

        }
    }

A: You can't use GetComponent to get array of all AudioSource objects because Unity will search for component with type AudioSource[] instead of AudioSource , which don't exist. To get array of all the AudioSource objects you have to do
_audio = GetComponents<AudioSource>();

instead.

A: What worked for me:
TMP_Text[] texts = newGo.GetComponentsInChildren<TMP_Text>();
Look that it is Component(s) not only Component.


text:
Q: The second fundamental form of geodesic sphere in space form
This is from Geometry Analysis by Peter Li. He said that in a space form, the inequality (2.4) will become an equality. I think it's because the second fundamental form of geodesic sphere in space form is $h_{ij}=\delta_{ij}$. But I can't prove it.


text:
Q: Cleaned text has significantly worse classification accuracy? I'm trying to classify whether or not I liked books that I've read this year based on the text in the books. I'm using the preprocessing described here, and a variety of sklearn classification models.
At first I was just feeding the models the raw text, but I cleaned it based on GloVe embeddings (a process described here). The text was improved from 40% vocab, 80% coverage to 80% vocab, 98% coverage based on GloVe embeddings. However, for some reason, after cleaning the text, the accuracy of the classification models seemed to be the same or lower.
Uncleaned text model results:

Cleaned text model results:

One thing to note is that the classes are quite imbalanced (75% of books were good as compared to 25% bad), so accuracy above 75% should be expected, since 75% is what the model would get if it guessed good every single time.
I've linked my full notebook here so you can check out the specific code if that will be helpful for solving this issue. I'm incredibly confused; I can't see where I'm going wrong, but it can't be right that cleaning the text data has zero or negative impact on model accuracy.

A: I think the main point you are missing is that data cleaning is an empirical process. Text preprocessing may consist of removing stop words, punctuations, numericals, lowercasing, but if this adds to model's ability to learn and generalize remains to be seen through Cross Validation, i.e. feeding results of your peprocessing to model train and seeing if this generalizes to test well.
In general preproceeeing (stop words removal, etc) works well for Bag of Words models because it reduces data dimensionality because data in BOW is long and sparse (check out Curse of dimensionality e.g. for possible theoretical foundations). The need for data preprocessing is diminished with word embeddings like word2vec or BERT.
In short, if you have any data preprocessing in mind, check if it helps your model to learn and generalize through properly constructed CV.


text:
Q: How to make mysql query select data from MAX(value) and not value? I am trying to return the Price data from the latest Date for each Name.
SELECT MAX(Date) AS max_date, Date, Price, Name
from STOCK_DATA_TRANSPOSED
group by Name

The output below is the output of the above query. As we see the price data is returned by Date and not max_date.
max_date                    Date        Price   Name
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    1COV.DE
2021-04-21 00:00:00 2019-12-31 00:00:00 73.41   AAPL
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ABB.ST
2021-04-21 00:00:00 2019-12-31 00:00:00 88.54   ABBV
2021-04-21 00:00:00 2019-12-31 00:00:00 86.86   ABT
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AC.PA
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ACA.PA
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ACCD
2021-04-21 00:00:00 2019-12-31 00:00:00 210.57  ACN
2021-04-21 00:00:00 2019-12-31 00:00:00 329.81  ADBE
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ADE.OL
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ADS.DE
2021-04-21 00:00:00 2019-12-31 00:00:00 7.64    AGLE
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AI.PA
2021-04-21 00:00:00 2019-12-31 00:00:00 51.33   AIG
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AIR.PA
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AKRBP.OL
2021-04-21 00:00:00 2019-12-31 00:00:00 1.75    AKTX
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ALFA.ST
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ALIV-SDB.ST
2021-04-21 00:00:00 2019-12-31 00:00:00 112.45  ALL
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ALV.DE
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AMBU-B.CO
2021-04-21 00:00:00 2019-12-31 00:00:00 241.07  AMGN
2021-04-21 00:00:00 2019-12-31 00:00:00 229.82  AMT

How can I return the Price data based max_date grouped by Name?

A: Try this:
SELECT sdt1.Date, sdt1.Price, sdt1.Name
FROM STOCK_DATA_TRANSPOSED AS sdt1
WHERE (sdt1.Date, sdt1.Name) IN
(
    SELECT MAX(sdt2.Date), sdt2.Name
    FROM STOCK_DATA_TRANSPOSED AS sdt2
    GROUP BY sdt2.Name
);

In this way you get the info from STOCK_DATA_TRANSPOSED where Date is the MAX(Date) from each Name.
You can see the result in DBFiddle.


text:
Q: Power Query Tables won't download data until VBA finishes executing I have a spreadsheet with 4 worksheets, each one connected to a power query which connects to an OLEDB database and runs a select to import data into the workbook.
I am trying to automate the refresh of the queries.
I have VBA in the workbook which
 - disables background refresh,
 - runs Workbook.RefreshAll,
 - resets the background refresh to true (as I need this for the automation software to be able to run it in the first place) and
 - then waits 30 seconds to give the automation software a bit of time before it starts saving the workbook.
All the software does is call the macro in the workbook and then save following execution.
The queries correctly execute one after the other and I can tell the data in the tables has refreshed.
The power query confirmation that the rows have been downloaded happens after the VBA completes executing, so the automation software saves it before this is done and Excel reports the download as having failed. This isn't a problem when everything works, but we won't know when the download has truly failed, unless I add in some sort of a row count comparison which is really a workaround rather than an actual solution.
I have tried creating two subs in the workbook, one to do the refresh and then another which calls the first sub and then waits 30 seconds, I was hoping the download would complete after the first sub finishes executing, but this doesn't happen. I have tried refreshing one connection at a time instead of using RefreshAll, tried refreshing the actual power query tables instead of the connections and have tried refreshing with background query set to true and then looping until the refresh is marked as complete (which works if you step through it, but crashes if you just run the VBA in full).
I also tried saving the spreadsheet at the end of the VBA, but it still waits until the save is complete to update the power query status.
My latest VBA:
Sub Workbook_RefreshAll()

Application.DisplayAlerts = False

For Each objConnection In ThisWorkbook.Connections

    'Temporarily disable background-refresh
    objConnection.OLEDBConnection.BackgroundQuery = False
    objConnection.OLEDBConnection.MaintainConnection = False

Next

ActiveWorkbook.RefreshAll

For Each objConnection In ThisWorkbook.Connections

    'Re-enable background-refresh
    objConnection.OLEDBConnection.BackgroundQuery = True
    objConnection.OLEDBConnection.MaintainConnection = True

Next

newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 30
waitTime = TimeSerial(newHour, newMinute, newSecond)

Application.Wait waitTime

End Sub

(I can't remember whether the maintain connection parameter actually helped as I as trying to force the connection to drop after each refresh, but it works so haven't taken it out.)

A: Instead of Application.Wait try the following:
Do until now() >= waittime
    DoEvents
Loop


text:
Q: smarter php login form validation I've started learning PHP and MySQL for a while but I still consider myself a beginner!
I created a simple register form and I also wrote PHP code to validate it...
I want to know if there is a better and smarter way to accomplish my goal.
My form is based on 5 inputs: username, password, repeat password, email, repeat email and it sends through POST, their content and a button's value. It must check these conditions when a submit is performed:

*

*show error "All fields empty" if all inputs are empty

*show error "Some fields empty" if one or more inputs, but not all, are empty

*username length must be up to 20 chars

*password and repeat password must be equal

*passwords must be between 8 and 20 chars

*email and repeat email must be valid emails and must be equal

*show an error message of what went wrong

I wrote this function (it's inside a class) which does everything I said above but can I improve it to reduce repetitive code? Are there other PHP functions which can be used for this? And finally, how secure is my code?
Here is it!
public function processRegisterInfo($POSTArray = array())
{
    if (count(array_filter($POSTArray)) > 1) // button don't have to be counted
    {
        if (count(array_filter($POSTArray)) < 6)
        {
            $this->errorMsg = "Some fields are empty";
            return FALSE;
        }
        else
        {
            $username = $POSTArray["username"];
            $password = $POSTArray["password"];
            $repPassword = $POSTArray["repPassword"];
            $email = $POSTArray["email"];
            $repEmail = $POSTArray["repEmail"];

            $isValid = TRUE;

            // Checking username length
            if (strlen($username) > 20)
            {
                $this->errorMsg .= " Username too long.";
                $isValid = FALSE;
            }

            // Checking password length and equality
            if (strcmp($password, $repPassword) == 0)
            {
                if (strlen($password) < 8)
                {
                    $this->errorMsg .= " Password must be at least 8 characters.";
                    $isValid = FALSE;
                }
                else if (strlen($password) > 20)
                {
                    $this->errorMsg .= " Password must be max 20 characters long.";
                    $isValid = FALSE;
                }
            }
            else
            {
                $this->errorMsg .= " Passwords don't match.";
                $isValid = FALSE;
            }

            // Checking email validation and equality
            if (strcmp($email, $repEmail) == 0)
            {
                if (!filter_var($email, FILTER_VALIDATE_EMAIL))
                {
                    $this->errorMsg .= " Email provided is not valid.";
                    $isValid = FALSE;
                }
            }
            else
            {
                $this->errorMsg .= " Emails don't match.";
                $isValid = FALSE;
            }

            if (isset($this->errorMsg) && !empty($this->errorMsg))
                $this->errorMsg = substr($this->errorMsg, 1);

            return $isValid;
        }
    }
    else
    {
        $this->errorMsg = "All fields are empty";
        return FALSE;
    }
}

Thank you so much for your help! :)

A: If you are only able to use php it's as good as it's going to get i think.
These check can be performed by Jquery(javasript) to.
The pros of using jquery are, you don't have to submit it first and you can easily mark which field has a wrong value.


text:
Q: Extension of trigonometric functions (like Bessel functions) I'm physics student learning mathematical physics, now especially Bessel functions.
I learned that the Bessel functions and that family are derived from the ODE
$$
y''+y'/x+(1-\nu^2/x^2)y=0,
$$
and $J_\nu(x)$, $Y_\nu(x)$, $H_\nu^{(1)}(x)$, $H_2^{(2)}(x)$, $I_\nu(x)$, $K_\nu(x)$ have similar properties to $\cos(x)$, $\sin(x)$, $e^{ix}$, $e^{-ix}$, $\cosh(x)$, $\sinh(x)$. (I'm using the notation in the Arfken's Mathematical methods for physicists.)
So I naturally began to wonder if we can also generalize the ODE for trigonometric function $y''+y=0$, to depend on certain index like $\nu$, so we can generate special functions which depend on the index, and which becomes trigonometric function for certain index.  But I'm not sure where should I put the index $\nu$ to make family of functions. If I set, like, $y''+\nu^2y=0$, then solution is just $\sin(\nu x)$, which is basically same as $\sin(x)$. Wait... but maybe we can do this way, $y''+(1-\nu^2/x^2)y=0$?
Is there a extension of trigonometric functions in this(or similar) way? Are they just not practical functions? Or is there a reason that trigonometric functions are special so they should be unique?

A: The Bessel functions are the generalization of sine and cosine across multiple dimensionalities. Classically, they're the generalization for $d=2$, but it turns out that they can be mapped onto the general case, too.
Specifically, the Laplacian in $d$-dimensions and hyperspherical coordinates is given by
$$\nabla^2 = \frac{1}{r^{d-1}}\frac{\partial}{\partial r} \left(r^{d-1}\frac{\partial}{\partial r}\right) + \frac{1}{r^2} \nabla^2_{S_d}, \tag1$$
where $\nabla^2_{S_d}$ is the Laplacian on the surface of a $d$-dimensional unit sphere. Now, let's look at the eigenvalue problem for the Laplacian, $\nabla^2 f = -k^2f$, which can be solved using separation of variables. The angular part is solved with Gegenbauer polynomials of sines/cosines of the angular variables and has eigenvalue $-\ell(\ell+d-2)$. The radial part then becomes the ODE
$$\frac{\partial^2R}{\partial r^2} + \frac{d-1}{r} \frac{\partial R}{\partial r} - \frac{\ell(\ell+d-2)}{r^2}R = -k^2R, \tag2$$
where $\ell$ is an integer (see Equation 2 from this paper).
Equation 2 becomes Bessel's differential equation if you make the substitution $R(r)=g(r) / r^{d/2-1}$, explicitly
$$g'' + \frac{ g'}{r} + \left(k^2 - \frac{\left[\frac{d}{2}- 1 + \ell\right]^2}{r^2}\right)g = 0, \tag3$$
which goes the rest of the way with the substitutions $y=g$, $x=kr$, and $\nu=\frac{d}{2}- 1 + \ell$.
For $d=2$ you get back to Bessel's equation. For $d=3$ you get the spherical Bessel's equation. For $d=1$ you can use $\ell=0,1$ to produce cosine and sine (the rotation symmetry there is just discrete parity).
I find this generalization so useful that I call the solution to these equations hyperspherical Bessel functions and defined a shorthand notation for them
$$X_{[d]_\pm\ell}(r) \equiv \frac{X_{\pm(\ell + d/2-1)}(r)}{r^{d/2-1}}, \tag4$$
where $X$ is any of the Bessel/Hankel function symbols, modified or otherwise: $J$, $Y$, $I$, $K$, $H^{(1)}$, or $H^{(2)}$.
It is possible to generalize even further, and you get into special functions that are so general I've never actually seen them used outside of Mathematica spitting them out from time to time: hypergeometric functions, generalized hypergeometric functions, the Meijer's $G$-function, etc.

A: There isn't really a single unique possible extension, because there's a myriad ways in which you might deform the trigonometric functions, and it comes down to the human subjective judgement on whether the deformation is useful enough to be classified as a special function or not.
However, there is a pretty clear answer in the Jacobi elliptic functions $\operatorname{sn}(x,k)$, $\operatorname{cn}(x,k)$, and related objects; these are explained in depth in Wikipedia and the Digital Library of Mathematical Functions. Since you explicitly mentioned the second-order ODE, I'll quote one relevant differential equation
$$
\frac{{\mathrm{d}}^{2}}{{\mathrm{d}z}^{2}}\operatorname{sn}\left(z,k\right)
=
-(1+k^{2})\operatorname{sn}\left(z,k\right)
+2k^{2}{\operatorname{sn}^{3}}\left(z,k\right),
$$
(with more found here), but that isn't really the cleanest way to obtain that family in a natural way; instead, the first place they tend to pop up is as inverses of the elliptic integrals.


text:
Q: How do I return only rows with non duplicate ids AND a matching value on another column? I have a table where I need to check if multiple ids exist with different types and return the ids that have only one record and has trial in the type column.
For example using this table:
id|type
--------
12|trial
12|purchase
13|trial
14|purchase
14|trial
15|trial

I want to return the following results:
id|type
--------
13|trial
15|trial

Since these only have one record containing a trial.  If an id contains a trial and a purchase I want those rows to be excluded.

A: Its can be done by using inner query
select * from t where id IN (select id from t group by id having count(*) <= 1) AND trial = 'trial';

A: I think you want not exists:
select t.*
from t
where t.type = 'trial' and
      not exists (select 1 from t t2 where t2.id = t.id and t2.type <> 'trial');

If you just want ids that meet this condition, I would suggests aggregation:
select t.*
from t
group by t.id
having sum( (t.type <> 'trial')::int ) = 0;

A: One more alternative, using a JOIN. The sub-query limits the results to id values that are unique, then the WHERE clause further filters that down to the type value you're interested in.
select
  t.id,
  t.type
from
  @table as t
JOIN
  (
    select
      id
    from @table
    group by id
    having count(*)=1
  ) as d
    on d.id = t.id
where type = 'trial';

Returns the result set you have in the question.


text:
Q: Center inline image to fit browser like image with its own url would (and with 100% width or height and no stretching) I have a webcam with vertical-align: middle; here: http://flamencopeko.net/cam.php. Works. But I want the scroll-bars to never appear. The fact that the image updates has no importance to what I'm trying to make. I'm thinking something like this:

Here's the complete code for the test version: http://flamencopeko.net/cam3.txt
Will not show 100% height when I change the variable in head from 1 to anything else.
I plan to read the inner html x and y values and then make the image adjust to that.


text:
Q: I can't seem to know how to concatenate two char pointer strings using strcat, is it not correct? I can't concatenate two pointer strings using strcat, is it not possible?
I tried using them like strcat(s1,s2), and strcat(*s1,*s2), and all and it still doesn't work.
char *s1="Hello";
char *s2="Bye";
printf("%s\n",s1);
strcat(s1,s2);
printf("%s",s1);

When I run it prints the first "Hello" that is before the strcat, but the code doesn't display the remaining output and doesn't return 0.

A: Your approach cannot work, for several reasons:
char *s1="Hello";

s1 points to a read-only string (literal). You cannnot modify it.
strcat(s1,s2);

This cannot work because there is not enough room in s1 to add s2.
Use:
char s1[30]="Hello";
char *s2="Bye";

strcat(s1,s2);

With char s1[30]="Hello"; the compiler allocates an array for 30 charactes and then copies the string "Hello" into that array. Unused elements are set to zero.
With char *s2="Bye"; the compiler makes s2 point to a read-only string, so to make that explicit it is better to write const char *s2="Bye";


text:
Q: I can't use arrays in bash (syntax error: "("unexpected). Why are some commands not working? I began my learning in Bash a few days ago, however, there are some commands that do not work. Fortunately, there are alternatives available.
But unfortunately, I didn't find alternatives in the arrays.
For each line, the command should be followed by its corresponding error in a comment on the same line.
#declare -A a               # declare: not found
#declare -a a               # declare: not found
#arr=()                 # Syntax error: "(" unexpected
#a=(1 2 5)              # Syntax error: "(" unexpected
#a= ( 1 2 5 )               # Syntax error: "(" unexpected
#myArray=("cat" "dog" "mouse" "frog")   # Syntax error: "(" unexpected

a=`seq 1 5`
for i in $a;    do echo $i;  done

#echo ${a[@]}               # Bad substitution
#a[1]=5                 # a[1]=5: not found
#echo "${a[1]}"             # Bad substitution

just seq ... way which run
in addition of that I can't access any specefic element outside the loop as "a[1]=5" for example
so what is the problem? why there are a lot of commands that don't run?
and how can I access specific element in an array?


text:
Q: MongoDB map reduce - group and find top N An , and collection called test
Consider this test collection, in which an airport is identified by AirportID:
{ AirportID:"1001", delayMinutes :"15.0" },
{ AirportID:"1004", delayMinutes :"3.0" },
{ AirportID:"1001", delayMinutes :"20.0" },
{ AirportID:"1002", delayMinutes :"6.0" },
{ AirportID:"1002", delayMinutes :"25.0" },
{ AirportID:"1004", delayMinutes :"55.0" },

I want to group it together and list the top 2 from that list.
This is the query I tried:
db.test.aggregate([
  { $group: { _id: "$AirportID", delayMinutes: { $sum: 1 } } },
  { $sort: { delayMinutes: -1 } }
])

But it didn't work for me

A: You're very close, you just need to do 2 additional things:

*

*Add a $limit stage at the end to only return 2 results

*Cast the delayMinutes to a number using $toDecimel or $toDouble, note that any invalid string value will make this stage fail.

Overall this is what it'll look like:
db.test.aggregate([
  {
    $group: {
      _id: "$AirportID",
      delayMinutes: {
        $sum: {
          "$toDouble": "$delayMinutes"
        }
      }
    }
  },
  {
    $sort: {
      delayMinutes: -1
    }
  },
  {
    $limit: 2
  }
])

Mongo Playground


text:
Q: apportable : No module named argparse error on mac i just installed apportable from here : http://www.apportable.com/users/1928
now , after installing successfully it gives this error :
Traceback (most recent call last):
  File "/Users/macintosh/.apportable/SDK/bin/apportable", line 3, in
    import argparse
ImportError: No module named argparse
i can understand it's import issue .. but i am not able to resolve this .. can anyone help on this !! i have tried this for many times & still same error .. what could be the possible resolution to this.
please help !

A: You may have an old python. You should have version 2.7+:
$ python --version
Python 2.7.2

Or old MacOS X. Apportable requires Mac OS X 10.7+.


text:
Q: find files in specified directory assembly I'm trying to make a program that finds files smaller than a certain size. The folders program needs to search in are specified in the beginning. I'm using DOSBOX, TASM and TLINK.
Here's some related code:
mov ax, @data
mov ds, ax
PrepDTA:
mov dx,OFFSET DTA   ; DS:DX points to DTA
mov ah,1AH      ; function 1Ah - set DTA
int 21h         ; call DOS service
WorkWithFiles:
FindFirst:
mov cx,3fh
mov si, offset DTA
mov ah, 4eh
mov dx, offset Folder
int 21h
cmp al, 0FFh
je NeraFailu
jmp FileSize
FindNext:
mov si, offset DTA
mov ah, 4fh
mov cx,3fh
mov dx, offset Folder
int 21h
jc NoMoreFiles
jmp FileSize
FileSize:
mov si, offset DTA+26
mov bh, 4

So when I run the program, DTA after FindFirst is set to some nonsence, and on FindNext it jumps to NoMoreFiles. There are 2 files in the directory I specify, but no matter which directory I specify DTA is the same. I tried adding *.* in the end, changing the security of files in properties, but nothing works. Any ideas?


text:
Q: Movement of fingers expressing shyness What is name of the action for when your fingers "caress" one another because you're shy?

A: Perhaps you are referring to fidgeting:

to move about restlessly, nervously, or impatiently. – dictionary.com

to make a lot of small movements because you are nervous, bored, etc. :
  to move or act in a nervous or restless way – Merriam-Webster


text:
Q: CleverCSS complaining when using gradient functions, is there a way to avoid this? I'm trying to use -webkit-linear-gradient inside of CleverCSS.  However, when I try to "compile" it, I get an error of TypeError: not enough arguments for format string
Here is the CleverCSS
button:
    background-image: -webkit-linear-gradient(top, #fff, #e6e6e6)

If I throw that into clevercss.convert(), that's the error I get. I see that parenthesis have special meaning in CleverCSS, but I'm unsure if this is a result of that or not.  Is there a way to have CleverCSS process this?

A: Use the backtick operator for verbatim CSS:
background-image: `-webkit-linear-gradient(top, #fff, #e6e6e6)`

The "official" PyPI version of CleverCSS isn't maintained and may not have that feature; get an updated version from Github.


text:
Q: How to construct nest/elastic search query I don't have a lot of experience constructing elasticsearch queries.  I basically want to construct a query where the results are for a specific record (job record in this case) and the notes contain keywords.  I have the following query constructed with nest and the job I'm searching on has all the keywords I'm looking for, so I'm not sure why it's not coming up as a match.  I'm also not sure if the terms under filter are treated as ORs or ANDs.  If I don't include any keywords so it only searches on the job id, it comes up fine.
{
    "from": 0,
    "query":
    {
        "bool":
        {
            "filter":
            [
                {
                    "term":
                    {
                        "notes":
                        {
                            "value": "electrical"
                        }
                    }
                },
                {
                    "term":
                    {
                        "notes":
                        {
                            "value": "engineer"
                        }
                    }
                },
                {
                    "term":
                    {
                        "notes":
                        {
                            "value": "recommend"
                        }
                    }
                }
            ],
            "must":
            [
                {
                    "term":
                    {
                        "job_id":
                        {
                            "value": 16472
                        }
                    }
                }
            ]
        }
    },
    "size": 20,
    "sort":
    [
        {
            "last_modified_date":
            {
                "order": "desc"
            }
        }
    ]
}

And here's the c# nest code to construct the query.
var client = new ElasticClient(settings);

var terms = !string.IsNullOrWhiteSpace(viewModel.Keyword) ? viewModel.Keyword.Split(' ').Select(x => x.Replace(",", "").Replace(".", "")) : Array.Empty<string>();

var filterContainer = new List<QueryContainer>();
var mustContainer = new List<QueryContainer>();

foreach (var term in terms)
    filterContainer.Add(new TermQuery {Field = "notes", Value = term.ToLower()});

if (viewModel.Job && viewModel.JobId.HasValue)
    mustContainer.Add(new TermQuery
    {
        Field = "contract_job_id",
        Value = viewModel.JobId.Value
    });

var boolQuery = new BoolQuery
{
    Filter = filterContainer,
    Must = mustContainer
};

var searchRequest = new SearchRequest<NotesAll>
{
    From = viewModel.Page * retval.PageSize,
    Size = retval.PageSize,
    Query = boolQuery,
    Sort = new List<ISort>
    {
        new FieldSort {Field = "last_modified_date", Order = SortOrder.Descending}
    }
};

var searchResponse = client.Search<NotesAll>(searchRequest);

Edit: Index mapping
{
  "notes" : {
    "mappings" : {
      "properties" : {
        "EnteredDateString" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "action_type_id" : {
          "type" : "long"
        },
        "agency_key_id" : {
          "type" : "float"
        },
        "automated" : {
          "type" : "boolean"
        },
        "company_id" : {
          "type" : "float"
        },
        "company_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "job_id" : {
          "type" : "float"
        },
        "entered_date" : {
          "type" : "date"
        },
        "firm_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "id" : {
          "type" : "long"
        },
        "last_modified_date" : {
          "type" : "date"
        },
        "last_modified_employee_id" : {
          "type" : "float"
        },
        "notes" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "notes_type_id" : {
          "type" : "long"
        },
        "people_id" : {
          "type" : "float"
        },
        "person_first_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "person_last_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "position_title" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "recruiter_first_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "recruiter_key_id" : {
          "type" : "float"
        },
        "recruiter_last_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "employee_id" : {
          "type" : "float"
        }
      }
    }
  }
}


text:
Q: System of (in)equalities in $\mathbb{Z}_p$. In the sequel, $\mathbb{Z}_p$ denotes the cyclic group of integers modulo $p$.
Working to a problem in Algebraic Geometry, I was led to state the following
Conjecture. Given every positive integer $b \geq 2$ and every odd prime $p$, it is possible to find non-zero elements $$\lambda_1, \ldots, \lambda_b, \, \; \mu_1, \ldots, \mu_b \in \mathbb{Z}_p$$ such that
\begin{cases} \sum_{i=1}^b \lambda_i =1 \\ \sum_{i=1}^b \mu_i =1 \\ \lambda_i\mu_i \neq 1 \; \mathrm{for \, all \, } i.
\end{cases}
I was able to verify it in many cases, but so far I could not find a general and easy proof. I suspect that an easy counting argument (that at the moment I do not see) might do the job, so I apologize in advance if the answer to the following question turns out to be trivial.

Q. Is the conjecture above true? If so, what is a clean and simple proof for it?

A: Choose arbitrarily $\lambda_i,\,i=1,\cdots,b-1$ and $\mu_i,\,i=1,\cdots,b-2$ such that $\lambda_i\cdot\mu_i\ne1,\,\forall i=1,\cdots,b-2$. (Then $\lambda_b$ is uniquely determined by $\lambda_b=1-\sum_{i=1}^{b-1}\lambda_i$.) Then $\mu_{b-1}$ and $\mu_b$ are subject to conditions: $\mu_{b-1}+\mu_b$ is a constant ($c:=1-\sum_{i=1}^{b-2}\mu_i$), and $\mu_{b-1}\ne\lambda_{b-1}^{-1},\,\mu_{b}\ne\lambda_{b}^{-1}$. The last two conditions are equivalent with $\mu_{b-1}\ne\lambda_{b-1}^{-1},\,c-\lambda_b^{-1}$. If $p>3$ then clearly this is possible as there are more than two non-zero elements in $\mathbb Z_p$. The only case where this is impossible is when $p=3$ and $\left\{\lambda_{b-1}^{-1},\,c-\lambda_b^{-1}\right\}=\left\{1,2\right\}$.
In fact when $p=3$, the condition $\lambda_i\cdot\mu_i\ne1$ implies that $\mu_i=-\lambda_i,\,\forall i$, and hence $\sum_{i=1}^{b}\mu_i=-\sum_{i=1}^{b}\lambda_i=-1$, so it is impossible to find elements satisfying the requirements when $p=3$.

Hope this helps.


text:
Q: What is the idiomatic way to convert an Array of Dict to a DataFrame I'm trying to convert an Array of Dict to a DataFrame. What is the idiomatic way to do this.
using HTTP, JSON

function getBody(resp)
    jsonb=String(resp.body)
    bodyData = JSON.parse(jsonb)
end

function histoday()
    base_url="https://min-api.cryptocompare.com"
    path= "data/histoday?fsym=BTC&tsym=USD&limit=100"
    url="$base_url/$path"
    bd = getBody(HTTP.get(url))["Data"]
end

histoday()

A: One way would be
x = histoday()
vcat(DataFrame.(x)...)


text:
Q: Django unable to persisted cached array Django cannot persist my cached data even if I set timeout to none.
My settings.py contains this:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'django_cache', #'/var/tmp/django_cache',
        'TIMEOUT': None,
    }
}

I save data with this line of code:
cache.set('array', array, timeout=None)

I fetch data like this:
array = cache.get('array')

try:
     iterator = iter(array)
except TypeError:
     # Array not iterable: my app gets here when cache data is lost
else:
     # I go through the array and get needed info

I don't think it's a MAX_ENTRIES issue because I only have one array with 39 elements.
When the data is lost, the array becomes not iterable (because empty).
I also tried using file cache cause I suspected that restarting the Django app may clear the RAM cache but had the same issue.
I've tried file caching with the following configuration in settings.py:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': os.path.join(BASE_DIR, 'filecache'),
        'TIMEOUT': None,
    }
}

The "filecache" directory is created and contains a non-empty cache file but I still loose my cached array somehow.


text:
Q: Event Hub Producer with Websockets through API Gateway Can anyone advise what connection parameters are needed in an EH Producer client when using a Proxy.
I am actually using a API Gateway with AMQP Support (CA Layer7) with an outbound proxy.
Does the connection string for "String Endpoint" need to be my Proxy target  or the Event Hub connection string?

A: Your connection string would not change; the Endpoint token should still point to the Event Hubs endpoint.   To use a proxy, you'll need to set the configuration with the options used to construct the producer.   You don't mention the specific language that you're using, so I'll illustrate with the .NET SDK.   The general form would look something like:
var connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>";
var eventHubName = "<< NAME OF THE EVENT HUB >>";

var producerOptions = new EventHubProducerClientOptions();
producerOptions.ConnectionOptions.TransportType = EventHubsTransportType.AmqpWebSockets;
producerOptions.ConnectionOptions.Proxy = new WebProxy("https://proxyserver:80", true);

var producer = new EventHubProducerClient(
    connectionString,
    eventHubName,
    producerOptions);

More discussion and examples can be found in repository samples here.


text:
Q: How to compare between two images using VB.net? I have a small bitmap image and I will do a screenshot. I need to find whether the small image is the screenshot. How I can compare two bitmap images? and then return the coordinates.
If it is MATLAB, (NOTE: I need VB.net)
What my plan is this
screenshot
for x_screen = 1: screen_width_x
     for y_screen = 1: screen_col_y
      for x_pic = = 1: pic_width_x
       for y_pic = = 1: pic_col_y
       if screenshot(x_screen, y_screen) != pic(x_pic , y_pic)
       break
       end
    end
    xx = (x_screen)
    yy = (y_screen)
    end
    end

A: See  Image comparison if you want something advanced Also you can look for machine learning techniques for such tasks.
Here is naive solution and not optimized one (plus it is better to do such tasks in native code):
Plus Note that it is better to check this with bmp files. otherwise it will not handle problem
Private Function FindSubImg2(img As Bitmap, subimg As Bitmap) As Point
    If (img.Width - subimg.Width < 0) Or (img.Height - subimg.Height < 0) Then Return Nothing
    Dim stepxLen As Integer = img.Width - subimg.Width
    Dim stepyLen As Integer = img.Height - subimg.Height
    Dim coor As Point
    Dim match As Boolean = False

    For oy As Integer = 0 To stepyLen
    For ox As Integer = 0 To stepxLen
            match = True
            For x As Integer = 0 To subimg.Width - 1
                For y As Integer = 0 To subimg.Height - 1
                    'actually here we do not need ToArgb method. But it will skip unneeded Color comparisions
                    If img.GetPixel(x + ox, y + oy).ToArgb <> subimg.GetPixel(x, y).ToArgb Then
                        match = False
                        Exit For 'we can use goto operator instead of double exit for
                    End If
                Next
                If match = False Then Exit For
            Next
            If match = True Then
                coor.X = ox
                coor.Y = oy
                Return coor
            End If
        Next
    Next

    Return New Point(-1, -1)
End Function

Private Function FindSubImg(a As Bitmap, b As Bitmap) As Point

    Dim subimg As Bitmap
    Dim img As Bitmap

    If (a.Height <= b.Height AndAlso a.Width <= b.Width) Then
        subimg = a : img = b
        Return FindSubImg2(img, subimg)

    ElseIf (a.Height > b.Height AndAlso a.Width > b.Width) Then
        subimg = b : img = a
        Return FindSubImg2(img, subimg)
    Else
        Return New Point(-1, -1)
    End If

End Function

Usage:
Dim p As Point = FindSubImg(New Bitmap("A.bmp"), New Bitmap("B.bmp"))

A: Try something like this:
Public Function CompareImages(ByVal img1 As Bitmap, ByVal img2 As Bitmap) As Boolean
    Dim i As Integer
    Dim j As Integer

    For i = 0 To img1.Width - 1
        For j = 0 To img2.Height - 1
            If img1.GetPixel(i, j) <> img2.GetPixel(i, j) Then
                Return False
            End If
        Next
    Next
    Return True
End Function

sample call:
CompareImages(New Bitmap("f:\img1.bmp"), New Bitmap("f:\img2.bmp"))


text:
Q: Fetching values of components in JPanel I have two JPanels in a Jframe. The upper panel has one JCombobox. The lower panel is dynamically populated by various components on basis of the selection in combobox in upper panel. The type and number of components to be added to lower panel is always dynamic. An example below -
Lower JPanel:
JLabelA: JCombobox
JLabelB: JCombobox + JTextfield
JLabelC: JCombobox1 + JCombobox2 + JCombobox3
JLabelD: JList
A user can select/type in values in desired components and then click on a Submit button. On the click of button. I need to do custom validation (e.g. some components are mandatory, some optional and in case of JLabelC above, values have been selected in all the three comboboxes). Once all the validation is passed, I need to fetch the user selected/provided values in the lower panel. Note that the names of components in lower panel are not fixed, so I can not directly fetch the values. One approach is to traverse all the components in the lower panel one by one and pick the values. This does not seem very efficient since I will need to traverse all while I need to traverse only those where user has provided some input.
Queries-
1) How can we attach the validations to components (as we can do in JavaScript validations)?
2) Please suggest alternate approaches for fetching the values of components.

A: I have seen (legacy) code that traversed JComponents and bound/unbound a multi-purpose listener to combo-boxes, text-fields, etc. I recall it working (it was for attaching "dirty" listener to all the editable widgets to that prevent the user from leaving unsaved changes behind).
If you want to do real-time validation, you can attach ChangeListeners or ActionListeners to the JComboBoxes or JLists and DocumentListeners to the JTextField documents. I've tried using InputVerifiers, but it's usually a problem for the user when you screw around with component focus.


text:
Q: Поведение высоты и ширины в em Добрый день почему em не слушаются, font-size.
Происходит такое на chrome Версия 75.0.3753.4 (Официальная сборка), dev (64 бит).
Так же повторяется на chrome Версия 73.0.3683.103 (Официальная сборка), (64 бит).
Вверху как должно быть.

P.S. Начинает работать как надо в выше указанных браузерах если указан font-size больше 6px.

span:before {
    display: inline-block;
    content: "";
    font-size: 1.3px;
    width: 10em;
    height: 11em;
    margin-right: 3px;
    vertical-align: middle;
    position: relative;
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 11" style="fill:rgb(198, 161, 113);"><path d="M7.8,8.7C7,9.4,6.1,9.8,5,9.8c-0.1,0-0.1,0-0.2,0c-0.8,0-1.5-0.3-2.1-0.7l0.1,0.7v0c0,0.2-0.1,0.4-0.3,0.4 c0,0,0,0,0,0h0C2.2,10.2,2,10,2,9.8L1.9,8.2c0-0.2,0.1-0.4,0.4-0.4l1.6-0.1c0.2,0,0.4,0.1,0.4,0.4c0,0.2-0.1,0.4-0.4,0.4L3.2,8.4 C3.8,8.8,4.4,9,5,9c0.8,0,1.6-0.3,2.2-0.9c0.9-0.8,1.3-2.1,1-3.4C8.2,4.5,8.3,4.3,8.6,4.3C8.8,4.2,9,4.3,9,4.6 C9.4,6.1,8.9,7.7,7.8,8.7z"/><path class="st0" d="M1.7,6.3c0.1,0.2-0.1,0.4-0.3,0.5c0,0-0.1,0-0.1,0C1.2,6.8,1,6.6,1,6.4C0.6,4.9,1.1,3.3,2.2,2.3 c0.8-0.8,1.9-1.2,3-1.1C6,1.3,6.7,1.5,7.3,2l0-0.7c0-0.2,0.1-0.4,0.4-0.4C7.9,0.8,8,1,8.1,1.2l0.1,1.6v0c0,0.2-0.2,0.4-0.4,0.4 L6.2,3.3h0c0,0,0,0,0,0C5.9,3.3,5.8,3.2,5.7,3c0-0.2,0.2-0.4,0.4-0.4l0.6,0c-1.2-0.8-2.9-0.7-4,0.4C1.8,3.7,1.4,5,1.7,6.3L1.7,6.3z"/></svg>');
}
Hello

A: В некоторых браузерах по умолчанию стоит ограничение минимального размера шрифта. То есть, можно задать хоть 0.0001em,  но результат будет не меньше некоего заданного значения.
Делалось это с целью борьбы с Васями Пупкиными, которые использовали слишком мелкий шрифт по причине тупости или желания, например, насовать на страницу список ключевых слов текстом нулевого размера.
Так что: а) проверьте ваш браузер (у меня в современном хроме все норм) и б) не используйте инструменты не по назначению.


text:
Q: Angular - Sending a value with button press I am making a chord player in Angular, and for each button, would like to send a value with the particular chord.  I wondering what the best way of doing this is.
In my index.html
<button class="chord-btn" ng-option="c" model="note" ng-click="ctrl.changeChord(note)">C major</button>

And in my controller.js....
app.controller('ChordController', [function() {

var self = this;

self.changeChord = function(note) {
  alert("Chord to be played is"+ note);
};
}]);

Currently when I click the button, the alert says that the note 'is undefined'.  Would greatly appreciate anyones thoughts, I am new to Angular and suspect I am doing something silly.

A: You have to inject $scope in your controller. $scope is the glue between your view and your controller. Then, add your function to the $scope object. The following code should do the trick.
app.controller('ChordController', function($scope) {

    $scope.changeChord = function(note) {
        alert("Chord to be played is"+ note);
    };
});


text:
Q: What does the skiplistnode variable "span" mean in redis.h? In redis.h, the skipnode is defined as below:
typedef struct zskiplistNode {
    robj *obj;
    double score;
    struct zskiplistNode *backward;
    struct zskiplistLevel {
        struct zskiplistNode *forward;
        unsigned int span;
    } level[];
} zskiplistNode;

What does the var span mean? What does this var store?

A: span at a particular node stores the number of nodes between the current node and node->forward at the current level. span is used to calculate the 1-based rank of element in the skip list.
For example, consider the following skip list :

Consider the head node. The span at all levels will be 1.
Consider node 1. At level 0, the span is 1, because you will span 1 element if you follow the forward pointer. At level 1, span is 2 because you will span 2 elements (node 2 and node 3) if you follow the forward pointer.
Take a look at the function zslGetRank in t_zet.c. You can see how the rank is calculated from the value of span at each level.


text:
Q: How can I share info among @Composable function in Android Studio? In order to reduce complex, I need to split a big  @Composable function to small parts, and I need to share info such as variables among them.
At present, I use Code A to do it by using top variables, I don't think it's a good.
How can I share info among @Composable function in Android Studio?
Code A
private var paddingXAxis = 80f
private var paddingXLabelMargin = 8f
private var paddingYAxis =50f
private var xAxisLength = 100f
private var yAxisLength = 100f
private var maxPointCount = 40

@Composable
fun ScreenHome_Table(
    modifier: Modifier = Modifier,
    mViewMode: SoundViewModel
) {
    Box( ) {

        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .padding(10.dp)
        ) {
            setParameterTable(this, mContext)
            setProcess(this, uiMSoundDensity.soundList.toList())
            setMainAxis(this)
            setChildXAxis(this, xTime)
            setChildYAxis(this)
        }
    }
}

fun setParameterTable(drawScope: DrawScope, mContext: Context) {
    with(drawScope) {
        xAxisLength = size.width - paddingXAxis * 2
        yAxisLength = size.height - paddingYAxis * 2
    }
    maxPointCount = mContext.resources.getInteger(R.integer.maxCount)
    divisionUnit = mContext.getString(R.string.divisionUnit)
     ...
}

fun setMainAxis(drawScope: DrawScope) {
    ...
}

A: You can do this by creating a class that contains properties as default Composables such as Text, TextField or Button use. A class wraps many properties.
  TextStyle(
        color = textColor,
        fontSize = fontSize,
        fontWeight = fontWeight,
        textAlign = textAlign,
        lineHeight = lineHeight,
        fontFamily = fontFamily,
        textDecoration = textDecoration,
        fontStyle = fontStyle,
        letterSpacing = letterSpacing
    )

this class is used by BasicText
fun BasicText(
    text: String,
    modifier: Modifier = Modifier,
    style: TextStyle = TextStyle.Default,
    onTextLayout: (TextLayoutResult) -> Unit = {},
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
)

TextFieldColors is another example of this
private class DefaultTextFieldColors(
    private val textColor: Color,
    private val disabledTextColor: Color,
    private val cursorColor: Color,
    private val errorCursorColor: Color,
    private val focusedIndicatorColor: Color,
    private val unfocusedIndicatorColor: Color,
    private val errorIndicatorColor: Color,
    private val disabledIndicatorColor: Color,
    private val leadingIconColor: Color,
    private val disabledLeadingIconColor: Color,
    private val errorLeadingIconColor: Color,
    private val trailingIconColor: Color,
    private val disabledTrailingIconColor: Color,
    private val errorTrailingIconColor: Color,
    private val backgroundColor: Color,
    private val focusedLabelColor: Color,
    private val unfocusedLabelColor: Color,
    private val disabledLabelColor: Color,
    private val errorLabelColor: Color,
    private val placeholderColor: Color,
    private val disabledPlaceholderColor: Color
)

Second option is to create a class that contains properties  and can act a State wrapper for other MutableStates. With this approach can trigger recomposition on any individual property change, pass or observe latest properties unlike first approach.
    class BadgeState(
        var maxNumber: Int = 99,
        var circleShapeThreshold: Int = 1,
        @IntRange(from = 0, to = 99) var roundedRadiusPercent: Int = 50,
        backgroundColor: Color,
        var horizontalPadding: Dp = 4.dp,
        var verticalPadding: Dp = 0.dp,
        textColor: Color,
        var fontSize: TextUnit,
        var fontWeight: FontWeight? = null,
        var fontFamily: FontFamily? = null,
        var fontStyle: FontStyle? = null,
        var textDecoration: TextDecoration? = null,
        var shadow: MaterialShadow? = null,
        var borderStroke: BorderStroke? = null,
        showBadgeThreshold: Int = Int.MIN_VALUE,
    ) {
{
    var backgroundColor by mutableStateOf(backgroundColor)

    /*
        Properties for Text
     */
    var textColor by mutableStateOf(textColor)

    var text by mutableStateOf("0")
        private set

    var numberOnBadge by mutableStateOf(0)
        private set

    var showBadgeThreshold by mutableStateOf(showBadgeThreshold)
    ...
}

And wrap it with remember to not create new instance on each recomposition
fun rememberBadgeState(
    maxNumber: Int = 99,
    circleShapeThreshold: Int = 1,
    @IntRange(from = 0, to = 99) roundedRadiusPercent: Int = 50,
    backgroundColor: Color = Color.Red,
    horizontalPadding: Dp = 4.dp,
    verticalPadding: Dp = 0.dp,
    textColor: Color = Color.White,
    fontSize: TextUnit = 14.sp,
    fontWeight: FontWeight? = null,
    fontFamily: FontFamily? = null,
    fontStyle: FontStyle? = null,
    textDecoration: TextDecoration? = null,
    shadow: MaterialShadow? = null,
    borderStroke: BorderStroke? = null,
    showBadgeThreshold: Int = Int.MIN_VALUE,
): BadgeState {
    return remember {
        BadgeState(
            maxNumber,
            circleShapeThreshold,
            roundedRadiusPercent,
            backgroundColor,
            horizontalPadding,
            verticalPadding,
            textColor,
            fontSize,
            fontWeight,
            fontFamily,
            fontStyle,
            textDecoration,
            shadow,
            borderStroke,
            showBadgeThreshold
        )
    }
}

You can pass this state between you Composables
@Composable
fun Badge(
    modifier: Modifier = Modifier,
    badgeState: BadgeState = rememberBadgeState(),
) {

    val showBadge = remember {
        derivedStateOf {
            badgeState.showBadgeThreshold < badgeState.numberOnBadge
        }
    }

    if (showBadge.value) {
        BadgeComponent(badgeState = badgeState, modifier = modifier)
    }
}

or you can pass to a Modifier you created
private fun Modifier.getBadgeModifier(
    badgeState: BadgeState,
    shape: Shape
) = this
    .materialShadow(badgeState = badgeState)
    .then(
        badgeState.borderStroke?.let { borderStroke ->
            this.border(borderStroke, shape = shape)
        } ?: this
    )
    .background(
        badgeState.backgroundColor,
        shape = shape
    )

or another one
fun Modifier.materialShadow(badgeState: BadgeState) = composed(
    inspectorInfo = {
        name = "shadow"
        value = badgeState.shadow
    },
    factory = {
   // rest of the code
}


text:
Q: fid of a default image in Drupal 7 - managed_file field. What to set default value of fid to? I've got this image upload field in Drupal 7 with:
'#default_value' => variable_get('default_img_fid', ''),

However, I'm not sure how to set that variable so that when Drupal senses there is no uploaded image and the form is submitted, it will gather the information for the default image. I've placed the image in the sites/default/files/images folder.
What do I set:
variable_set('default_img_fid', '?????');

to?
Thanks

A: A file doesn't have a fid until it's in the file_managed table. If you've uploaded the file manually then you'll also need to register it manually in the file_managed table.
Just take one of the other rows in there as a base example and work from there, once the record's been inserted you'll have the fid you need :)


text:
Q: Getting duplicate iOS notifications from IFTTT I use IFTTT to send me iOS notifications for some of my recipes, but for some reason, every time it sends me a notification, it sends it twice. So every notification I get from IFTTT is duplicated.
Anyone know why this happens, and how I can fix it?

A: I just fixed this. What I did was I deleted the iOS Notifications channel, then deleted the app from my iPhone, then re-installed the app, re-activated the channel, and re-created the recipe.

A: This problem occurs when you have more than one Apple device with IFTTT installed with reminder access turned on. When the app gets triggered both devices write to your reminder list. You can fix this by deleting IFTTT from either device.  Or, by not allowing one of the IFTTT apps on either device to access to reminders. Remember, one of them has to be able to write to your Reminders or the recipe won't work. But just allow one.


text:
Q: Deny log on through Remote Desktop via powershell I have to deny log on through windows RDP. I know, I can do it by gpedit.msc in
 Computer Configuration --> Windows Settings --> Security Settings -->
 Local Policies --> User rights assignment

But I have to do it by powershell.
Is it possible?

A: But why not just use GPO?
If this is an enterprise environment, that is why it's there and the recommended way to do this sort of thing and much of Windows enterprise central management. Oh well, orgs have their reasons for what things are.
Anyway, there are many resources and samples on how to do this all over the web.
Using you post title in any search engine, would return many hits on the topic.
For example:

MS PowerShell gallery scritps
Get, Set, Remove NT Rights Privileges for example, adding "Logon As
  Service" right to User Account. Get, Set, Remove NT Rights Privileges
  on local and remote computers
https://gallery.technet.microsoft.com/Get-Set-Remove-NT-Rights-0a8a36db
How to Remotely Enable and Disable (RDP) Remote Desktop
By default on a Windows Server Product Windows Remote Management
  (WinRM) is enabled, but Remote Desktop (RDP) is Disabled.  On
  workstation operating systems neither is enabled by default, so if you
  want to be able to accomplish the following you will need to enable
  WinRM on the workstations.
https://www.interfacett.com/blogs/how-to-remotely-enable-and-disable-rdp-remote-desktop/
How to enable Remote Desktop using Powershell
If you are using Windows 2012 R2 Core or if you just like using
  Powershell, then you may want to know how to enable Remote Desktop.
To do this, you should go into your Core server where you should see a
  command box. In here, type in Powershell and press enter. This will
  open up the Powershell console for you to use.
https://blog.techygeekshome.info/2014/07/how-to-enable-remote-desktop-using-powershell
PowerShell Problem Solver: Active Directory Remote Desktop Settings
During my recent PowerShell workshop in Finland, an attendee asked
  about Active Directory cmdlets from Microsoft in regards to remote
  desktop user settings. Although you can readily see the settings in
  Active Directory Users and Computers, Get-ADUser doesn't retrieve
  them. I haven't worked with Remote Desktop Services in quite a while,
  but I told him I'd look into this long-standing problem.
https://www.petri.com/powershell-problem-solver-active-directory-remote-desktop-settings

Then there is NTRights tool from the WiNTResKit.

The Microsoft® Windows® Server 2003 Resource Kit Tools are a set of
  tools to help administrators streamline management tasks such as
  troubleshooting operating system issues, managing Active Directory®,
  configuring networking and security features, and automating
  application deployment.
https://www.microsoft.com/en-us/download/details.aspx?id=1765

Yes, it and viraully all the tools in the Reskit still work, even on Win01/WS2K16.
So, doing something like this....
$ADUser = [ADSI]"LDAP://CN=UserName,OU=Users,DC=TestDomain,DC=com"
$ADUser.SamAccountName #to check the account
$ADUser.psbase.invokeSet("allowLogon",0)
$ADUser.setinfo()


text:
Q: Getting 'Unable to translate collection subquery' in the mapper when doing Join in the EF Core I am trying to join several results of LINQ queries in the EF Core
var frameworkOrg = context.Applications
    .Where(c => c.Certifications.Select(f => f.Framework).Any(fr => fr.Name == search.Framework))
    .Select(apporg => apporg.Organization)
    .Select(t => t);

var coveredDataOrg = context.Applications
    .Where(c => c.PrivacyPolicies.Any(pp => pp.Type == search.DataCovered))
    .Select(apporg => apporg.Organization)
    .Select(t => t);

var orgResult = frameworkOrg.Union(coveredDataOrg);
var organizationModel = mapper.ProjectTo<Models.Organization>(orgResult).ToList();

But when I am trying to map the results, I get an error below.

Unable to translate collection subquery in projection since the parent
query doesn't project key columns of all of it's tables which are
required to generate results on client side. This can happen when
trying to correlate on keyless entity or when using 'Distinct' or
'GroupBy' operations without projecting all of the key columns.

If I don't use the join, however, and place frameworkOrg or coveredDataOrg into a mapper, there is no error
How can I fix my join statement to avoid the error in the mapper?
Thank you in advance

A: Try to combine results in one Where. Union has limitations in translation, especially for navigation properties:
var orgResult = context.Applications
    .Where(c => c.Certifications.Select(f => f.Framework).Any(fr => fr.Name == search.Framework)
      || c.PrivacyPolicies.Any(pp => pp.Type == search.DataCovered)
    )
    .Select(apporg => apporg.Organization);

var organizationModel = mapper.ProjectTo<Models.Organization>(orgResult).ToList();

If you need to build predicate with OR dynamically you can use Predicatebuilder from LINQKit


text:
Q: 3d Figures giving some error in python So, a python newbie here. What I'm trying to do is to plot point onto 3d plane. Although some errors occur at execution.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

fig = plt.figure()

chart = fig.add_subplot(1,1,1,projection='3d')

X,Y,Z=[1,2,3,4,5,6,7,8],[2,5,3,8,9,5,6,1],[3,6,2,7,5,4,5,6]

chart.plot_wireframe(X,Y,Z)

plt.show()

Output:
Traceback (most recent call last):
  File "/home/nishantsikri/3d objects.py", line 10, in <module>
chart.plot_wireframe(X,Y,Z)
  File "/home/nishantsikri/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1834, in plot_wireframe
    if Z.ndim != 2:
AttributeError: 'list' object has no attribute 'ndim'