text:
Q: AngularJS: Update template binding via directive I modified the AngularUI-Bootstrap direvtive for tooltips to help me display error messages, here is what I did so far: http://jsfiddle.net/distractedBySquirrels/TaAHZ/
But I have a problem with the dynamic messages. The first time you mouseover the first input field, the message is in the wrong place, this is because the model is not correctly updated yet. Of course, after the second mouseover the tooltip is in the right place. But if the message to display changes again the same failure occurs.
I am using $parse to update the template:
$parse('tt_content').assign( scope,
    getErrorMessage( ctrl.$error ) || attrs.tooltip
);

Seems like not all the listeners have revceived and updated and "ttHeight" and "ttWidth" are still set to the "old" values. The correct update of the message/model only works with the $observe, which is illustrated by the third example.
I am stuck and don't know what I did wrong? :(

A: The problem is that when you modify your models with $apply, you need to manually activate the digest cycle in order to notify all watchers of such models. So basically, you need to add scope.$digest(); whenever you change the scope doing things like scope.$apply( show );
I modified your code with my suggestions here http://jsfiddle.net/TaAHZ/2/


text:
Q: Не работает урон от пули Народ помогите,я делаю урон от пули но при соприкосновение с обьектом с тэгом Vraginа ничего не происходит,как буддто этого обьекта и нет.Что делать??Помогите
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ammo : MonoBehaviour
{
    public float speed;
    public float destroyTime;
    public int valueDown;
    bool isAmmo = false;
    // Start is called before the first frame update
    void Start()
    {
        //Invoke("DestroyAmmo", destroyTime);
    }

    // Update is called once per frame
    void Update()
    {
            transform.Translate(Vector2.left * speed * Time.deltaTime);

    }
    void OnTriggerStay2D(Collider2D collider)
    {
        if (collider.tag == "Vragina")
        {

            Debug.Log("Da ura");
            collider.GetComponent<Creatureshealth>().health -= valueDown;
            isAmmo = true;
            if (isAmmo == true)
            {
                Destroy(gameObject);
            }

        }
    }
    //void DestroyAmmo()
    //{
    //    Destroy(gameObject);

    //}
}

A: *

*Ammo это амуниция, а пуля это Bullet

*Почему OnTriggerStay, а не OnTriggerEnter?

*События физики Stay/Enter/Exit не произойдёт с двумя неподвижными объектами. Изменение Transform это не движение а по сути телепортация, движение это Rigidbody.

*В 99.9% случаях в играх стрельба это HitScan, а трейсинг пуль просто визуал. Вычисление столкновений малого объекта на высоких скоростях слишком затратны.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to setup angularjs select to work with objects Code:
<select ng-model="ticket.owner.id"
        ng-options="user.id as getFullName(user) for user in users" required>
</select>

The above example actually works. However when I send the modified object to my rest api, the only changed value of the object is the ID. E.g. when option 1 is selected and I select option2 and submit, the object associated to option1 is send, but with the ID of option2.
When I have:
<select ng-model="ticket.owner"
        ng-options="user as getFullName(user) for user in users" required>
</select>

and change the selected value and submit, the correct object is transmitted to rest api. However the select box is broken, it shows an empty field and does not set the selected value.
Any ideas we can use the select box to select objects but not just ID's?

A: Not sure your implementation of getFullName() and what is actually
getting sent to the rest service.
http://plnkr.co/edit/U7WIe4CvPUQFJFE4NtB6?p=preview
You can see in this example, ticket.owner being one of the
object in users array that is chosen by the select box.
And selection box shows the full name of the users.
Is this what you want?


text:
Q: Выбор программ и языка для создания контента Здравствуйте,
У меня появился вопрос. Я попыталась найти в гуугле ответ, но нашла какие-то общие мысли и ничего конкретного.
Меня как начинающего программиста заинтересовало как можно создать (какие языки программирования и какие библиотеки использовать) веб сайт, который будет предоставлять услуги клиентам для создания их собственного графического контента.
Вот примеры таких сайтов. Я как обычный пользователь могу создать свой сайт с определенным дизайном и отредактировать фотографию, использую разные фильмы и разную функциональность.
https://www.wix.com
https://avatan.ru/#/
Я знаю, что это все популярная и известная тема, но меня за мои годы обучения в университете ни разу не сталкивали с такими рода проблемами.
(Мы программировали какие-то онлайн магазины, библиотеки, кинотеатры, а до таких вещей дело не доходило)
Если я, например, являюсь фанатом java и планирую изучить react js - возможно ли создать что-то подобное в целях самообразования, используя эти языки?
И есть ли каки-нибудь научные статьи на эти темы (может быть примеры имплементации на GitHub) или еще лучше - книги, которые могут послужить для меня альма матром при изучении данного вопроса.
Заранее спасибо за ответ и ваши комментарии!


text:
Q: Is $ z = 10 $ a removable singularity of $ f(z) = 1 + 2(z - 10) + 3(z - 10)^2 $? From Complex Variables with Applications (Orloff):

Poles refer to isolated singularities. So, we suppose $ f(z) $ is analytic on $ 0 < |z - z_0| < r $ has Laurent series
$$ f(z) = \sum_{n=1}^{\infty} \frac{b_n}{(z - z_0)^n} + \sum_{n=0}^{\infty} a_n (z - z_0)^n. $$

Then it defines:

If all the $ b_n $ are $ 0$, then $ z_0$ is called a removable singularity. That is, if we define $f(z_0) = a_0$ then $f$ is analytic on the disk $|z - z_0|< r $.

I am unable to understand this definition of removable singularity. See this $ f(z) $ for example:
$$
f(z) = 1 + 2(z - 10) + 3(z - 10)^2
$$
All coefficients $ b_n $ are $ 0 $ in the above function. By the definition above, we should call $ 10 $ to be a removable singularity. But why is $ 10 $ a singularity? The function $ f(10) = 1 $ which is a finite value. The function $ f(z) $ appears to be analytic at $ z = 10 $. Then why should we call $ z = 10 $ a removable singularity here.
Is the quoted definition of "removable singularity" correct? Am I misunderstanding the definition?


text:
Q: Запрос возвращает повторяющиеся значения есть запрос:
SELECT  name_department,  salary
FROM  listdep, (SELECT DISTINCT salary FROM listworker ORDER BY salary DESC)
WHERE ROWNUM < 6;

Вывод:

Как исправить, чтобы он не возвращал повторяющиеся значения ?


text:
Q: Minimize / miniaturize cocoa NSWindow without titlebar I'm stuck!  Obviously... because I'm posting a question here.
I have built my own custom window controls for my OS X / cocoa app.  The close button works great -- no problems.  The minimize button doesn't work at all when I disable the titlebar.

So when the title bar is on like the image above and I hit this method, the minimizing works fine:
ViewController.h
@interface ViewController : NSViewController {

    - (IBAction)minimize:(id)sender;
    @property (strong) IBOutlet NSButton *btn_minimize;

}
@end

ViewController.m
@implementation ViewController

    - (void)viewDidLoad {
        [super viewDidLoad];
    }

    - (IBAction)minimize:(id)sender {
      [[NSApp mainWindow] performMiniaturize:self];
    }

    -(IBAction)terminate:(id)sender {
        [NSApp terminate:self];
    }
@end

Then if I disable the title bar, that same method stops working.  No errors, nothing.  I've tried both: [[NSApp mainWindow] miniaturize:nil]; and also [[NSApp mainWindow] performMiniaturize:self];.  Neither of which worked.  Actually... the both work IF the title bar is on.  But once I turn it off, neither work.

Thoughts / comments?
Oh, I'm using Storyboards, Xcode 7, and am targeting 10.10 and using the 10.11 SDK if that matters at all.
Thanks in advance.

A: You have to keep the original "traffic light" buttons around and hide them manually.
Here's how I've configured the window:
self.titleVisibility = NSWindowTitleHidden;
self.titlebarAppearsTransparent = YES;
self.movableByWindowBackground = YES;

And here's how I've hidden the traffic lights:
for (id subview in self.contentView.superview.subviews) {
    if ([subview isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")]) {
        NSView *titlebarView = [subview subviews][0];
        for (id button in titlebarView.subviews) {
            if ([button isKindOfClass:[NSButton class]]) {
                [button setHidden:YES];
            }
        }
    }
}

See sample project here.

A: In my case, I wanted to completely remove the title bar and trigger the miniaturization through some other means (eg: a key assignment).
I found that ensuring that the window style mask includes NSMiniaturizableWindowMask was required in order for NSWindow::miniaturize to have an effect.

A: Adding to Wez Furlong's answer, this is how to do it in Swift 5.
Assuming you have an NSWindow named "theWindow", do the following:
theWindow.styleMask = theWindow.styleMask.union(.miniaturizable)

Basically, you perform a set union of the window's existing style mask with the .miniaturizable option.


text:
Q: Getting Twitter Access Secret using DotNetOpenAuth in MVC4 I'm creating an app with MVC4 that will authorize users using Twitter and lets them tweet from the app as well. I'm able to get the user authenticated without a problem using the BuiltInOAuthClient.Twitter that is in MVC4. http://www.asp.net/web-pages/tutorials/security/enabling-login-from-external-sites-in-an-aspnet-web-pages-site
I have the access token, and oauth_verifier, but I need to get the acess_secret back from Twitter as well. https://dev.twitter.com/docs/auth/implementing-sign-twitter
What I'm missing is how to pass the oauth_verifier back to Twitter to get the access secret using OAuthWebSecurity.
Again, I can use Twitter for the login ok, but I need to be able to use twitter as the user as well. I've done this with the TweetSharp library before, but am trying to use DotNetOpenAuth on this project.
UPDATE:
I'm using the OAuthWebSecurity class as described in the first link to manage authentication. OAuthWebSecurity.RegisterClient in the AuthConfig expects a DotNetOpenAuth.AspNet.IAuthenticationClient. You can't swap that out with the TwitterConsumer class as suggested.
I can use the "built in" DotNetOpenAuth authentication piece as described in the first link, OR I can use custom code to do the full authorization, but I'm trying to find a way to do both.
I can do it separately, but then the user is presented with the Twitter dialog twice (once to login and once to authorize). I'm hoping there's a way to use the already wired up authentication piece that uses OAuthWebSecurity but ad the authorization piece as well.

A: The DotNetOpenAuth.AspNet.Clients.TwitterClient class only allows authentication, not authorization.  So you wouldn't be able to post tweets as that user if you use that class.
Instead, you can use DotNetOpenAuth.ApplicationBlock.TwitterConsumer, which does not share this limitation and you can even copy the source code for this type into your application and extend it as necessary.
You should be able to enhance the TwitterConsumer class (once you've copied it into your own project) to implement the required interface so that the OAuthWebSecurity class will accept it.  Otherwise, you can just use TwitterConsumer directly yourself to both authenticate and authorize your web app so the user only sees Twitter once but you get all the control you need.  After all, folks using ASP.NET have been using TwitterConsumer to both login and authorize for subsequent calls to Twitter for long before OAuthWebSecurity even existed.

A: I've been banging my head against a wall with this for a few days now, but I finally have something that works. Would be interested to know if it's a valid solution though!
First off, create a new OAuthClient:
public class TwitterClient : OAuthClient
{
    /// <summary>
    /// The description of Twitter's OAuth protocol URIs for use with their "Sign in with Twitter" feature.
    /// </summary>
    public static readonly ServiceProviderDescription TwitterServiceDescription = new ServiceProviderDescription
    {
        RequestTokenEndpoint =
            new MessageReceivingEndpoint(
                "https://api.twitter.com/oauth/request_token",
                HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
        UserAuthorizationEndpoint =
            new MessageReceivingEndpoint(
                "https://api.twitter.com/oauth/authenticate",
                HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
        AccessTokenEndpoint =
            new MessageReceivingEndpoint(
                "https://api.twitter.com/oauth/access_token",
                HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
        TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
    };

    public TwitterClient(string consumerKey, string consumerSecret) :
        base("twitter", TwitterServiceDescription, consumerKey, consumerSecret) { }

    /// Check if authentication succeeded after user is redirected back from the service provider.
    /// The response token returned from service provider authentication result.
    protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
    {
        string accessToken = response.AccessToken;
        string accessSecret = (response as ITokenSecretContainingMessage).TokenSecret;
        string userId = response.ExtraData["user_id"];
        string userName = response.ExtraData["screen_name"];

        var extraData = new Dictionary<string, string>()
                            {
                                {"accesstoken", accessToken},
                                {"accesssecret", accessSecret}
                            };
        return new AuthenticationResult(
            isSuccessful: true,
            provider: ProviderName,
            providerUserId: userId,
            userName: userName,
            extraData: extraData);
    }
}

The important part is where you cast the response to an ITokenSecretContainingMessage. It appears that the response has the TokenSecret all along, but it is only on an internal property. By casting it, you get access to a public property. I can't say that I'm a fan of doing this, but then I also don't understand why DotNetOpenAuth the Asp.Net team have hidden the property in the first place. There must be a good reason.
You then register this client in AuthConfig:
OAuthWebSecurity.RegisterClient( new TwitterClient(
    consumerKey: "",
    consumerSecret: ""), "Twitter", null);

Now, in the ExternalLoginCallback method on the AccountController, the accessSecret is available in the ExtraData dictionary.

A: For a WebForms project template which references Microsoft.AspNet.Membership.OpenAuth in AuthConfig.cs instead of Microsoft.Web.WebPages.OAuth (MVC4 Internet Application) I was able to modify Paul Manzotti's answer to get it to work:

*

*Create a custom twitter client class that derives from DotNetOpenAuth.AspNet.Clients.TwitterClient
public class CustomTwitterClient : TwitterClient
{
    public CustomTwitterClient(string consumerKey, string consumerSecret) :
        base(consumerKey, consumerSecret) { }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
{
    //return base.VerifyAuthenticationCore(response);
    string accessToken = response.AccessToken;
    string accessSecret = (response as ITokenSecretContainingMessage).TokenSecret;
    string userId = response.ExtraData["user_id"];
    string userName = response.ExtraData["screen_name"];

    var extraData = new Dictionary<string, string>()
                    {
                        {"accesstoken", accessToken},
                        {"accesssecret", accessSecret}
                    };
    return new AuthenticationResult(
        isSuccessful: true,
        provider: ProviderName,
        providerUserId: userId,
        userName: userName,
        extraData: extraData);
}

}

*Add the custom client in AuthConfig.cs
public static void RegisterOpenAuth()
{
    OpenAuth.AuthenticationClients.Add("Twitter", () => new CustomTwitterClient(
        consumerKey: ConfigurationManager.AppSettings["twitterConsumerKey"],
        consumerSecret: ConfigurationManager.AppSettings["twitterConsumerSecret"]));
}

Ta-dow! Now you can haz access secret.

A: You can extract the oauth_token_secret from OAuthWebSecurity by designing your own TokenManager. You can register the token manager when you register your Twitter client in OAuthWebSecurity.RegisterClient.
I used this method to extract the needed values to be able to bypass the authorization step of the Linq-to-Twitter lib.
I will soon post my solution at my blog.


text:
Q: Check if date range equals today and copy values below the date range to a new cell I have multiple horizontal date ranges, and I need to see if one of them = today, and if so copy the cells values beneath the date and paste them into a new cell.

I managed to do 1 by 1 and multiple copy pastes.
Sub copyModes()

If Range("R29") = Date Then
    Range("R30:R34").Select
    Selection.Copy
    Range("P37:P41").Select
    ActiveSheet.Paste
End If

If Range("U29") = Date Then
    Range("U30:U34").Select
    Selection.Copy
    Range("P37:P41").Select
    ActiveSheet.Paste
End If

If Range("S29") = Date Then
    Range("S30:S34").Select
    Selection.Copy
    Range("P37:P41").Select
    ActiveSheet.Paste
End If

If Range("T29") = Date Then
    Range("T30:T34").Select
    Selection.Copy
    Range("P37:P41").Select
    ActiveSheet.Paste
End If

If Range("V29") = Date Then
    Range("V30:V34").Select
    Selection.Copy
    Range("P37:P41").Select
    ActiveSheet.Paste
End If

End Sub

A: You may use generic sub like this:
Sub CheckRangeAndCopy(rng As Range)
    If rng.value = Date Then
        rng.Offset(1, 0).Resize(5, 1).Copy Range("P37:P41")
    End If
End Sub

And then call it:
CheckRangeAndCopy Range("T29")
CheckRangeAndCopy Range("V29")
' and so on


text:
Q: how to integrate paypal in website I have to make a paypal integration in my website for paying person.I found a simple code
<form action="https://www.paypal.com/cgi-bin/webscr" method="POST">

To pay with PayPal now please click on the PayPal icon below:

<input type="hidden" name="cmd" value="_xclick">

<input type="hidden" name="business" value="your@paypal.email">

<input type="hidden" name="item_name" value="Order #{$order_id}">

<input type="hidden" name="amount" value="{$order_amount}">

<input type="hidden" name="currency_code" value="{$currency_iso_3}">

<input type="image" name="submit" src="http://images.paypal.com/images/x-click-but01.gif" alt="Pay with PayPal">

< /form>

Is this secure for payment ?

A: You are sending the information over SSL/TSL.
If all the certificates are current and valid, you should be fine (so MITM attacks are less likely).
It is what banks and other financial and retail organizations are using - should be OK.
However, you did not really specify your requirements for secure integration - can you provide more information?


text:
Q: pyopengl glut input After the window containing GLUT graphics appears, I would like to enter input in the terminal:
user@computer: python woop.py
# Now displaying a beautiful landscape
(cmd): season winter
# Now changing season to winter
(cmd): event meteor
# Now meteoring otherwise peaceful landscape
(cmd): season summer
# Now changing season to summer
(cmd): exit
#bye ^_^
user@computer:

Ideally I would like to integrate python cmd with GLUT's glutKeyboardFunc. My attempts failed (allows one or the other at once, not both. Also problems with whether the window or terminal had focus).
Here is some example code, which displays a spinning teapot. Currently, pressing 'm' will invoke meteory goodness (stub), but being able to enter e.g. "meteor 500" would be preferable.
#! /usr/bin/env python
'''
Code is a reduced version of http://www.seethroughskin.com/blog/?p=771
'''
import OpenGL
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

import time, sys

class dizzyTea:

    global rotY

    def __init__(self):
        self.main()

    def InitGL(self,Width, Height):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glClearDepth(1.0)
        glShadeModel(GL_SMOOTH)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
        glMatrixMode(GL_MODELVIEW)

    # The main drawing function.
    def DrawGLScene(self):
        global rotY
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()                    # Reset The View
        glTranslatef(-0.5, 0.0, -6.0)
        glRotatef(rotY,0.0,1.0,0.0)
        glutWireTeapot(1.0)
        glScalef(0.3,0.3,0.3)
        glutSwapBuffers()
        rotY += 1.0

    # The function called whenever a key is pressed. Note the use of Python tuples to pass in: (key, x, y)
    def keyPressed(self,*args):

        # If escape is pressed, kill everything.
        if args[0] == '\x1b':
            sys.exit()
        elif args[0] == 'm':
            print "Now meteoring otherwise peaceful teapot"
            # meteor shenanigans

    def main(self):
        global window
        global rotY
        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(640, 480)
        glutInitWindowPosition(0, 0)
        window = glutCreateWindow("Jeff Molofee's desecrated GL Code Tutorial")
        glutDisplayFunc(self.DrawGLScene)
        glutIdleFunc(self.DrawGLScene)
        glutKeyboardFunc(self.keyPressed)
        self.InitGL(800, 600)
        rotY = 0.0
        glutMainLoop()

if __name__ == "__main__":
    x = dizzyTea()

I can collect characters into a global string using glutKeyboardFunc, giving the same functional effect, however the user would be typing blind. "print somestring," allows printing on the same line, however the comma means the output does not get displayed whilst typing. Also "print '\b'" (backspace) doesn't work universally...
basically I don't want to have:
user@computer: python woop.py
# Now displaying a beautiful landscape
(cmd): s
(cmd): se
(cmd): sea
(cmd): seas
...etc

to type out one command
Restriction of using:

*

*pyopengl

*GLUT

(Though other answers are welcome for wayward future-people looking to solve a different problem)

A: # The function called whenever a key is pressed. Note the use of Python tuples to pass in: (key, x, y)
def keyPressed(self,*args):
    if args[0] == '\x08':
        self.keyCache = self.keyCache[:-1]
    elif args[0] == '\x1b':
        sys.exit()
    elif args[0] == 'm':
        print "Now meteoring otherwise peaceful teapot"
        # meteor shenanigans
    else:
        self.keyCache += args[0]
    sys.stdout.write(self.keyCache +"                                                  \r")#print "keypress: <",self.keyCache,">"
    sys.stdout.flush()

And add a new class variable 'keyCache'.
Then just use normal print flushing to write data to the same line.  The only hacky bit is that you have to write several blank spaces after the cached keystrokes, otherwise when you use backspace the deleted elements will still be on the screen.
Another alternative would be a parallel keyboard thread just to handle keystrokes from the command line.  The big problem there is that glut doesn't provide a nice call back for when the window closes so you'd have to figure out an alternative way to kill your thread.

A: you should use the cmd [0] framework to build your interpreter, and launch cmd.cmdloop in a separate thread.
0. http://docs.python.org/3/library/cmd.html


text:
Q: Simple linear transformation of variable in R: changing the scope of a variable. How to make it right? I am trying to change the value range of a variable (array, set of values) while keeping its properties. I don't know the exact name in math, but I mean such a kind of transformation that the variable array has exactly the same properties, the spacing between the values is the same, but the range is different. Maybe the code below will explain what I mean.
I just want to "linearly transpose" (or smth?) values to some other range and the distribution should remain same. In other words - I'll just change the scope of the variable using the regression equation y = a * x + b. I assume that the transformation will be completely linear, the correlation between the variables is exactly 1, and I calculate new variable (array) from a regression equation, actually a system of equations where I simply substitute the maximum ranges of both variables:
minimum.y1 = minimum.x1 * a + b
maximum.y2 = maximum.x2 * a + b

from which I can work out the following code to obtain a and b coefficients:
# this is my input variable
x <- c(-1, -0.5, 0, 0.5, 1)
# this is the range i want to obtain
y.pred <- c(1,2,3,4,5)

max_y = 5
min_y = 1

min_x = min(x)
max_x = max(x)
c1 = max_x-min_x
c2 = max_y-min_y

a.coeff = c2/c1
b.coeff = a.coeff-min_x
y = x * a.coeff + b.coeff
y
# hey, it works! :)
[1] 1 2 3 4 5

the correlation between the variable before and after the transformation is exactly 1. So we have a basis for further action. Let's get it as a function:
linscale.to.int <- function(max.lengt, vector) {
max_y = max.lengt
min_y = 1

min_x = min(vector)
max_x = max(vector)
c1 = max_x-min_x
c2 = max_y-min_y

a.coeff = c2/c1
b.coeff = a.coeff-min_x
return(vector * a.coeff + b.coeff)
}
x <- c(-1, -0.5, 0, 0.5, 1)
linscale.to.int(5,x)
[1] 1 2 3 4 5

and it works again. But here's the thing: when i aplly this function to random distribution, like this:
x.rand <- rnorm(50)
y.rand <- linscale.to.int(5,x.rand)
plot(x.rand, y.rand)

or better seable this:
x.rand <- rnorm(500)
y.rand <- linscale.to.int(20,x.rand)
plot(x.rand, y.rand)

I get the values of the second variable completely out of range; it should be between 1 and 20 but i get scope of valuest about -1 to 15:

And now the question arises - what am I doing wrong here? Where do I go wrong with such a transformation?

A: What you are trying to do is very straightforward using rescale from the scales package (which you will already have installed if you have ggplot2 / tidyverse installed). Simply give it the new minimum / maximum values:
x <- c(-1, -0.5, 0, 0.5, 1)

scales::rescale(x, c(1, 5))
#> [1] 1 2 3 4 5

If you want to have your own function written in base R, the following one-liner should do what you want:
linscale_to_int <- function(y, x) (x - min(x)) * (y - 1) / diff(range(x)) + 1

(Note that it is good practice in R to avoid periods in function names because this can cause confusion with S3 method dispatch)
Testing, we have:
x <- c(-1, -0.5, 0, 0.5, 1)
linscale_to_int(5, x)
#> [1] 1 2 3 4 5

x.rand <- rnorm(50)
y.rand <- linscale_to_int(5, x.rand)
plot(x.rand, y.rand)

y.rand <- linscale_to_int(20, x.rand)
plot(x.rand, y.rand)

Created on 2022-08-31 with reprex v2.0.2


text:
Q: How do you disable the are you sure you want to leave this page alert? How do you disable the are you sure you want to leave this page alert when running selenium in chrome?

A: Assuming you intend to leave the page, why not accept the alert?
driver.switchTo().alert().accept();


text:
Q: Find ways an Integer can be expressed as sum of n-th power of unique natural numbers.code giving wrong output I have t test cases.
Given two numbers x and n, find number of ways x can be expressed as sum of n-th power of unique natural numbers.
The approach is to either select a number or move to the next one.The ans returned is stored in an array since I am using the dp approach.
This is my code
#include<bits/stdc++.h>
using namespace std;

int arr[101];

int func(int x,int n,int ind)
{
    if(arr[x]!=-1)
    {
        return arr[x];
    }
    if(x==0)
    {
        return 1;
    }
    if(ind>=(sqrt(x)+1))
    {
        return 0;
    }
    if(x<0)
    {
        return 0;
    }

    //you can either take ind or just move to the next one

    arr[x]=func(x-pow(ind,n),n,ind+1)+func(x,n,ind+1);
    return arr[x];
}

int main()
{

    int t;
    cin>>t;
    while(t)
    {

        int ans=0;
        memset(arr,-1,sizeof(arr));

        int x,n;
        cin>>x>>n;

        int ind=1;
        ans=func(x,n,ind);

        cout<<"printing the ans\n"<<ans;
        t--;
    }

    return 0;
}

for input
1
10 2
I am getting
printing the ans
-297160607
though the ans is 1

A: I inserted a simple debug output in func. For the given input "1 10 2" x sometimes gets negative. This causes UB when accessing the array, but does not necessarily crash.
You already check if x is less than 0, but after using x. Move the if(x < 0) up and you are done.
In general to avoid such mistakes you should use stl containers like std::array or std::vector. Though it is not garantued by the c++ standard, many implementations will performe bounds checking on operator[] when compiled in debug mode. Or you can use at() where the standard garantuess bounds checking.


text:
Q: how can increse timeline in dhtmlxGantt tool hellow, I am using dhtmlxgantt tool for project management in My laravel app. but in My time line I can only add till 2014-12-31 but I need increse My year till 2020. how can I do this.

A: It can be done in a couple of different ways
1) You can define range using start_date/end_date options
gantt.config.start_date = new Date(2016, 0, 1);
gantt.config.end_date = new Date(2021, 0, 1);
gantt.init();//or gantt.render() if gantt is already initialized

2) Alternatively, you can tell gantt to always recalculate the time scale in order to fit all data you have in gantt (by default such calculation happens only once when you load data)
gantt.config.fit_tasks = true;

Note, that you either set date range explicitly (define start/end dates), or tell gantt to calculate it automatically (use fit_tasks config), you can't enable both.
Then you can set the date picker range in the details form:
gantt.config.lightbox.sections=[
    {name:"description", height:70, map_to:"text", type:"textarea",focus:true},
    {name:"time", year_range: [2016, 2025]  map_to:"auto", type:"duration"}
];

http://docs.dhtmlx.com/gantt/desktop__duration.html
Note, that gantt may become slow when you display huge date range. Usually, it can be fixed by enabling static_background mode and smart rendering extension. http://docs.dhtmlx.com/gantt/desktop__performance.html http://docs.dhtmlx.com/gantt/api__gantt_static_background_config.html


text:
Q: Need to scroll to find yourself in leaderboard in mobile version If I go to the Winter Bash leaderboard on the mobile version, I don't come on the top:

But the same if I do on the desktop; I come on the top with my leaderboard position. Above the number one position. Which adds unnecessary scrolling necessity while using a mobile browser. I am using Google Chrome.

A: Just posting this as an answer since it identifies the cause of the issue:
It looks like you're not logged in to the Winter Bash site on your phone, which would explain why you're not being shown above the other leaderboard rankings there. If you log in on the Winter Bash site, you should see your username displayed above the full leaderboard for each site.


text:
Q: Nodejs + Mongoose + Typescript "This expression is not callable." on .populate() I have a project in Node JS with mongoDB and Typescript (all at the latest version at the time of writing) that I cannot start. Can anyone help me?
The problem I get is the following (i.e. I can't compile due to a problem on a .populate()):
/Users/{...}/Projects/{...}/node_modules/ts-node/src/index.ts:843
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/apis/v1/controllers/users/update.controller.ts:136:35 - error TS2349: This expression is not callable.
  Each member of the union type '{ <Paths = {}>(path: string | PopulateOptions | (string | PopulateOptions)[]): Promise<MergeType<Document<unknown, any, UserDocument> & { ...; } & UserDocument & { ...; }, Paths>>; <Paths = {}>(path: string | ... 1 more ... | (string | PopulateOptions)[], callback: Callback<...>): void; <Paths = {}>(path: string, se...' has signatures, but none of those signatures are compatible with each other.

136       savedData = await savedData.populate('createdBy', config.userPopulate);

I have a project with the following packages:
{
  "dependencies": {
    "express": "^4.18.1",
    "mongoose": "^6.4.2",
    "typescript": "^4.7.4",
  },
}

Here are the files involved in creating the user module:
// Interface
interface User {
  _id: string | Types.ObjectId;

  ...
  givenName: string;
  familyName: string;
  ...

  createdBy?: string | Types.ObjectId;
  createdAt: Date;
  updatedBy?: string | Types.ObjectId;
  updatedAt: Date;
  __v?: number;
}

// Model
const UserModel = mongoose.model<UserDocument, UserModelDef>('User', userSchema);

// Schema
export interface UserDocument extends User, Document {}
export interface UserModelDef extends Model<UserDocument> {}
const { Schema } = mongoose;
export const userSchema = new Schema<UserDocument, UserModelDef>(
  {
    ...

    givenName: {
      type: Schema.Types.String,
      required: true,
      trim: true,
      minlength: 2,
      maxlength: 50,
    },
    familyName: {
      type: Schema.Types.String,
      required: true,
      trim: true,
    },

    ...

    createdBy: {
      type: Schema.Types.ObjectId,
      required: false,
      ref: 'User',
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      required: false,
      ref: 'User',
    },
  },
  {
    timestamps: true,
  },
);

Code on which the error occurs
const item = await UserModel.findById(userId);
item.set('givenName', 'John');
item.set('updatedBy', req.userLoggedIn?._id);
let savedData = await item.save();
savedData = await savedData.populate('updatedBy', config.userPopulate);


text:
Q: How to set up Idea under MacOs I downloaded Idea EAP 2017.3 Ultimate for Mac OS, with a bundled jre.
Once I cloned my gradle project, I tried to sync but it was complaining that there was no project SDK.
I tried to add the bundled jre under /Applications/IntelliJ IDEA.app/Contents/jdk/Contents/Home but it always complained it wasnt a valid JDK home.
So I downloaded the jre 9 and installed.
Added that as Project SDK, now I get this:
The newly created daemon process has a different context than expected.
It won't be possible to reconnect to this daemon. Context mismatch:
Java home is different.
Wanted: DefaultDaemonContext[uid=null,javaHome=/Applications/IntelliJ IDEA.app/Contents/jdk/Contents/Home,daemonRegistryDir=/Users/loredanasoetta/.gradle/daemon,pid=421,idleTimeout=null,daemonOpts=-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=IT,-Duser.language=en,-Duser.variant]
Actual: DefaultDaemonContext[uid=d56a6606-9df7-4dbb-b269-96531b5ba6f9,javaHome=/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home,daemonRegistryDir=/Users/loredanasoetta/.gradle/daemon,pid=481,idleTimeout=10800000,daemonOpts=-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=IT,-Duser.language=en,-Duser.variant]

1) Why the bundled jre doesn't get accepted?
2) I saw some people solved by explicitly declaring the jdk path in gradle-wrapper.properties
org.gradle.java.home=/Library...
but this is crap because it'd be pushed on the repo and it's valid only for me
Which is the right way to do have Idea on Mac OS?

A: Credits to Serge Baranov

*

*The bundles runtime that is not a complete JDK, you need to have normal JDK installed for development, see this.

*Configure JDK used to run Gradle in IntelliJ IDEA:


text:
Q: Why are there no co-op jobs on Careers? I've been looking at the job boards for a while now, and I have yet to see any listings for co-op positions. Are companies simply not interested in paying the amount to be listed if the employment is for the short-term only? Or are the companies that know of Stack Overflow simply uninterested in hiring co-ops? Has there ever even been a co-op listed? I think a lot of companies could get some fairly talented people as interns, so why do you suppose this is?

A: I would image that there are few internship/co-op positions listed because Fog Creek charges for the job placements. While the fee is justifiable for a company looking for a full-time, permanent savior, it makes much less economic sense for a short-term person.

A: Co-Ops and Internships are generally handled via other avenues (such as directly working with local schools that are ready to supply businesses with fresh student talent). Advertising this sort of position does not make financial sense overall. If there was going to be any advertising, I would expect it to be a lot more local because it is not very common for people to go for internships that are not local, unless that opportunity came with things like free room and board and other big perks.

A: Having gone through a co-op program at my university, I can say that this is not how co-ops work.  The school itself sets up various job openings at companies, and then the students apply for them through the school.  The only sort of advertising that would make sense is a general "hey, we're open to hiring co-ops, please contact us" sort of announcement by the company, but it's generally easier for the company's HR/Personnel department to contact the various Co-op Coordinators directly (normally, just the schools nearby).

A: Our intern program deals directly with the intern programs at the universities we recruit from.


text:
Q: C++ | How to make a vector which contains multiple objects of different classes I am trying to code my first game engine in C++ which will be like how Unity's scripting works. I am trying to make a component system. Here is my problem:
I want to have a vector containing my component since I will maybe need to add some dynamically. Where the problem happens is when I want to add derived class of my Component class. Here is an example:
std::vector<Component*> components;

With this line I cannot do this (which I would love to be able to do):
gameObject.GetComponent<TextRenderer>().text [...]

I still need to learn a lots and sincerely I do not understand totally the part of this (I don't understand templates and can't find a good tutorial) code but here is my GetComponent function:
template<typename T>
inline T* GetComponent()
{
    for (int i = 0; i < components.size(); i++)
        if (typeid(components[i]) == typeid(T))
        {
            std::cout << "Found Component." << std::endl;
            return (T*) &components[i];
        }
}

This function does not works it return nothing and/or have conversion problem.

A: I think that C-style conversion is undefined behavior.
As far as I know, all the component class(like SpriteRenderer, Rigidbody and so on) derive from Component in Unity. So we can use dynamic_cast which offers safe downcasting. If the casting succeeds it returns a valid pointer otherwise nullptr.
Here's an example of how I'd implement it.
template<typename T>
inline T* GetComponent()
{
    for (int i = 0; i < components.size(); i++)
    {
        T* downcasted = dynamic_cast<T>(components[i]);
        if (downcasted)
        {
            std::cout << "Found Component." << std::endl;
            return downcasted;
        }
    }
    return nullptr; // Unity's GetComponent returns null when not found
}

And please also note that dynamic_cast is relatively slow, just in case you care about the performance really seriously.


text:
Q: Interaction.Behaviors in Windows 10 UAP I'm experimenting with using Interaction.Behaviors in XAML to bind events to my controller like so,
<GridView x:Name="mygrid" >
    <interact:Interaction.Behaviors>
        <interactcore:EventTriggerBehavior EventName="SelectionChanged">
            <interactcore:InvokeCommandAction
                Command="{Binding Controller.Test}"
                CommandParameter="{Binding ElementName=mygrid, Path=SelectedItem}"/>
        </interactcore:EventTriggerBehavior>
    </interact:Interaction.Behaviors>
</GridView>

This works perfectly except... Visual Studio 2015 shows the following errors,
Severity    Code    Description Project File    Line    Suppression State
Error       The name "EventTriggerBehavior" does not exist in the namespace "using:Microsoft.Xaml.Interactions.Core".   MVC C:\Prototype\MVC\MVC\MainPage.xaml  19
Error       The name "InvokeCommandAction" does not exist in the namespace "using:Microsoft.Xaml.Interactions.Core".    MVC C:\Prototype\MVC\MVC\MainPage.xaml  20
Error       The name "Interaction" does not exist in the namespace "using:Microsoft.Xaml.Interactivity".    MVC C:\Prototype\MVC\MVC\MainPage.xaml  18

This has caused the designer to break, so even though the code works, the designer doesn't.  Any ideas?
My includes are...
xmlns:interact="using:Microsoft.Xaml.Interactivity"
xmlns:interactcore="using:Microsoft.Xaml.Interactions.Core"

And just to clarify, I included the behaviors SDK via the "Add Reference..." dialog.

A: The answer that worked for me were the comments made by Grace Feng in the question and confirmed by Nick.
That is when doing Windows 10 Universal apps use the Microsoft.Xaml.Behaviors.Uwp.Managed nuget package and remove the Behaviors SDK (XAML) package


text:
Q: VBScript/ creación de carpeta/recorrer rutas Soy nueva en VBscript y ustedes ya me ayudaron anteriormente así que confío que lo harán nuevamente(son muy amables).
Lo que necesito hacer es lo siguiente:

*

*Proceso que lea rutas de carpetas, verifique si esa ruta de carpeta contiene un archivo de extensión(ej. PDF y HTML) y si tiene,  los copie y los pegue en otra carpeta final, que se debe crear con la fecha del día.
Si no encuentra ningún archivo con la extensión especificada en alguna ruta de carpeta, que salte a la siguiente ruta y así sucesivamente.

Por ahora tengo listo el proceso de lectura de solo UNA ruta, donde copia los archivos y los lleva a una carpeta final
Me falta:
- Creación de la carpeta con la fecha del día.
- Realización del proceso con mas de una ruta
- Verificación de existencia del algún archivo con esa o esas extensiones
- Si no encuentra que salte a la próxima ruta
- Si encuentra que ejecute el proceso
Código 1:
Proceso de lectura de una ruta y copia-pega en otra carpeta ya creada
Dim ruta1, ruta_final
ruta1 = "C:\rutaA\*.html"
ruta_final = "C:\ruta_final"

Set fso = CreateObject("Scripting.FileSystemObject")

fso.CopyFile (ruta1, ) , (ruta_final)

-----ERROR: El subíndice está fuera del intervalo (Línea 26-última línea)----

A: En este caso lo mejor sería crear una función a la que le pasas los parámetros:
Función:
Function copiarPorExtension(sFolderOrigen, sFolderDestino, sExtension)
   For Each sFile In oFSO.GetFolder(sFolderOrigen).Files
      If LCase(oFSO.GetExtensionName(sFile)) = sExtension Then
         If Not oFSO.FileExists(sFolderDestino & "\" &  oFSO.GetFileName(sFile)) Then
           oFSO.GetFile(sFile).Copy sFolderDestino & "\" & oFSO.GetFileName(sFile),True
         End If
      End If
   Next
End Function

Preparar los parámetros y llamar la función desde cualquier parte
Dim sOrigen, sDestino, sExtension, dtmValue, sFecha, sHora
sOrigen = "C:\rutaA\"

'Para obtener la fecha
'Almacenaré la fecha en la variable sFecha y la hora en la variable sHora
'En el ejemplo se crea el nombre de carpeta con la fecha, si quieres que tenga la hora le agregas la variable sHora

dtmValue = Now()

sFecha = Year(dtmValue)"_" & Month(dtmValue) & "_" & Day(dtmValue)
sHora = strDate & "\" & Hour(dtmValue) & "-" & Minute(dtmValue) & "-" & Second(dtmValue)
sDestino = "C:\ruta_final" & sFecha
sExtension = "html"

'Llamamos la función pasándole los parámetros

Call copiarPorExtension(sOrigen, sDestino, sExtension)

La ventaja de la función es que, en el caso de querer pasar otros parámetros, como trabajar con archivos de extensión txt, doc u otros o con directorios distintos, no necesitas cambiar todo el código, sino solamente los parámetros que pasas a la función.
Si son varios directorios de origen
Se crea un array con los nombres de los directorios y se pasa como parámetro.
Nótese que la función copiarPorExtension () quedaría modificada, ya que recibirá como primer parámetro un array, en lugar de una cadena, por eso el primer parámetro se llama ahora arrOrigenes() donde las () indican que se trata de un array.
Luego, tendrá otro bucle for donde irá leyendo las diferentes carpetas de origen que recibió en parámetro, donde arrOrigenes(i)irá tomando la ruta de los folders existentes en el array (LaRutadelFolder1, LaRutadelFolder2, etc).
Nota: Aquí solo modifico el valor de arrFoldersOrigen, los demás valores se declararían tal y como aparece más arriba.
Dim arrFoldersOrigen
arrFoldersOrigen = Array ("LaRutadelFolder1","LaRutadelFolder2","LaRutadelFolder3")
i=0

Para llamar la función:
Call copiarPorExtension(arrFoldersOrigen,sDestino, sExtension)

Function copiarPorExtension(arrOrigenes(), sFolderDestino, sExtension)
   For i=0 to ubound(arrOrigenes)
      For Each sFile In oFSO.GetFolder(arrOrigenes(i)).Files
         If LCase(oFSO.GetExtensionName(sFile)) = sExtension Then
            If Not oFSO.FileExists(sFolderDestino & "\" &  oFSO.GetFileName(sFile)) Then
               oFSO.GetFile(sFile).Copy sFolderDestino & "\" & oFSO.GetFileName(sFile),True
            End If
         End If
       Next
   Next
End Function

Como detalle y aclaración:
Lo mismo se podría hacer si se desea pasar varias extensiones, se crea un array de extensiones y se le pasa a la función. Entonces habría que crear otro bucle for dentro de cada folder para que busque las extensiones pasadas en el array.

A: Podrías hacer un tipo de substring para detectar los últimos dígitos del nombre del archivo y así saber que tipo de extensión tiene.
Ejemplo:
set fso = CreateObject("Scripting.FileSystemObject")
set directory = fso.GetFolder(".").Files

for each file in directory
if Mid(file.NAME,len(file.NAME)-4,4) = ".html" AND Mid(file.NAME,len(file.NAME)-3,4) = ".pdf" then
   'Aqui pones tu codigo
end if
next


text:
Q: Как использовать type io.ReadCloser в качестве byte массива У меня есть обычный код:
req, err := http.Get(url)
if err != nil {
    fmt.Println("Error")
} else {
    fmt.Println("OK")

    content := []byte(req.Body) // или req.Header
    fmt.Printf("%s", hex.Dump(content))
}

Как мне использовать/конвертировать/преобразовать req.Byte, req.Header в []byte массив?

A: Как правило, вам не нужно читать все байты из Body, потому что вы можете передать его напрямую, например в json.NewDecoder. Иногда чтение может быть вредным, если например передаётся большой файл. Если же вам действительно это нужно, можете использовать ioutil.ReadAll:
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("%s", b)

Вывести же хексдамп хедеров можно так:
dumper := hex.Dumper(os.Stdout)
err := resp.Header.Write(dumper)
if err != nil {
    log.Fatal(err)
}

Playground: https://play.golang.org/p/8J9s7tpj3e.


text:
Q: C++ can't override parent class method I'm having some issues overriding a function and I don't know why it's not working. I keep looking online, but I haven't found anything. I should probably add that I'm using the c++11 standard right now just in case. Here is my code:
class SupervisedLearner {
public:
    ...
    virtual double measureAccuracy(Matrix& features, Matrix& labels, Matrix* pOutStats = NULL);
}

class NeuralNet: public SupervisedLearner {
public:
    ...
    double measureAccuracy(Matrix& features, Matrix& labels, Matrix* pOutStats = NULL) override;
}

The method measureAccuracy is then being called via a pointer to the generic SupervisedLearner class:
SupervisedLearner* learner = getLearner(model, r, parser.getLearnerExtra());
...
double accuracy = learner->measureAccuracy(trainFeatures, trainLabels, &stats);

Note that both the base class and the child class have implementations of the method. The program for some reason always goes to the SupervisedLearner::measureAccuracy function.
Can anyone see anything obviously wrong?

A: Try adding the keyword virtual to your child function, that way the compiler knows it is a virtual function.
By not adding the virtual, you are implementing a completely new function:
Object = (constructor, destructor another measure function, parent measure function)
When you run the code, the compiler will decide which function to use
If you add virtual to your child function it will look like this:
Object = (constructor, destructor, child measure function, parent measure function)
When you run the code with this the compiler will use the child function

A: I figured out the problem. The problem was happening with a decorator class between the lines:
SupervisedLearner* learner = getLearner(model, r, parser.getLearnerExtra());
...
double accuracy = learner->measureAccuracy(trainFeatures, trainLabels, &stats);

So, the code looked like:
SupervisedLearner* learner = getLearner(model, r, parser.getLearnerExtra());
...
learner = new Normalize( learner );
...
double accuracy = learner->measureAccuracy(trainFeatures, trainLabels, &stats);

The Normalize decorator looks like:
class Normalize: public SupervisedLearner {
private:
    SupervisedLearner* innerLearner;
public:
    Normalize(SupervisedLearner* learner) : learner(innerLearner) {}
    ...
}

The decorator did not override the SupervisedLearner method. Thanks everyone for the help. Thanks @Casey for the dynamic_cast(learner) == nullptr tip.


text:
Q: Read spark dataset only first n columns I have a dataset with more than 5000 columns and OutOfMemoryException was thrown when try to read the dataset, even when limiting to 10 rows. There is another post on the cause of exception and so I want to read only first n columns to avoid the error.
I could not find an api call that does that and only the rows could be restricted with head or limit.
Is there a way to do restricting to only first few columns? Thanks.

A: Given that your Dataset is ds, you can extract the first n columns into an Array :
val n = 2
val firstNCols = ds.columns.take(n)

and then select only these columns from the Dataset :
ds.select(firstNCols.head, firstNCols.tail:_*)


text:
Q: JAXB - generated classes implement interface Is there a way to configure JAXB to so that a generated class implements a specified interface?  I'm intending to use JAXB generated classes as DAO's and they should be able implement my DAO interface.

A: Unfortunately, it looks like the interface-injection plugin mentioned in some of the other answers is no longer well supported. In fact, I'm having trouble finding the JAR for download.
Thankfully, the JAXB2 Basics Plugins provides a similar mechanism for adding an interface to the generated JAXB stubs (see the Inheritance plugin).
The JAXB2 Basics Plugins documentation includes instructions for using the plugin with Ant and Maven.
The JAXB2 Basics Plugins provides a number of other utilities which you might also find useful (such as autogeneration of equals, hashCode, and toString methods).

A: The interface injection plugin for XJC lets you do this.


text:
Q: Execute a function with a new stack passed in a Linux Kernel Module My  Kernel Module takes as input with ioctl a function pointer and a stack size and should create a child process that execute that function with a newly allocated stack of that size. The behaviour is similar to clone()
The function is defined in user space so it must be executed again in user space and it must share the same parent process address space .
I know the correct way to create a new process inside a Kernel Module is to use  kthread_create but I need to execute the function in user mode.
I do not see how the user mode helper API can came in handy.
Is it possible to initialize a struct kernel_struct specifying that function and stack size as well as copying the address space of the parent process ?


text:
Q: The Object's equals Method? Can anybody explain why the first code equates to false and the second to true?

A: All objects in Java start with the equals(Object) method, found in the base Object class. Your second example simply overrides this method, so that any time the equals(Object) method is called, the override implementation is used rather than the base implementation.
However, in your first example, you have added a new overload for the equals() method, with a parameter list different from the based Object.equals() method. This overload would be used any time you call it when both of these are true:

*

*The reference used to call the method has a compile-time type of Circle, and

*The parameter passed to the method has a compile-time type of Circle
The first condition is required so that the compiler can find the method in the first place. If the compile-time type of the target instance of the call is not Circle, then the equals(Circle) overload of the method will not even be considered as a possibility.
The second condition is required so that the compiler can identify the equals(Circle) overload as the one to be called. If the parameter being passed is not known at compile time to be Circle, then the compiler can't safely use the equals(Circle) method, and must instead choose the equals(Object) overload.
In your first example, the compile-time types of both the target instance for the method call, as well as the parameter passed to the method, is Object and not Circle. As such, the compiler has no safe way to call the equals(Circle) overload, and must instead call equals(Object). And that overload, the base implementation, simply compares the references of the two objects, returning true only if they are identical (which in this case, being two different instances, obviously are not).
See also Overriding Object.equals VS Overloading it

As an aside: the second implementation is not quite right, because it assumes that the circle parameter passed in is always of type Circle. This is true in the degenerate code example in your question, but would not be generally true in a real-world program. A correct implementation of equals(Object) would check the type of the parameter first, and immediately return false if the type was not correct.


text:
Q: How to generate curried arguments for a ProvidedMethod? I want to generate a static method this the signature A -> B -> C
But I can only generate A * B -> C:
ProvidedMethod(name, [ ProvidedParameter("A", aType); ProvidedParameter("B", bType) ], cType, IsStaticMethod = true)

I can't do the currying manually, because function types don't work correctly in type providers, only delegate types. Is there any other way to do this that I'm not aware of, or is this just not supported at all?

A: I suspect that you can't do currying by using the ProvidedMethod simply. However you could make your methods return a function that wraps the application of the parameters.
public Func<A, Func<B, C>> Curry<A, B, C>(Func<A, B, C> func)
{
   return a1 => a2 => func(a1, a2);
}

Example above given in C# to show the types more explicit, in a type provider, this will look something like the following.
let retType = typeof<('a -> ('b -> 'c)>
let ftype = typeof<('a -> 'b -> 'c>
let method = ProvidedMethod(name, [ProvidedParameter("Func", ftype)], retType)

I don't currently have an F# compiler to hand (I'm on my iPad) but, hope this is a push in the right direction.


text:
Q: Widget right click pops up wrong place I added right click action to widget embedded in QTableWidget. When I click right QMenu appears in wrong place. Here is my code:
I added widget in QTableWidget:
        tableWidget = self._dlg.tableWidget
        variableLabel = QLabel()
        variableLabel.setText(str(var))
        variableLabel.setContextMenuPolicy(Qt.CustomContextMenu)
        variableLabel.customContextMenuRequested.connect(self.showMenu)
        tableWidget.setCellWidget(row, 0, variableLabel)

And here showMenu:
def showMenu(self, pos):
    print("pos", str(pos))
    menu = QMenu()
    applyAction = menu.addAction("Tümüne Uygula")
    action = menu.exec_(self._dlg.mapToGlobal(pos))
    if action == applyAction:
    ...

Lastly, here is my result, when I click colored cell (QLabel) the menu appears below:

A: the position sent by customContextMenuRequested is relative to the widget that issued it, in your case to the QLabel, assuming that showMenu() belongs to any widget we can use the sender() method to obtain it.
def showMenu(self, pos):
    menu = QMenu()
    applyAction = menu.addAction("Tümüne Uygula")
    action = menu.exec_(self.sender().mapToGlobal(pos))
    if action == applyAction:

If showMenu() does not belong to a widget then it will have to pass the label explicitly using functools.partial
from functools import partial

...

        tableWidget = self._dlg.tableWidget
        variableLabel = QLabel()
        variableLabel.setText(str(var))
        variableLabel.setContextMenuPolicy(Qt.CustomContextMenu)
        variableLabel.customContextMenuRequested.connect(partial(self.showMenu, variableLabel))
        tableWidget.setCellWidget(row, 0, variableLabel)

    ...

def showMenu(self, label, pos):
    menu = QMenu()
    applyAction = menu.addAction("Tümüne Uygula")
    action = menu.exec_(label.mapToGlobal(pos))
    if action == applyAction:
    ...


text:
Q: Looking for a way to load modal content when opening vs. on page load I have been researching for hours and have not found a solution to my problem.  I have a Wordpress site where I have built a dashboard of metrics.  I have setup modal windows using bootstrap to display details for each metric.  The modal window loads a google sheet using an inline viewer plugin/shortcode.  The issue is that all modal windows are loading in the background on page load causing the page to take up to 60 seconds to load.  I am looking for a solution that will only load the content of the modal windows when you click the metric.
Any suggestions would be much appreciated.
Here is a sample of my code:
1

Ashland Move-In Inspections

×

[this is where my shortcode goes]

<button class="btn btn-sm btn-default inverted" style="float:right; margin-top: -18px;" type="button" data-dismiss="modal">Close</button>

A: I would suggest adding this components on click with javascript but problem is that shortcodes are generated through PHP which means you would need an Ajax call each time you click on an item.
Found that somebody wanted to tackle the same issue you are facing here so it might be of use for you as well:
https://wordpress.stackexchange.com/questions/140086/execute-a-shortcode-when-clicking-on-a-image

A: I implemented that by changing [shortcodes] to <shortcodes></shortcodes> so they are not parsed by PHP and then attaching click events as suggested, converting and processing them with Ajax talking in general.


text:
Q: Looking for algorithm for spherical point in polygon that works across meridian and anti-meridian I need to process millions of latitude/longitude points every day to see if they are located within a defined lat/lon bounded polygon.  The polygon may be rectangular, or it may be some irregular 3.. n sided shape.  The points of the polygons will all be straight lines between points defined by lat/lon, no curves to complicate things.  Allowing for great circle would be great.  Many of the polygons will transit the anti-meridian or meridian.  Every approach that I have tried so far fails with anti-meridian crossing and some don't handle meridian crossings.
I'm working mostly with node.js which uses the Javascript language, sometimes I use Python.
There do not appear to be any proven or well documented JavaScript wrappers for libraries like OGR.  OGR is available for Python but my development work is mostly moving away from Python toward Node.js
I would appreciate it if someone could show me an algorithm (in the form of JavaScript or pseudo code) that can do this point in polygon operation.
I'm completely useless with mathematics and probably not trainable at this point so classical math notation will fly directly over my head.
The math functions that are available in my environment include all the standard geometry elements (a full list of available math functions can be seen at this link
I don't expect anyone to write code for me, but I'm hoping that someone can show me an algorithmic example in the pseudo-code like form of:
(ignore the content, it's meaningless)
c = atan2(lon) * 4800
ca = sin(c)

Something like that would be really helpful.


text:
Q: QRectF doesn't appear in my QGraphicsScene I am trying to play around with QGraphicsView(inside Maya) and got some code which I will paste down bellow. Problem is that window with QGraphicsView coming , but looks like QGraphicsScene(with my QRectF) doesn't come. I am a little bit still confused how inheritance works , so could somebody point out please where do I do mistake. Thank you.
from PySide2 import QtGui, QtCore, QtWidgets
from shiboken2 import wrapInstance
import maya.OpenMaya as om
import maya.OpenMayaUI as omui
import maya.cmds as cmds
import os, functools

def getMayaWindow():
    pointer = omui.MQtUtil.mainWindow()
    if pointer is not None:
        return wrapInstance(long(pointer), QtWidgets.QWidget)

class testUi(QtWidgets.QDialog):
    def __init__(self, parent=None):
        if parent is None:
            parent = getMayaWindow()
        super(testUi, self).__init__(parent)
        self.window = 'vl_test'
        self.title = 'Test Remastered'
        self.size = (1000, 650)

        self.create()

    def create(self):
        if cmds.window(self.window, exists=True):
            cmds.deleteUI(self.window, window=True)

        self.setWindowTitle(self.title)
        self.resize(QtCore.QSize(*self.size))
        self.testik = test(self)

        self.mainLayout = QtWidgets.QVBoxLayout()
        self.mainLayout.addWidget(self.testik)
        self.setLayout(self.mainLayout)

class test(QtWidgets.QGraphicsView):

    def __init__(self, parent=None):
        super(test, self).__init__(parent)

        self._scene = QtWidgets.QGraphicsScene()
        rect_item = QtWidgets.QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 100))
        rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self._scene.addItem(rect_item)

v = testUi()
v.show()

A: The problem is that you have not added the QGraphicsScene to the QGraphicsView:
class test(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(test, self).__init__(parent)
        self._scene = QtWidgets.QGraphicsScene()
        self.setScene(self._scene) # <---
        rect_item = QtWidgets.QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 100))
        rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self._scene.addItem(rect_item)

A: Eyllanesc is correct, you've created a QGraphicsScene but you still need to set it to the QGraphicsView.
Looking at the docs for QGraphicsView's constructor, you can also pass the scene through one of its __init__ parameters: QGraphicsView.__init__ (self, QGraphicsScene scene, QWidget parent = None)
So you can save a line and set it pass it directly to your class's super:
class test(QtWidgets.QGraphicsView):

    def __init__(self, scene, parent=None):
        self._scene = QtWidgets.QGraphicsScene()  # Create scene first.

        super(test, self).__init__(self._scene, parent)  # Pass scene to the QGraphicsView's constructor method.

        rect_item = QtWidgets.QGraphicsRectItem(QtCore.QRectF(0, 0, 100, 100))
        rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self._scene.addItem(rect_item)


text:
Q: How to start a span tag from a new line only if there is a break inside it? I have two spans inside an HTML table cell, first one is title and second one is view-count. Text inside first span is of variable length but the one inside the second span is very small e.g. Views: 1K. I don't want the text inside the second span to break or wrap on multiple lines. It should always appear as a single block. If there is a break inside the view-count span, e.g. between the words Views: and 1K, entire span should start from a new line. How can I achieve this?

table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

table {
width: 100%
}

td {
width: 25%
}

.view-count {
 color: white;
 background-color: rgb(150, 150, 150);
 padding: 0 3px;
 border-radius: 4px
}
<!DOCTYPE html>

    Variable length title.
    Views: 2K

  Test string

  Test string

  Test string

    Variable length title. Bit longer.
    Views: 2K

  Test string

  Test string

  Test string

    Variable length title. A little longer.
    Views: 2K

  Test string

  Test string

  Test string

A: You can prevent the text inside the view-count span from wrapping by setting  white-space: nowrap

table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

table {
width: 100%
}

td {
width: 25%
}

.view-count {
 color: white;
 background-color: rgb(150, 150, 150);
 padding: 0 3px;
 border-radius: 4px;
 white-space: nowrap;
}
<!DOCTYPE html>

    Variable length title.
    Views: 2K

  Test string

  Test string

  Test string

    Variable length title. Bit longer.
    Views: 2K

  Test string

  Test string

  Test string

    Variable length title. A little longer.
    Views: 2K

  Test string

  Test string

  Test string


text:
Q: Update SQL with PHP form (variable in name of input) I'm newbie so I hope u'll help me. I need to update my SQL with this PHP form. I googled a lot, but problem is i have name in variable:
($rowclanky["id"])
And simply just can't handle it... Tried a lot of things like adding slashes, etc. But I still couldn't make it. Can someone help me how to figure this out? Thanks a lot guys and sorry for my English.
<form method='POST'>;
    $sql = "SELECT id,text FROM clanky";
    $result = $con->query($sql);
    if ($result->num_rows > 0){
         while($row = $result->fetch_assoc()) {
             echo "<input type='text' name=".$row["id"]."  value='".$row["text"]."'>
";
                                              }
                               }
        echo "<input type='submit' name='send' value='Upravit'>
 </form>;
       }

A: You have not declared the $rowclacky variable. Try the following:
while ($row = $result->fetch_assoc()) {
    echo "<input type='text' name=".$row["id"]."  value='".$row["text"]."'>
";
}

notice that you are setting the results from "fetch-assoc()" to the variable $row. So when you try to access the columns in you need to get them from the $row variable.
Hopefully this helps.

A: $rowclanky is not defined anywhere

$rowclanky["id"]

should be

$row["id"]

And

$rowclanky["text"]

should be

$row["text"]


text:
Q: Why does the original list change? Running this:
a = [[1], [2]]
for i in a:
    i *= 2
print(a)

Gives
[[1, 1], [2, 2]]

I would expect to get the original list, as happens here:
a = [1, 2]
for i in a:
    i *= 2
print(a)

Which gives:
[1, 2]

Why is the list in the first example being modified?

A: You are using augmented assignment statements. These operate on the object named on the left-hand side, giving that object the opportunity to update in-place:

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

(bold emphasis mine).
This is achieved by letting objects implement __i[op]__ methods, for =* that's the __imul__ hook:

These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).

Using *= on a list multiplies that list object and returns the same list object (self) to be 'assigned' back to the same name.
Integers on the other hand are immutable objects. Arithmetic operations on integers return new integer objects, so int objects do not even implement the __imul__ hook; Python has to fall back to executing i = i * 3 in that case.
So for the first example, the code:
a = [[1], [2]]
for i in a:
    i *= 2

really does this (with the loop unrolled for illustration purposes):
a = [[1], [2]]
i = a[0].__imul__(2)  # a[0] is altered in-place
i = a[1].__imul__(2)  # a[1] is altered in-place

where the list.__imul__ method applies the change to the list object itself, and returns the reference to the list object.
For integers, this is executed instead:
a = [1, 2]
i = a[0] * 2  # a[0] is not affected
i = a[1] * 2  # a[1] is not affected

So now the new integer objects are assigned to i, which is independent from a.

A: The reason your results are different for each example is because list are mutable, but integers are not.
That means when you you modify an integer object in place, the operator must return a new integer object. However, since list are mutable, the changes are simply added to already existing list object.
When you used *= in the for-loop in the first example, Python modify the already existing list. But when you used *= with the integers, a new integer object had to be returned.
This can also be observed with a simple example:
>>> a = 1
>>> b = [1]
>>>
>>> id(a)
1505450256
>>> id(b)
52238656
>>>
>>> a *= 1
>>> b *= 1
>>>
>>> id(a)
1505450256
>>> id(b)
52238656
>>>

As you can see above, the memory address for a changed when we multiplied it in-place. So *= returned a new object. But the memory for the list did not change. That means *= modified the list object in-place.

A: In the first case your i in the for loop is a list. So you're telling python hey, take the ith list and repeat it twice. You're basically repeating the list 2 times, this is what the * operator does to a list.In the second case your i is a value, so you're applying * to a value, not a list.


text:
Q: Sequence of Integers in Rcpp I want to create a sequence of integer numbers for indexing within a matrix. The R pendant would be:
indexRow <- max(0,1):min(2,12)
matrix1[indexRow, ]

This is what i have tried in Rcpp to create the sequence of integers:
#include <Rcpp.h>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace Rcpp;
using namespace std;

// [[Rcpp::export]]
NumericVector test(NumericVector x) {
  IntegerVector indexRow = Rcpp::seq_along(max(0, 1), min(1, 12));
}

However I get the Error message:
no matching function for call to 'seq_along(const int&, const int&)'

How can I create a sequence of integers in Rcpp?

A: Here is a possible Rcpp implementation :
library(Rcpp)
cppFunction(plugins='cpp11','NumericVector myseq(int &first, int &last) {
NumericVector y(abs(last - first) + 1);
if (first < last)
   std::iota(y.begin(), y.end(), first);
else {
   std::iota(y.begin(), y.end(), last);
   std::reverse(y.begin(), y.end());
 }
return y;
}')
#> myseq(max(0,1), min(13,17))
#[1]  1  2  3  4  5  6  7  8  9 10 11 12 13

This code generates a function myseq which takes two arguments: The first and the last number in an integer series. It is similar to R's seq function called with two integer arguments seq(first, last).
A documentation on the C++11 function std::iota is given here.

A: seq_along takes in a vector, what you want to use is seq combined with min and max, both take vectors. seq returns an IntegerVector. Here is an example.
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector test(IntegerVector a, IntegerVector b) {
  IntegerVector vec =  seq(max(a), min(b));
 return vec;
}

In R you use
> test(c(0,1), c(2,12))
[1] 1 2


text:
Q: Using apply() and its correlaries to replace loops to apply outlier test (e.g.) I have data from a behavioral task that looks something like this (assuming data frame named data):
data <- data.frame(subject = c(rep(8666, 6), rep(5452, 6)), RT = c(714, 877, 665, 854, 1092, 1960, 770, 4551, 1483, 1061, 755, 1090))
data
subject  RT
8666      714
8666      877
8666      665
8666      854
8666     1092
8666     1960
5452      770
5452     4551
5452     1483
5452     1061
5452      755
5452     1090

That is, for this question, I'm working with a selection of subjects and reaction times. (All told, 183 subjects with 156 trials each.) Using reshape's cast() function, I've calculated a value for each subject that I'd like to use to exclude certain trials.
outl <- function(x) {
    2.5 * mad(x) + median(x)
    }
melteddata <- melt(data, id.vars="subject", measure.vars = "RT")
outliers <- cast(melteddata, subject ~ ., outl)
colnames(outliers)[2] <- "outlier"

This outputs something like:
  subject    outlier
1    5452   2235.635
2    8666   1517.844
...

Now, the way I'd normally do this is to write a loop which, for each unique subject number, compares their RT to the outlier value for that subject:
data$outliers <- 0
for(subject in unique(data$subject)) {
    temp <- data[data$subject == subject,]
    temp$outliers <- ifelse(temp$RT > outliers[outliers$subject == subject,]$outlier, 0, 1)
    data[data$subject == subject,]$outliers <- temp$outliers
    }

... which marks the RTs of 1960 for subject 8666 and 4551 for 5452 as outliers.
However, I feel like there's got to be a more R way to do this. It feels like apply() should be able to do the same thing, and certainly this takes a long time to run as a loop. Any suggestions?
Edit:
I realize I can do this with ddply() from the library(plyr) package instead of using melt() and cast():
library(plyr)
outliers <- ddply(data, .(subject), summarize, median = median(RT), mad = mad(RT), outlier = median(RT) + 2.5 * mad(RT))

A: Here's a try. Turn the outliers data frame into a named vector:
out <- outliers$outlier
names(out) <- outliers$subject

Then use it as a lookup table to select all the rows of data where the RT column is less than the outlier value for the subject:
data[data$RT < out[as.character(data$subject)], ]

The as.character is necessary since the subject IDs are integers, and you don't want to get, e.g., the 8666th element of out.
Edit to add a dplyr solution:
group_by(data, subject) %>% summarize(outlier = 2.5 * mad(RT) + median(RT)) -> outliers
merge(data, outliers)
filter(data, RT < outlier)


text:
Q: Nested generic wildcard binding in ninject Is there a clean way to bind to a nested generic "wildcard" in Ninject?
I know that I can ask for any arbitrary IThing<T> with the following binding:
kernel.Bind(typeof(IThing<>)).To(typeof(Thing<>));

However, what I really want is any arbitrary IThing<Foo<T>>. The following does not work syntactically:
kernel.Bind(typeof(IThing<Foo<>>)).To(typeof(FooThing<>));

This works syntactically:
kernel.Bind(typeof(IThing<>).MakeGenericType(typeof(Foo<>))).To(typeof(FooThing<>));

But ninject doesn't know what to do with that. Can Ninject achieve this sort of thing?

A: The simple answer is: no, you cannot do this with Ninject. In fact, the only DI library that actually supports this kind of complex bindings using partially closed generic types is Simple Injector. In Simple Injector you can do this:
container.RegisterOpenGeneric(
    typeof(IThing<>),
    typeof(Thing<>).MakeGenericType(typeof(Foo<>)));

And in your example you have a FooThing<T> that probably contains a nested type constraint as follows:
public class FooThing<T> : IThing<Foo<T> { }

Again, Ninject does not support this. I believe that Autofac has some support for this up to some level, but only Simple Injector is able to resolve types for your with almost any bizarre and complex generic type constraints. In Simple Injector that registration is simply:
container.RegisterOpenGeneric(typeof(IThing<>), typeof(FooThing<>));

And Simple Injector will find out for you that it has to resolve a FooThing<int> when an IThing<Foo<int>> is requested.


text:
Q: Unique combinations of all elements from long python list with elements from shorter list I have two lists:
trips = ['trip1', 'trip2', 'trip3', 'trip4',...., 'tripN']

trucks = ['A', 'B', 'C']

I want to obtain all possible unique combinations so that all trips are matched with a truck in the trucks list. Please note, that all trucks must execute the same number of trips. In the above case for example if len(trips) == 12 then all trucks must be matched with 4 trips each.
Moreover,
extra_trips = len(trips) % len(trucks). If extra_trips != 0

then get also all the unique combinations of trips-trucks by matching the remaining trip with whatever truck.
I have done the following but I have trouble to proceed:
import itertools
import random
trucks=['A','B','C']
trips = ['trip1', 'trip2', 'trip3', 'trip4']

combs= [list(itertools.zip_longest(trucks, x)) for x in itertools.permutations(trips,len(trips))]

From the above code, I get this output:
[[('A', 'trip1'), ('B', 'trip2'), ('C', 'trip3'), (None, 'trip4')], [('A', 'trip1'), ('B', 'trip2'), ('C', 'trip4'), (None, 'trip3')], [('A', 'trip1'), ('B', 'trip3'), ('C', 'trip2'), (None, 'trip4')], [('A', 'trip1'), ('B', 'trip3'), ('C', 'trip4'), (None, 'trip2')], [('A', 'trip1'), ('B', 'trip4'), ('C', 'trip2'), (None, 'trip3')], [('A', 'trip1'), ('B', 'trip4'), ('C', 'trip3'), (None, 'trip2')], [('A', 'trip2'), ('B', 'trip1'), ('C', 'trip3'), (None, 'trip4')], [('A', 'trip2'), ('B', 'trip1'), ('C', 'trip4'), (None, 'trip3')], [('A', 'trip2'), ('B', 'trip3'), ('C', 'trip1'), (None, 'trip4')], [('A', 'trip2'), ('B', 'trip3'), ('C', 'trip4'), (None, 'trip1')], [('A', 'trip2'), ('B', 'trip4'), ('C', 'trip1'), (None, 'trip3')], [('A', 'trip2'), ('B', 'trip4'), ('C', 'trip3'), (None, 'trip1')], [('A', 'trip3'), ('B', 'trip1'), ('C', 'trip2'), (None, 'trip4')], [('A', 'trip3'), ('B', 'trip1'), ('C', 'trip4'), (None, 'trip2')], [('A', 'trip3'), ('B', 'trip2'), ('C', 'trip1'), (None, 'trip4')], [('A', 'trip3'), ('B', 'trip2'), ('C', 'trip4'), (None, 'trip1')], [('A', 'trip3'), ('B', 'trip4'), ('C', 'trip1'), (None, 'trip2')], [('A', 'trip3'), ('B', 'trip4'), ('C', 'trip2'), (None, 'trip1')], [('A', 'trip4'), ('B', 'trip1'), ('C', 'trip2'), (None, 'trip3')], [('A', 'trip4'), ('B', 'trip1'), ('C', 'trip3'), (None, 'trip2')], [('A', 'trip4'), ('B', 'trip2'), ('C', 'trip1'), (None, 'trip3')], [('A', 'trip4'), ('B', 'trip2'), ('C', 'trip3'), (None, 'trip1')], [('A', 'trip4'), ('B', 'trip3'), ('C', 'trip1'), (None, 'trip2')], [('A', 'trip4'), ('B', 'trip3'), ('C', 'trip2'), (None, 'trip1')]]

As you can see, it returns some combinations but for every comb, one trip is not matched.

A: Using zip_longest sort of sounds like the right approach, but you need to cycle the shorter list so that if they don't share a common divisor some trucks will get repeated.
from itertools import cycle

def zip_cycle_shorter(a, b):
    if len(a) < len(b):
        a = cycle(a)
    elif len(b) < len(a):
        b = cycle(b)
    return zip(a, b)

list(zip_cycle_shorter([1,2,3], ['a','b','c','d','e']))

gives me: [(1, 'a'), (2, 'b'), (3, 'c'), (1, 'd'), (2, 'e')]
which is what I think you want.  It might be instructive to try generalising this to support an arbitrary number of lists.  For example, try filling in code to complete:
def zip_cycle_shorter(*lists):
   ...

(you just use comprehensions instead of handling each case specifically)

A: You only need to do the cartesian product of the two lists:
trucks=['A','B','C']
trips = ['trip1', 'trip2', 'trip3', 'trip4']

print([(truck, trip) for truck in trucks for trip in trips])

Result:
[('A', 'trip1'), ('A', 'trip2'), ('A', 'trip3'), ('A', 'trip4'), ('B', 'trip1'), ('B', 'trip2'), ('B', 'trip3'), ('B', 'trip4'), ('C', 'trip1'), ('C', 'trip2'), ('C', 'trip3'), ('C', 'trip4')]


text:
Q: Is it possible to tell Spring Security how my user and authority schemes look like without raw SQL queries? I have columns nickname, password, enabled and authority in my user scheme. Column authority is a foreign key to scheme authority.
I have columns authority in my authority scheme.
My schemes are different from those Spring Security waits by default.
That's why I have to write this code in configuration.
@Bean
public UserDetailsManager users(DataSource dataSource) {
    JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
    users.setUsersByUsernameQuery(
            "SELECT nickname, CONCAT('{noop}', password), true " +
                    "FROM \"user\" WHERE nickname = ?"
    );
    users.setAuthoritiesByUsernameQuery(
            "SELECT u.nickname, a.authority " +
                    "FROM authority a " +
                    "LEFT JOIN \"user\" u " +
                    "ON a.authority=u.authority WHERE nickname = ?"
    );
    return users;
}

It works well. But I think it is not the best solution because of the raw SQL queries in my code.
Is there a way not to write SQL queries?

I also use Spring Data JPA in my project.
I an idea have to write my implementation of AuthenticatedProvider and use UserService inside it.

A:
The image is from: Spring Security In Action by Laurentiu Spilca.
You could always implement the interface/contract UserDetailsService https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetailsService.html
and load users with model classes that also implements another interface/contract UserDetails.
https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetails.html
and configure your UserDetailsService as a bean so that AuthenticationProvider could retrieve at run time(autowired). You should also provide a PasswordEncoder in the same configuration class as a bean. [No need to implement a provider if you use default authentication logic(compare passwords from db and given password by using a password encoder)]
Your database schema should allow you to provide the information contained in UserDetails service contract/interface.
NOTE: GrantedAuthorities starting with ROLE_ are identified as roles.


text:
Q: Scala - Traversing a ByteString Until Empty Is there a more concise and/or performant way to traverse the message than what I have here?
    import akka.util.ByteString

    @throws[GarbledMessageException]
    def nextValue(message: ByteString) =

        message.indexOf(delimiter) match {

           case i if i >= 0 => message.splitAt(i)

           case _ => throw new GarbledMessageException("Delimiter Not Found")
       }

   @tailrec
   def processFields(message: ByteString): Unit = nextValue(message) match {

      case (_, ByteString.empty) => // Complete Parsing

      case (value, rest) =>
        // Do work with value

        // loop
        processFields(rest)
   }

A new ByteString is created for each split which hurts performance, but at least the underlying Buffer is not copied, only reference counted.
Maybe it can be even better than that?

A: It may depend on specifically what kind of work you are doing, but if you are looking for something more performant than splitting off ByteStrings, take a look at ByteIterator, which you can get by calling iterator on a ByteString.
A ByteIterator would allow you to go directly to primitive values (ints, floats, etc.) without having to split off new ByteStrings first.


text:
Q: How to get transferable docker compose stack without dockerhub I have few docker images composed together in the stack using docker-compose.yml.
Now I want to transfer whole docker compose stack to the other host machine without uploading to the dockerhub,
And deploy it on the docker swarm.
I saw there is a thing called docker compose bundle, would that help?

A: If you're deploying on a multi-host swarm (or something similar like Kubernetes or Nomad) you all but need a Docker registry.  It doesn't specifically have to be Docker Hub — quay.io, Amazon's ECR, Google's GCR, and self-hosted registries all work fine — but you do need to have pushed the built images somewhere where the orchestrator can retrieve them by name.
I've never used docker-compose bundle myself, but its documentation also notes that its operation "requires interaction with a Docker registry".
The only real alternative is using docker save and docker load to manually move images between machines, but as a manual process it will get tedious very quickly, and you need to make sure an identical set of images are on every machine for consistency.  Using a registry will be vastly easier.

A: The easyest way to do it is to use a Docker registry. The problem with Docker Hub is that you can only have one private registry, the rest must be public or paid.
Thankfully, there are other (free) alternatives:

*

*Deploy your own private registry. Here is a nice tutorial where you can try it in the browser.

*Use a free private registry. I personnaly use Codefresh. It can automatically build your image from a private repo (like bitbucket who has free plan too), but you can also just use it like a "simple" docker registry and push and pull your Docker images there.


text:
Q: QDA | lengths of training and test data sets | How to split data in training and test data? In QDA (Quadratic Discriminant Analysis), do i need to keep length of training and test data exactly same? If not, how do you find a Confusion Matrix in such cases?
Here's psuedo data.
Because if I keep training-data and test data sets of different lengths, it gives an error (Using R Studio):
"Error in table(pred, true) : all arguments must have the same length".
Tried to remove NAs using na.omit() on both data sets as well as pred and true; and using na.action = na.exclude for qda(), but it didn't work.
After dividing the data set in exactly half; half of it as training and half as test; it worked perfectly after na.omit() on pred and true.
Following is the code used for either of approaches. In approach 2, with data split into equal halves, it worked perfectly fine.
#Approach 1: divide data age-wise

train <- vif_data$Age < 30
# there are around 400 values passing (TRUE) above condition and around 50 failing (FALSE)

train_vif <- vif_data[train,]
test_vif <- vif_data[!train,]

#taking QDA
zone_qda <- qda(train_vif$Awareness~train_vif$Zone, na.action = na.exclude)
#compare QDA against test data
zone_pred <- predict(zone_qda, test_vif)
#omitting nulls
pred <- na.omit(zone_pred$class)
true <- na.omit(test_vif$Awareness)
length(pred) #  result: 399
length(true) # result: 47

#that's where it throws error: "Error in table(zone_pred$class, train_vif) : all arguments must have the same length"
zone_aware <- table(zone_pred$class, train_vif)
# OR
zone_aware <- table(pred, true)
accur <- mean(zone_pred$class==test_vif$Awareness)

###############################

#Approach 2: divide data into random halves
train <- splitSample(dataset = vif_data, div = 2, path = "./", type = "csv")
train_data <- read.csv("splitSample_s1.csv")
test_data <- read.csv("splitSample_s2.csv")

#taking QDA
zone_qda <- qda(train_vif$Awareness~train_vif$Zone, na.action = na.exclude)
#compare QDA against test data
zone_pred <- predict(zone_qda, test_vif)
#omitting nulls
pred <- na.omit(zone_pred$class)
true <- na.omit(test_vif$Awareness)
length(train_vif)

# this works fine
zone_aware <- table(zone_pred$class, train_vif)
# OR
zone_aware <- table(pred, true)
accur <- mean(zone_pred$class==test_vif$Awareness)

Want to know if there is any method by which we can have a confusion matrix with data set unequally divided into training and test data set.
Thanks!

A: Are you plugging in your training inputs instead of your test set input data to predict? Notice how this yields the same error message:
table(c(1,2),c(1,2,3))

If pred isn't the right length, then you're probably predicting incorrectly. At the moment, you haven't shared any of your code, so I cannot say anything more. But there is no reason that you shouldn't be able to get a confusion matrix using test data of different size than your training data.


text:
Q: Returning the correct path for a wordpress CHILD theme I know wordpress quite well, but this is the first time that I am creating a child theme. I realized that I need to link everything differently in a child theme.
I got it to work for images by using "stylesheet_directly", like so:
  <img src="<?php bloginfo('stylesheet_directory'); ?>/images/icon.png" />

However, I am now trying to enqueue a javascript file in the child theme's functions.php I tried using "stylesheet_directory" again, but it returned a path of the parent's theme, and not the child theme.
Why does "stylesheet_directory" work for the image files in my child theme, but not for enqueing javascript files in my functins file?
Here is what I have in my functions. What else can I use to return the correct path?
wp_enqueue_script( 'ga-slider', bloginfo('stylesheet_directory') . '/js/ga-slider.js');

A: I have used get_stylesheet_directory_uri() instead of yours bloginfo('stylesheet_directory') .  Ex.
wp_enqueue_script('script-name', get_stylesheet_directory_uri() . '/js/script.js', array('jquery'),2, true );

A: you can use get_stylesheet_directory_uri() for relative path to the child theme directory.
get_stylesheet_directory() will return absolute path of the child theme directory.

*

*Docs: https://codex.wordpress.org/Function_Reference/get_template_directory


text:
Q: Insert query locking down the entire DB and not responding I have a almost fully normalized (3NF) database for a ticket booking/purchase application, widely used throughout my country by a traveling company. It is in MySQL.
Recently it has exceeded 1GB (DUMP SIZE) and queries has become sufficiently slower. In order to reduce query time and db size (greatly), I am thinking about doing this cheating.
I'm going to dump all the data into a offline server where the management can view history older than 3 months. Then remove all the old data (by querying) from the online database. Trust me older data isn't that much important in here.
The only old data that is important that is how many time a registered passenger has travelled with the company. Even though it's probably not the greatest idea, I'm just planning on adding up an integer value to the "passenger" table where I'll be keeping the old count. As simple as that.
But here's the problem. When I run this following query, my phpMyAdmin (or adminer) hangs up. So does the server and somehow the table gets locked. It doesn't work unless I restart the Server.
Here's the query. It's pretty
UPDATE `passenger`
SET `CountAddition` = (
                       SELECT COUNT(1) FROM booking
                       WHERE booking.Passenger = passenger.ID
                       )
WHERE 1

I've given it around 30 minutes to run. It never ends. What might have gone wrong with it? Any help would be hugely appreciated.
Also, if there is a better alternative than this one, please suggest.

A: Subquery will not work without the group by and that is why it is not showing any progress.

A: you should include some verbose messages to your scripts.
also do the select first and loop through the results updating the table. If your using MyISM tables then the whole table gets locked when your doing an update to a row. You can try switching to innodb. Also ensure there is an index on booking.Passenger and passenger.ID


text:
Q: Anyway to link a dll compiled using c++ builder in vc++ code? I did some google and all I find is ways to make a vc++ dll compatible to c++ builder via COFF2OMF. But I need to bring a c+ builder dll into vc++. Is there any similar tool that creates a vc++ compatible .lib from a c++ builder dll?
Thanks in advance.

A: If the interface of your DLL (functions that have been exported) does not depend on VCL and object pascal, you can do one on the to methods below:

*

*extract a .LIB from the DLL by using the methods described here
and linking the generated .LIB into your project.

*Use LoadLibrary(), GetProcAddress() to dynamically load the DLL and use the exported functions.

keep in mind that your DLL might be dependent on VCL libraries and ... which makes using them more difficult. also I have to say it again, if any VCL or object pascal data is being used in the exported functions, you will not be able to use this DLL at all.
Sam

A: COFF2OMF.EXE is the wrong way to use a VC++ DLL in C++Builder. It should only be used when converting a static LIB. It is not necessary for a DLL import LIB. You should use IMPLIB.EXE instead to generate a new C++Builder compatible import LIB from the DLL directly.
The VC++ equivalent is to use DUMPBIN.EXE to list the DLL exports, then write a .DEF file defining those exports, and then run the .DEF through LIB.EXE to create a VC++ compatible import LIB.
See this blog for more details:
Create .lib file from .dll


text:
Q: Does sequelize support SQL Server views? I'm working on a project that I need to define a model from SQL Server views. Is it possible to define a model from views according to not to use table joins and decrease complexities.

A: Yes, you can point a Sequelize model at a view, rather than a table at least for SELECT statements (e.g. model.findAll())   I doubt that model.sync() would work against a view, but haven't tested.  IIRC, some databases allow INSERT, UPDATE or DELETE against views in limited cases) and in those limited cases you might be able to use model.create(), model.update() or model.delete() also.

A: sequelize.sync() creates the models assuming that you only want to work with tables and tries to create a table when you actually want a view... as per the example below
Error message when the view already exists
In OBJECT_ID('V_Funds','U') 'U' is for Table.(cf. image)
So forget about using sequelize.sync() and just use Sequelize-Auto (as per the comments above). Then just run a simple .bat or .cmd such as the one below and all is done for you automatically
rem recreate the various models
node node_modules\sequelize-auto\bin\sequelize-auto -h localhost -d XXXX -e mssql -u sa -x PASSWORD -c "./config.json" -o "./../server/src/models"


text:
Q: Pinch Gesture Recognizer resets image on second pinch zoom I'm using the UIPinchGestureRecognizer for pinch/zoom and image. If I zoom in with my fingers release them trying to zoom in more the image resets to the org. size for the second zoom in attempt.
How can I get the image to stay "zoomed in" for the second pinch?
here is how I'm doing the UIPinchGestureRecognizer
@IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
    sender.view?.transform = CGAffineTransformMakeScale(sender.scale, sender.scale)
}

A: you can try this
@IBAction func scaleImage(recognizer : UIPinchGestureRecognizer) {
    if let view = recognizer.view {
        view.transform = CGAffineTransformScale(view.transform,
            recognizer.scale, recognizer.scale)
            recognizer.scale = 1
    }
}


text:
Q: Openlayers 7.1.0: Using a Style Function with WebGLPointsLayer/VectorSource I have a simple Openlayers 7.1.0 app (Node.JS) which processes 30K+ records & plots them on a map using a WebGLPointsLayer & a VectorSource. With a static style object each point is rendered but I'd like to style each point based on Features. I tried a Style Function but the style function, not the compiled style, is passed to parseLiteralStyle() which fails with Uncaught TypeError: Cannot read properties of undefined (reading 'size').
Any ideas what I am doing wrong? Thanks.
Repo: https://github.com/Tomcariello/ol-plot_direction_and_magnitude-WebGL
const map = new Map({
  layers: [new Tile({source: new OSM()}),
    new WebGLPointsLayer({
      source: new VectorSource({ features: featuresArr,}),

      // THIS STATIC STYLE OBJECT WORKS AS EXPECTED
      style: {
        symbol: {
          symbolType: "triangle",
          size: 8,
          color: "blue",
          rotateWithView: true,
        }
      }

      // A STYLE FUNCTION FAILS TO RENDER
      // Result: Uncaught TypeError: Cannot read properties of undefined (reading 'size')
      // style (feature, resolution) {
      //   return {
      //     symbol: {
      //       symbolType: "triangle",
      //       size: 8,
      //       color: "blue",
      //     }
      //   }
      // }
    }),
  ],
  target: "map",
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

A: Thanks again to @Mike above for providing the solution which has been pushed to the repo.
"Style functions are not supported for WebGL points because the style object can access properties of the features using [a Style] Expression".
Click here to learn more about Openlayers Style Expressions
And here is the working style expression for my issue.
style: {
    symbol: {
      symbolType: "triangle",
      size: [
        "array",
        ["*", ["get", "speed"], 0.3], // speed * 0.3 --> width (triangle base)
        ["*", ["get", "speed"], 0.8], // speed * 0.8 --> height (triangle peak)
      ],
      color: [
        "case",
        [">", ["get", "speed"], 40], // if speed over 40 --> red
        "red",
        [">", ["get", "speed"], 20], // if speed over 20 --> blue
        "blue",
        "green", // if speed <= 20 --> green
      ],
      rotation: ["*", ["get", "deg"], Math.PI / 180],
      rotateWithView: true,
    },
  },
}),


text:
Q: How to disable telnet on a Debian 11 As per title, how can I disable telnet on a Debian 11 server?
I think I can (how?) block port using ufw, but... how can I disable the service itself?
I tried
systemctl disable telnet

But
Failed to disable unit: Unit file telnet.service does not exist.

EDIT
I am ahppy to receive an answer even if the question is stupid. I had the dubt that service was running even if I'm not able to detect at my first attemp.
The answer I accepetd is simple, give me an explanation and a solution.

A:
Failed to disable unit: Unit file telnet.service does not exist.

The error message tells you the reason for the failure is that the "Unit file telnet.service does not exist". You don't have a telnet service installed (by that name, if at all) so it's not possible to disable it.
You can check this with netstat -na or ss -na to confirm that there is nothing listening on TCP port 23. For example, this command will return results only if there is something listening on port 23:
ss -na | grep LISTEN | grep -w 23

If there is something reported then please update your question with the command you used and its output.

A: In Debian, the various telnet server implementations don't use systemd to provide their services, they are configured as inetd services. So if they are installed, you can't use systemctl to disable them.
However, they are all packaged as single-purpose packages. So the best approach to ensure that telnet servers are disabled in Debian is to check that the corresponding packages aren't installed:
sudo apt purge '*telnetd*'