text:
Q: Remove Pagination in Appearance -> Menus -> Categories I asked this question on WP Stackexchange already but did not get any answers. So let me try here. Wordpress Stackexchange
Is there a way to remove the Pagination in the Wordpress Menu Editor?
I have something like 200 categories in my blog and customising menus seems to be tricky when you have to click through it to find the desired category.
I know there's a plugin that "removes" the pagination for PAGES but I could not find anything to remove the pagination for the CATEGORIES.
I tried to find something in the Wordpress Admin PHP files or even nav-menus.php but did not get lucky.
Link to Problem

A: Ok after reading through the source code I found that the number of categories returned in the edit menu section is hardcoded to 50 on line 613 of \wp-admin\includes\nav-menu.php
// Paginate browsing for large numbers of objects.
    $per_page = 50;
    $pagenum = isset( $_REQUEST[$taxonomy_name . '-tab'] ) && isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 1;
    $offset = 0 < $pagenum ? $per_page * ( $pagenum - 1 ) : 0;

In order to override the default of 50 per page you can set the number to '' to instruct the query to return all categories.  Add the following code to your functions.php file.
add_filter( 'get_terms_args', 'show_all_categories_admin_nav_menu', 10, 2);

function show_all_categories_admin_nav_menu( $args, $taxonomies ) {
    if( reset($taxonomies) === 'category' ) {
        $args['number'] = '';
    }

    return $args;
}

If you set the number to blank it still shows the pagination even though it's showing all the categories.
There's also a filter called terms_clauses that exists in which you can remove the SQL LIMIT clause from the query but this didn't seem to have any affect on the query.
add_filter('terms_clauses', 'modify_terms_clauses', 10, 3);

function modify_terms_clauses( $clauses, $taxonomies, $args ) {
    if( reset($taxonomies) === 'category' ) {
        $clauses['limits'] = '';
    }

    return $clauses;
}


text:
Q: How to use the Input.Location and mock location in the unity editor I am building a location based game, a bit like pokemon go.
I am reading the location on my android phone without any problem, but I can't get any location data when I'm developing in the unity editor since Input.location.isEnabledByUser is false in the editor
It would be ok to mock/hard code a location, just so I can try it without deploying to my phone.
I tried to hard code it like this:
LocationInfo ReadLocation(){
    #if UNITY_EDITOR

    var location = new LocationInfo();
    location.latitude = 59.000f;
    location.longitude = 18.000f;
    location.altitude= 0.0f;
    location.horizontalAccuracy = 5.0f;
    location.verticalAccuracy = 5.0f;

    return location;
    #elif
    return Input.location.lastData;
    #endif
}

But all of the properties of the location are read only, so I'm getting compilation errors.
Is there a way to enable location service in the editor, or hardcode a location?

A:
Is there a way to enable location service in the editor, or hardcode a
  location?

This is one of the reasons why Unity Remote was made. Setup Unity Remote then connect your mobile device to the Editor. You can now get a real location from the Editor.

But all of the properties of the location are read only

If you really want to develop a way to mock the location, you have to abandon Unity's LocationInfo structure. Make your own custom LocationInfo and name it LocationInfoExt. Ext is = Extended.
Do the-same thing for LocationService too, then Wrap the official LocationService into your custom LocationServiceExt class. You can use LocationServiceExt to decide if you should mock location by using LocationInfoExt or not mock location by using LocationInfo internally to provide the result.
In the example below, the official LocationService,  LocationInfo and LocationServiceStatus class/struct/enum are replaced with LocationServiceExt, LocationInfoExt and LocationServiceStatusExt. They also have the-same functions and properties implemented. The only difference is that you can pass true/false to the constructor of  LocationServiceExt in order to use it in the Editor.
LocationServiceExt wrapper class:
Create a class called LocationServiceExt then copy the code below into it:
It has every function and property from the original LocationService class.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LocationServiceExt
{
    private LocationService realLocation;

    private bool useMockLocation = false;
    private LocationInfoExt mockedLastData;
    private LocationServiceStatusExt mockedStatus;
    private bool mIsEnabledByUser = false;

    public LocationServiceExt(bool mockLocation = false)
    {
        this.useMockLocation = mockLocation;

        if (mockLocation)
        {
            mIsEnabledByUser = true;
            mockedLastData = getMockLocation();
        }
        else
        {
            realLocation = new LocationService();
        }
    }

    public bool isEnabledByUser
    {
        //realLocation.isEnabledByUser seems to be failing on Android. Input.location.isEnabledByUser is the fix
        get { return useMockLocation ? mIsEnabledByUser : Input.location.isEnabledByUser; }
        set { mIsEnabledByUser = value; }
    }

    public LocationInfoExt lastData
    {
        get { return useMockLocation ? mockedLastData : getRealLocation(); }
        set { mockedLastData = value; }
    }

    public LocationServiceStatusExt status
    {
        get { return useMockLocation ? mockedStatus : getRealStatus(); }
        set { mockedStatus = value; }
    }

    public void Start()
    {
        if (useMockLocation)
        {
            mockedStatus = LocationServiceStatusExt.Running;
        }
        else
        {
            realLocation.Start();
        }
    }

    public void Start(float desiredAccuracyInMeters)
    {
        if (useMockLocation)
        {
            mockedStatus = LocationServiceStatusExt.Running;
        }
        else
        {
            realLocation.Start(desiredAccuracyInMeters);
        }
    }

    public void Start(float desiredAccuracyInMeters, float updateDistanceInMeters)
    {
        if (useMockLocation)
        {
            mockedStatus = LocationServiceStatusExt.Running;
        }
        else
        {
            realLocation.Start(desiredAccuracyInMeters, updateDistanceInMeters);
        }
    }

    public void Stop()
    {
        if (useMockLocation)
        {
            mockedStatus = LocationServiceStatusExt.Stopped;
        }
        else
        {
            realLocation.Stop();
        }
    }

    //Predefined Location. You always override this by overriding lastData from another class
    private LocationInfoExt getMockLocation()
    {
        LocationInfoExt location = new LocationInfoExt();
        location.latitude = 59.000f;
        location.longitude = 18.000f;
        location.altitude = 0.0f;
        location.horizontalAccuracy = 5.0f;
        location.verticalAccuracy = 5.0f;
        location.timestamp = 0f;
        return location;
    }

    private LocationInfoExt getRealLocation()
    {
        if (realLocation == null)
            return new LocationInfoExt();

        LocationInfo realLoc = realLocation.lastData;
        LocationInfoExt location = new LocationInfoExt();
        location.latitude = realLoc.latitude;
        location.longitude = realLoc.longitude;
        location.altitude = realLoc.altitude;
        location.horizontalAccuracy = realLoc.horizontalAccuracy;
        location.verticalAccuracy = realLoc.verticalAccuracy;
        location.timestamp = realLoc.timestamp;
        return location;
    }

    private LocationServiceStatusExt getRealStatus()
    {
        LocationServiceStatus realStatus = realLocation.status;
        LocationServiceStatusExt stats = LocationServiceStatusExt.Stopped;

        if (realStatus == LocationServiceStatus.Stopped)
            stats = LocationServiceStatusExt.Stopped;

        if (realStatus == LocationServiceStatus.Initializing)
            stats = LocationServiceStatusExt.Initializing;

        if (realStatus == LocationServiceStatus.Running)
            stats = LocationServiceStatusExt.Running;

        if (realStatus == LocationServiceStatus.Failed)
            stats = LocationServiceStatusExt.Failed;

        return stats;
    }
}

public struct LocationInfoExt
{
    public float altitude { get; set; }
    public float horizontalAccuracy { get; set; }
    public float latitude { get; set; }
    public float longitude { get; set; }
    public double timestamp { get; set; }
    public float verticalAccuracy { get; set; }
}

public enum LocationServiceStatusExt
{
    Stopped = 0,
    Initializing = 1,
    Running = 2,
    Failed = 3,
}

Usage:
Create a mock location
LocationServiceExt locationServiceExt = new LocationServiceExt(true);

Create a real location
LocationServiceExt locationServiceExt = new LocationServiceExt(false);

Modify the location later on
LocationInfoExt locInfo = new LocationInfoExt();
locInfo.latitude = 59.000f;
locInfo.longitude = 18.000f;
locInfo.altitude = -3.0f; //0.0f;
locInfo.horizontalAccuracy = 5.0f;
locInfo.verticalAccuracy = 5.0f;

locationServiceExt.lastData = locInfo; //Apply the location change

Full ported working example from Unity Doc.
public Text text;
IEnumerator StartGPS()
{
    text.text = "Starting";
    //Pass true to use mocked Location. Pass false or don't pass anything to use real location
    LocationServiceExt locationServiceExt = new LocationServiceExt(true);

    LocationInfoExt locInfo = new LocationInfoExt();
    locInfo.latitude = 59.000f;
    locInfo.longitude = 18.000f;
    locInfo.altitude = -3.0f; //0.0f;
    locInfo.horizontalAccuracy = 5.0f;
    locInfo.verticalAccuracy = 5.0f;
    locationServiceExt.lastData = locInfo;

    // First, check if user has location service enabled
    if (!locationServiceExt.isEnabledByUser)
    {
        text.text = "Not Enabled";
        yield break;
    }
    else
    {
        text.text = "Enabled!";
    }

    // Start service before querying location
    locationServiceExt.Start();

    // Wait until service initializes
    int maxWait = 20;
    while (locationServiceExt.status == LocationServiceStatusExt.Initializing && maxWait > 0)
    {
        text.text = "Timer: " + maxWait;
        yield return new WaitForSeconds(1);
        maxWait--;
    }

    // Service didn't initialize in 20 seconds
    if (maxWait < 1)
    {
        print("Timed out");
        text.text = "Timed out";
        yield break;
    }

    // Connection has failed
    if (locationServiceExt.status == LocationServiceStatusExt.Failed)
    {
        print("Unable to determine device location");
        text.text = "Unable to determine device location";
        yield break;
    }
    else
    {
        // Access granted and location value could be retrieved
        string location = "Location: " + locationServiceExt.lastData.latitude + " "
            + locationServiceExt.lastData.longitude + " " + locationServiceExt.lastData.altitude
            + " " + locationServiceExt.lastData.horizontalAccuracy + " " + locationServiceExt.lastData.timestamp;
        Debug.Log(location);
        text.text = location;
    }

    // Stop service if there is no need to query location updates continuously
    locationServiceExt.Stop();
}

A: Steps to follow:
First you need to start the GPS calling:
Input.location.Start();

The "start" takes some time initializing all the needed processes so you could do this:
IEnumerator InitLocationTracker()
    {
        // Start service before querying location
        Input.location.Start();

        // Wait until service initializes

        if (true == disableGPSMode)
        {
            //delegate to call again "InitLocationTracker"
            if (null != OnRetryLocation)
            {
                OnRetryLocation ();
            }
            //variable to check the location available
            isLocationAvailable = false;

            yield return null;
        }
        // I chose 20s to retry the call
        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
        {
            // Service didn't initialize in 20 seconds
            if (maxWait < 1)
            {
                Debug.Log("LocationTracker: Timed out");

                //GameObject to show error text
                errorText.text = "LocationTracker: Timed out";
                errorPanel.SetActive(true);

                //delegate to call again "InitLocationTracker"
                if (null != OnRetryLocation)
                {
                    isLocationAvailable = false;
                    OnRetryLocation ();

                    yield break;
                }

            }

            yield return new WaitForSeconds(1f);
            maxWait--;
        }

        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed)
        {
            Debug.Log("LocationTracker: Unable to determine device location");

            errorText.text = "LocationTracker: Unable to determine device location";
            errorPanel.SetActive(true);

            if (null != OnRetryLocation)
            {
                OnRetryLocation ();
            }

            isLocationAvailable = false;
        }
        else
        {
            Debug.Log("LocationTracker Location: " + current_lat + " " + current_lon + " " + Input.location.lastData.timestamp);
            isLocationAvailable = true;

            StartCoroutine(TrackLocation());
        }
    }

Then you can call and use the location data calling:
private float current_lat;
private float current_lon;

current_lat = Input.location.lastData.latitude;
current_lon = Input.location.lastData.longitude;

However I would suggest you calling a coroutine and make an infinite loop to check that you have GPS signal at any time. The pseudo code could be something like this:
 IEnumerator TrackLocation()
{
    while (true)
    {
        //5 seconds for example
        yield return new WaitForSeconds (5f);

        if (Input.location.status == LocationServiceStatus.Running)
        {
            //Get the location data here
        }
    }
}

One last note, if you need the GPS data in certain points you could move the coroutine to the zone where you need it. Is up to you how to program the GPS check and data usage.
Resource links (From Unity documentation)
LocationInfo
LocationService

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does every $k$ algebra necessarily have a basis closed under multiplication? Let $A$ be a $k-$algebra with $k$ field. Suppose $A$ is finite dimensional over $k$.
$\textbf{Q:}$ Is it possible to find a basis $B$ of $A$ over $k$ s.t. the basis set is closed under multiplication in general? It seems this is true in finite quiver path algebra quotient by admissible ideals or finite group algebra over field $k$. If not, what is the counter example?

A: No, the existence of such a basis is an extremely strong condition.  For instance, notice that for any $x\in B$, the powers of $x$ must be eventually periodic, since they are all elements of the finite set $B$.  In particular, if $A$ is a field extension of $k$, this implies every element of $B$ is a root of unity, and so $A$ must be spanned by the roots of unity it contains.  So for instance, if $k=\mathbb{Q}$ and $A=\mathbb{Q}(\sqrt{2})$, this is not possible since the only roots of unity in $A$ are $\pm 1$.

A: This is not always possible, for example $\mathbb{C}$ has no multiplication-closed basis over $\mathbb{R}$. The main theorem of this interesting AMM note provides many more examples.


text:
Q: Web scraping with cheerio not working with some elements I just started learning about web scraping and I found this tutorial:
https://www.mundojs.com.br/2020/05/25/criando-um-web-scraper-com-nodejs/
It works fine, however I'm trying to get different elements from the same webpage: https://ge.globo.com/futebol/brasileirao-serie-a/
With the group of classes of the tutorial it brings all the elements with the selected class, but with other classes it doesn't work:

As can be seen all fifty elements with the class ranking-item-wrapper are returned, but if I select elements with the class lista-jogos__jogo it doesn't return anything:

I don't get why I'm getting this error, since I'm doing exectly the same thing as it is done in the tutorial.
Here is a short version of the code:
const axios = require('axios');
const cheerio = require('cheerio');
const url = 'https://ge.globo.com/futebol/brasileirao-serie-a/';

axios(url).then(response => {
  const html = response.data;
  const $ = cheerio.load(html);
  console.log($('.ranking-item-wrapper')) // => tutorial class
  console.log('***')
  console.log($('.lista-jogos__jogo')) // => class that I'm using
}).catch(console.error);

A: I saw the answer from @Bradley and although it explained what was happening, it doesn't provide a solution. He was correct in saying the elements are being appended with Javascript. There are a few ways we can handle this to get the same data.
I saw your response regarding waiting for the elements to load, this is possible using something like JSDOM/Puppeteer but it's completely overkill and would most likely result in bugs from unsupported JS and/or a massive CPU/Memory overhead in comparison to something like Cheerio.
Typically, in my experience, the reason the elements are being appended with Javascript is that the data is being pulled externally from an API, this is a simple fix because you can just check the networking tools to see an XHR request which gets the data, usually it's in an easier-to-parse format too because it's being pulled from an API (JSON). This is very common now a days with all the client-side progressive web apps.
The alternative is the data is hard-coded in a site script which can be split out into a parsable format. You might see this on progressive web apps that take advantage of server-side rendering for the SEO benefit.
I found the data is coming from an external API which is returning JSON data. The URL Is:
https://api.globoesporte.globo.com/tabela/d1a37fa4-e948-43a6-ba53-ab24ab3a45b1/fase/fase-unica-campeonato-brasileiro-2021/rodada/38/jogos/
You will need to request this URL instead and parse the JSON response to get the data that you need, rather than using Cheerio.

A: It looks like those elements are being added with JavaScript when the page is loaded.
If you inspect the page in your browser with JavaScript disabled you can see that those elements don't exist, so they also wont exist when you pull down the page with Cheerio.


text:
Q: MySQL Delete with Limit This seems very simple, but it's failing.  All I want to do is delete all but the first row using the code below.
$sql    = "DELETE FROM ".TABLE_PREFIX."news WHERE course_id = $course_id LIMIT 1,18446744073709551615";
$result = mysql_query($sql, $db);

If I do this...
$sql    = "SELECT news_id FROM ".TABLE_PREFIX."news WHERE course_id = $course_id LIMIT 1,18446744073709551615";
$result = mysql_query($sql, $db);
while ($row = mysql_fetch_assoc($result)) {
    echo $row['news_id'] . '<br>';
}

All news_ids are echoed except the first one.  Why is the delete statement not working when the same statement for select is working?

A: Like @Sabashan said LIMIT in DELETE statement only allows one parameter.
If you want to exclude the 1st row, use something like:
DELETE FROM tnews WHERE course_id = $course_id
AND primary_key NOT IN
(SELECT * FROM (
SELECT primary_key FROM tnews ORDER BY something LIMIT 1 OFFSET 0))

The inner SELECT picks up the records to exclude.
The outer SELECT solves the problem that you cannot select from the same table that you're deleting from.
Because the inner SELECT is enclosed by the outer select MySQL materializes the result in a temp table and uses that instead of rerunning the query for every delete (which MySQL does not allow).

A: The delete statement is not working because of incorrect syntax near the limit keyword...you cannot do LIMIT 1,18446744073709551615...LIMIT must be followed by a single number when used with DEELTE
Reference: DELETE MYSQL
Only in a SELECT statement can you have LIMIT 1,18446744073709551615 clause
Reference: SELECT MYSQL
What you can do alternatively is find the course_id of the first row you want deleted, (and hopefully if the table is set up correctly and it is a primary key for the table and auto increments), do something like the below:
$sql = "DELETE FROM ".TABLE_PREFIX."news
        WHERE course_id >=".COURSE_ID_YOU_WANT_DELETED.";

Or this works as well:
$sql = "DELETE FROM ".TABLE_PREFIX."news
        WHERE course_id !=".COURSE_ID_YOU_WANT.";

A: You should find the id of the first row and do a
DELETE FROM table WHERE id != id_found

or find the ids you have to delete and
DELETE FROM table WHERE id IN (ids_found)


text:
Q: how to tell if a photo was taken in landscape or portrait? JPEG .NET metadata orientation Thru VB.net/C# is there any way to read any metadata of off a JPEG to tell if the photo was taken in landscape or portrait?
I would assume a camera would need an accelerometer first of all to even tell what direction is up...correct? Assuming there is that kind of intelligence to detect the angle of tilt, how would I go about reading that info from a JPEG?
I found some samples online to read metadata with vb/.net not sure what to read to find the info i need.
Appreciate any pointers.....

A: Yes, there's an EXIF tag that can store the orientation.  Tag number 274, values are documented here.  Sample code to read the tags from the JPEG data is available here.

A: A lot of digital cameras now have sensors within them to detect if the picture was taken in landscape or portrait mode. They then store this information in the header of the JPG. This data is known as EXIF.
Here is a pretty good tutorial on extracting the EXIF data from a JPG file. In addition to portrait/landscape info you can also extract (usually) the model/make of camera, lens settings, time/date etc.
http://www.codeproject.com/KB/graphics/NishExifReader.aspx

A: Would it be sufficient to simply compare the width of the JPG image to its height and if width > height, treat as landscape?
I have done this in C# before (although I can't remember the implementation details now but I remember it wasn't particularly difficult, a couple of lines of code only) for a website I worked on which required uploaded JPGs to be displayed within a frame (such as you might hang on your wall) and we needed to know whether to add the landscape or portrait version of the frame.


text:
Q: Can't Connect to Vbox Virtual Machine on my Ubuntu server via windows RDP I have an ubuntu 18.x server. I installed virtualbox on the server and configured a new VM using these instructions. When I try the last step I get an error window

I also noticed that when I run netstat, the IP associated with my VM's port is 0.0.0.0
But when I run nmap on my servers IP I get this
PORT     STATE SERVICE
22/tcp   open  ssh
139/tcp  open  netbios-ssn
445/tcp  open  microsoft-ds
5001/tcp open  commplex-link

Where the last row is the port number of my VM
Here is the output of $ VboxManage showvmdetails tails (which is far more verbose than the tutorials example)

Name:                        tails
Groups:                      /
Guest OS:                    Linux 2.6 / 3.x / 4.x (32-bit)
UUID:                        7107a87f-4ffb-4c80-9cf9-0bc3ff6c6b4c
Config file:                 /var/vbox/tails/tails.vbox
Snapshot folder:             /var/vbox/tails/Snapshots
Log folder:                  /var/vbox/tails/Logs
Hardware UUID:               7107a87f-4ffb-4c80-9cf9-0bc3ff6c6b4c
Memory size                  1024MB
Page Fusion:                 disabled
VRAM size:                   8MB
CPU exec cap:                100%
HPET:                        disabled
CPUProfile:                  host
Chipset:                     piix3
Firmware:                    BIOS
Number of CPUs:              1
PAE:                         enabled
Long Mode:                   disabled
Triple Fault Reset:          disabled
APIC:                        enabled
X2APIC:                      enabled
Nested VT-x/AMD-V:           disabled
CPUID Portability Level:     0
CPUID overrides:             None
Boot menu mode:              message and menu
Boot Device 1:               DVD
Boot Device 2:               DVD
Boot Device 3:               HardDisk
Boot Device 4:               Not Assigned
ACPI:                        enabled
IOAPIC:                      disabled
BIOS APIC mode:              APIC
Time offset:                 0ms
RTC:                         local time
Hardw. virt.ext:             enabled
Nested Paging:               enabled
Large Pages:                 disabled
VT-x VPID:                   enabled
VT-x unr. exec.:             enabled
Paravirt. Provider:          Default
Effective Paravirt. Prov.:   KVM
State:                       running (since 2019-12-11T04:49:39.483000000)
Monitor count:               1
3D Acceleration:             disabled
2D Video Acceleration:       disabled
Teleporter Enabled:          disabled
Teleporter Port:             0
Teleporter Address:
Teleporter Password:
Tracing Enabled:             disabled
Allow Tracing to Access VM:  disabled
Tracing Configuration:
Autostart Enabled:           disabled
Autostart Delay:             0
Default Frontend:
Storage Controller Name (0):            tails_SATA
Storage Controller Type (0):            IntelAhci
Storage Controller Instance Number (0): 0
Storage Controller Max Port Count (0):  30
Storage Controller Port Count (0):      30
Storage Controller Bootable (0):        on
tails_SATA (0, 0): /tmp/tails-amd64-4.1.iso (UUID: b48d5261-170d-4bc8-a1d6-2ee18c29051f)
tails_SATA (1, 0): /var/box/tails.vdi (UUID: 94e4ba64-b33d-4cdf-a37f-959ccd3dcffb)
NIC 1:                       MAC: 080027B4FB40, Attachment: NAT, Cable connected: on, Trace: off (file: none), Type: 82540EM, Reported speed: 0 Mbps, Boot priority: 0, Promisc Policy: deny, Bandwidth group: none
NIC 1 Settings:  MTU: 0, Socket (send: 64, receive: 64), TCP Window (send:64, receive: 64)
NIC 2:                       disabled
NIC 3:                       disabled
NIC 4:                       disabled
NIC 5:                       disabled
NIC 6:                       disabled
NIC 7:                       disabled
NIC 8:                       disabled
Pointing Device:             PS/2 Mouse
Keyboard Device:             PS/2 Keyboard
UART 1:                      disabled
UART 2:                      disabled
UART 3:                      disabled
UART 4:                      disabled
LPT 1:                       disabled
LPT 2:                       disabled
Audio:                       enabled (Driver: ALSA, Controller: AC97, Codec: STAC9700)
Audio playback:              disabled
Audio capture:               disabled
Clipboard Mode:              disabled
Drag and drop Mode:          disabled
Session name:                headless
Video mode:                  720x400x0 at 0,0 enabled
VRDE:                        enabled (Address 0.0.0.0, Ports 5001, MultiConn: off, ReuseSingleConn: off, Authentication type: null)
VRDE port:                   5001
Video redirection:           disabled
VRDE property               : TCP/Ports  = "5001"
VRDE property               : TCP/Address = <not set>
OHCI USB:                    disabled
EHCI USB:                    disabled
xHCI USB:                    disabled

USB Device Filters:

<none>

Available remote USB devices:

<none>

Currently Attached USB Devices:

<none>

Bandwidth groups:  <none>

Shared folders:<none>

VRDE Connection:             not active
Clients so far:              0

Capturing:                   not active
Capture audio:               not active
Capture screens:
Capture file:                /var/vbox/tails/tails.webm
Capture dimensions:          1024x768
Capture rate:                512kbps
Capture FPS:                 25kbps
Capture options:

Guest:

Configured memory balloon size: 0MB
OS type:                     Linux26
Additions run level:         0

Guest Facilities:

No active facilities.

How can I fix this to connect to my VM via RDP?
I really Just don't know where to even start. I'm a software developer, and normally I can extrapolate some information from errors, but this doesn't tell me anything. Is the problem in the server side? on the host side? my network configuration? the virtual box setup? my Windows permissions? I'm all over the place trying to find a path to follow. I don't know enough about networking so I am here for help. I've posted on Superuser and Serverfault as well and received no responses whatsoever

A: Had the same problem following the guide you used. Did the following to fix the problem:

enable multi-connection
sudo VBoxManage modifyvm ubuntu16 --vrdemulticon on

allow port 5001
sudo ufw allow 5001/tcp

reboot
sudo VBoxManage controlvm ubuntu16 savestate
sudo reboot
sudo VBoxManage startvm ubuntu16 --type headless

finally, can open Microsoft Remote Desktop to enter IP address and port
PC name: 192.107.123.12:5001

a screenshot of connecting to Remote Desktop
The above worked for me on a Ubuntu 18.04 server with Virtual Box 5.2.44. Think should also work on Ubuntu 16.04 with Virtual Box 6.1.
Hope it can be of any help!

A: It turns out that you are using an old, buggy version of vbox extension pack. You will have tho update the same. Here is the link to the page to download it.


text:
Q: Understanding the operator norm through this example? I'm a better learner through examples so I need help solving this one to better understand the operator norm.
We define first the norm of a matrix as $\|A\|_\infty = \sup_{1\leq i,j\leq n}|c_{ij}|$ .
Questions: Prove that $\Omega(A,B)=tr(AB)$ is continuous and calculate its operator norm.
I have no idea on how to proceed.
I'm not trying to learn the solution. I just want to know the reasoning behind it. Am I supposed to find an inequality of some sort and bound the quantity? What's the method to proceed?

A: Since you said you only want to know how to approach this type of problem, I'll be a little vague here so you can fill in the details. First, to define the operator norm, as Teresa Lisbon mentioned in the comments, we can't really address this problem until we understand the spaces and norms we are talking about. You equipped the space $\mathbb{R}^{n\times n}$ with the $\ell^\infty$ norm. However, $\Omega$ is a mapping from $(\mathbb{R}^{n\times n})^2 \to \mathbb{R}$. To define the operator norm, we need to have a norm on the space $(\mathbb{R}^{n\times n})^2$. For the purposes of this problem, let $(A,B) = (a_{ij},b_{ij})_{i,j=1,\dots, n}$ and say that,
$$\|(A,B)\|_{\infty} = \sup_{i,j}\max\{|a_{ij}|,|b_{ij}|\}.$$
Then the definition of the operator norm is,
\begin{equation}
\tag{1}
\|\Omega\| = \sup_{\|(A,B)\|_{\infty} = 1} |\Omega(A,B)|.
\end{equation}
From here on, I'm going to be a little vague. We can prove continuity directly. For any $\epsilon > 0$, introduce two perturbation matrices $\|(A_\epsilon,B_\epsilon)\|_\infty < \epsilon$. Then,
$$(A + A_\epsilon)(B+B_\epsilon) = AB + AB_\epsilon + A_\epsilon B + A_\epsilon B_\epsilon.$$
You can use this and the definition of $\Omega$ to directly bound the quantity $\|\Omega(A,B) - \Omega(A+A_\epsilon,B+B_\epsilon)|$ by some function of $\epsilon$. This would show that for any sequence $\{(A_n,B_n) \in (\mathbb{R}^{n\times n})^2\}$ such that $(A_n,B_n) \to (A,B)$, $\Omega(A_n,B_n) \to \Omega(A,B)$. Thus, $\Omega$ is continuous.
To compute the operator norm, we again consider equation (1). To compute $\|\Omega\|$, we want to show two things. First, we need a bound $M$ such that for all $(A,B)$ with $\|(A,B)\|_\infty=1$, $|\Omega(A,B)| \leq M$. Second, we need an example of matrices $\|(A,B)\|_\infty = 1$ such that $|\Omega(A,B)| = M$.
The easiest way to do this is to explicitly write out $\Omega$ in terms of the entries of $A$ and $B$. Note that,
$$\text{tr}(AB) = \sum_{k=1}^n (AB)_{k,k} = \sum_{k=1}^n \sum_{i=1}^n a_{k,i}b_{i,k}.\tag{2}$$
Then I'll leave this for you. Given that $|a_{i,j}|,|b_{i,j}| \leq 1$ for every $i,j \in \{1,\dots,n\}$, is there a simple choice of $M$ such that
$$\text{tr}(AB) \leq M?$$
Second, are there matrices $(A,B)$ with norm 1 such that $\text{tr}(AB) = M$?
Hint:

 Given that $-1\leq a_{ij},b_{ij}\leq 1$ for every $i,j$, is there a choice of entries $(a_{ij},b_{ij})_{i,j = 1,\dots,n}$ that clearly maximize equation (2)?

With this as an example, let's talk more generally. Suppose you have a normed vector space $X$ such that the set $\{x \in X: \|x\|_X= 1\}$ is compact and a continuous operator $\Omega: X \to \mathbb{R}$ and you want to compute the operator norm. Then try investigating what $\Omega(x)$ looks like and see if there is an $x \in X$ such that $\|x\|_X = 1$ and $|\Omega(x)| \geq |\Omega(x')|$ for any other $x' \in X$ such that $\|x'\|_X = 1$. If you can find that value of $x$, then $\|\Omega\| = |\Omega(x)|$. Note that the existence of this value $x$ follows from the continuity of $\Omega$ and the compactness of $\{\|x\|_X = 1\}$ in $X$.


text:
Q: Simple code methods (Intent, finish(), etc...) are not recognized I think it has something to do with gradle, but anyway the simple methods now do not work and aren't recognized by the system and it shows a red line under them, this picture shows it.(The picture is just to show the red line)
The code at the top -

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class DriverLoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etDriverEmail, etDriverPassword;
    private Button btnDriverLogin, btnDriverRegistration;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener firebaseAuthListener;

A: Seems like you're missing the correct imports. Also make sure your activity extends
the right class, E.g. Activity or AppCompatActivity
import android.os.Bundle; //Make sure all imports are satisfied

public class ExampleActivity extends Activity{ //your activity implementation has to extend an activity class.
...
}

If a class is not imported (and you're using Android studio) you can always press CTRL + SPACE while having the cursor in the missing class/ method to import it.
BTW: The
@Override

throws an error when the method does not override from its superclass. This is either because you forgot to extend (Base)Activity / AppCompatActivity, or those in turn where not imported at the top of your activity class.


text:
Q: Bitmap Collision Detection(AS3) I have some bitmaps, one of the character and the other of spikes. I'm wanting to detect when the character bitmap collides with the spikes. The spike bitmaps are added to an array because there's so many of them. I've read things like this: http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
But that uses BitmapData and draws the bitmaps. Mine are embedded from PNGs. For example:
[Embed(source="../lib/NewChar.png")]
    public var CharImage:Class;

public var char:Bitmap = new CharImage();

How would I go about this or maybe I'm just missing something?

A: Since embedded bitmaps is represented by the BitmapAsset class you should be able to access your embedded image data through the bitmapData property:
public var img:Bitmap = new CharImage();

var data:BitmapData = img.bitmapData;


text:
Q: Why does my reputation drop by a few points every Friday night? For several weeks I have lost reputation points on the night between Friday and Saturday without explanation.
Two weeks ago I lost 2 points, last week I lost 4 points and last night I lost 4 points.
The problem is not losing points, but is not knowing why.

*

*Is an edit that has been deleted?

*Is there a bug?

*There is a rule that I do not know?

*Someone has a grudge against me?

*Is there a curse of on Friday night?

An idea of future suggestion (if it is not a bug) is to show why I lost these points.
The question may have already been asked, but I have not found them.

A: As far as I can tell you are losing some score as questions with low views, score and no answer get automatically deleted by a batch job.
You seem to have edited a number of them, which of course gave you +2 rep. As the questions get deleted so goes the rep bonus.
Unfortunately, you can't see the questions because they are deleted and you need more reputation.


text:
Q: How to convert data from file into a structure in C? I have to make a function that converts data(time) from file into structure with use of other function. So take this from the file (2018-06-01 01:00:00) and convert it into structure.
First is year then month, day, hour, min and sec.
I am kinda new to this so I don't know how to properly use strtok fro parsing.
Data in file look like this:

*

*id;sensor_id;time;m3

*12899;1;2018-06-01 01:00:00;0.0000

*150362;222;2019-11-14 14:00:00;0.2465

*150369;35;2019-11-14 15:00:00;0.2550

*. . .

And this is how the structre should looks like.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct {
int year;
int month;
int day;
int hour;
int min;
int sec;
int dayInWeek;
}tDateTime;

And declarations of functions. I have already solved the "giveDayInWeek" function.
tDateTime dejDateTime(char* datetime) //converts input from text file (2018-05-01 01:00:00) into structure, with using giveDayInWeek

int giveDayInWeek(int y, int m, int d) //returns dan in a week (0-Monday,…,6-Sunday)
{
    static int t[] = { 0,3,2,5,0,3,5,1,4,6,2,4 };
    y -= m < 3;
    return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
}

I would really appreaciate a help.
Thank you

A: A good approach would be, to have a function that return each value you are interested in (getYear, getMonth, ...), that receives the line as input, and return the desired value:
#include <stdio.h>
#include <string.h>
#define YEAR_LEN 4

typedef struct {
  int year;
  int month;
  int day;
  int hour;
  int min;
  int sec;
  int dayInWeek;
}tDateTime;

int getYear(char* p_line){
  char year[YEAR_LEN+1];
  strncpy(year, p_line+8, 4);
  year[YEAR_LEN] = '\0';   /* null character manually added */
  return atoi(year);
}

int main(int argc, char** argv){
  char const* const fileName = argv[1];
  FILE* file = fopen("data.txt", "r");
  char line[256];
  tDateTime dt;

  while (fgets(line, sizeof(line), file)) {
    printf("line: %s\n", line);
    dt.year = getYear(line);
    printf("%d\n", dt.year);
  }

  fclose(file);
  return 0;
}

After this is working you could also group all functions call into another function (something like getData) in that way the code is more organized and more maintainable.
Something like:
tDateTime getData(char* p_line){
  tDateTime res;
  res.year = getYear(p_line);
  res.month = getMonth(p_line);
  return res;
}


text:
Q: GraphicsMagic, create new image with another image centered in it I have an image I1 of size AxB and want to create a bigger image I2 with a solid background of size CxD where C>A and D>B. I need to put I1 in I2 so that upper-left corner of I1 be at X,Y point of I2.

How can I do this with GraphicsMagic tools?

A: Like this:
gm convert -size 1200x1000 xc:steelblue -draw 'image over 10,200 600,800 "tux.png"' result.png

where C=1200, D=1000, x=10, y=200

Or, less flexible over the positioning:
gm convert -background steelblue "tux.png" -gravity center -extent 1200x1200 result.png


text:
Q: Mounting hard drive from FreeBSD Live CD? Before my question, a little background info, as I'm not sure whether it might be pertinent or not:
I am trying to set up full disk encryption using GELI, booting from an external thumb drive, on FreeBSD 10.1.  I've done this several times over the years with earlier versions of FreeBSD, based on section 3.5 of the this paper.
It's pretty out of date by this point - written in 2005 based on FreeBSD 6.0 - but it's served me well over the years and I haven't yet been able to find anything more recent.
Anyway, I have wiped the hard drive, and done geli init, geli attach, bsdlabel, and newfs.  Now I'm trying to install the system, as in the bottom part of section 3.5.4, which starts:
mount /dev/ad0.elia /fixed

When I try to do this, it tells me "No such file or directory" (referring to /fixed).
So, I try mkdir /fixed.  But it then tells me "Read-only file system".
Then I did a chmod +w /, which didn't complain to me, and tried the mkdir again, but it again told me that it was a read-only file system.
How can I do this? Thanks.
Edit: Poking around, I found that there's a preexisting /mnt directory, and I can mount into that.  I can't mkdir /mnt/fixed, though, so I guess I can only mount one thing at a time.  And there's no /dist directory, I can't find anything like /dist/10.1-RELEASE, and there seems to be no file anywhere called install.sh, so I can't do what I wanted to do by mounting anyway... but I guess that's a different question.

A: The installer now has support for setting up ZFS on top of geli. I highly recommend you use the installer. It does things a bit differently than it sounds like you're trying to (didn't follow the link), but it works well.
The new installer setup creates two GPT partitions, one for /boot where only the kernel and a password protected copy of the encryption key. At boot, the kernel prompts for the password and sets up the encrypted disk. So the only thing unencrypted is your kernel.
And you can easily and safely copy the password protected key to your external thumb drive, or even better, setup an external disk to replicate the unencrypted boot and encrypted root and zfs send to an external disk for a full system backup, which you can then take off-site.


text:
Q: Is there a way to install dependencies from a package.json file into a different directory? I'm wondering if there is a way for the dependencies of a package.json file into a different directory. Scenario is this:
I have a project that I'm deploying with git and and post-receive hook. When I want to deploy my project, I push it to the bare git repo on my server, which then clones the repo into a separate folder (thus making the files available), runs npm install to install the dependencies, runs the build (in this case grunt), moves the build file to the folder being hosted by the web server, overwriting any older files, and then proceeds to clean up the cloned folder by removing it.
Unfortunately, this also has the side effect of wiping out the node_modules folder which means that a fresh set of dependencies must be installed on the next build which takes time if I'm trying to deploy quickly.
The reason behind my question is essentially wondering if there is a more graceful solution than what I have currently. Is there a way that I could install the dependencies to a dependencies directory on my server and then run all the builds from there? That way I could keep all of my modules in 1 place and have other builds that I run on my server use those packages as well, while also adding any additional dependencies that they require.
My research so far has not proven successful—  I tried running
npm install /some_folder --prefix /other_folder

but that had the adverse effect of creating a directory structure that looked like this:
/
├── some_folder
|  ├── <various files>
|  └── package.json
└── other_folder
   └── node_modules/
      └── some_folder/
         ├── <various files from first folder>
         ├── package.json
         └── node_modules/

which wouldn't really work for having a central dependencies directory.
I also found 1 question that talked about using symbolic links. How would that work?

A: What it sounds like you actually want is to have a local package cache on your build server. NPM already does this. However, by default:

Commands that make non-essential registry requests (such as search and
  view, or the completion scripts) generally specify a minimum timeout.
  If the .cache.json file is younger than the specified timeout, then
  they do not make an HTTP request to the registry.

This does not include package installs. You can circumvent this by doing the following:
npm --cache-min 9999999 install <package-name>

There are few requests to have a nicer interface to this command as it's a pretty common requirement.
There are also a couple of projects that provide alternative mechanisms:

*

*https://www.npmjs.com/package/npm-cache - provides an alternative command that caches packages locally

*http://mixu.net/npm_lazy/ - effectively an internal package registry server


text:
Q: ipywidget: Update one widget based on results from another Here is my current code:
all_teams = np.unique(march['PitcherTeam'])
all_pitchers = np.unique(march['Pitcher'])
all_pitches = np.unique(march['TaggedPitchType'])
_ = widgets.interact(pitch_chart, df=march, team=list(all_teams), pitcher = list(all_pitchers), pitch_type = list(all_pitches))

It currently outputs this:
pitch chart
I want it to be able to eliminate future drop down choices based on choices they have already made. For example, when they select ORE_DUC as their team, I want it to only present pitchers that play for ORE_DUC in the next line, and then based on the pitcher they choose, only present the pitches they pitch.


text:
Q: Angular translate directive vs filter: is XSS possible? I have a translation key which is actually a HTML code, both encoded as well as unencoded.
   $scope.translations = {
    "html_code" : "",
    "html_code_full" : "",
    "greeting" : "Welcome!"
  }

When I use these values to display the translated text in view, I use two methods:

*

*As directive {{translations.html_code}}

*As filter {{translations.html_code|translate}}
I try the same for translations.html_code_full.
Here's the code for view:
translations.html_code = {{translations.html_code|translate}}
translations.html_code = {{translations.html_code}}

translations.html_code_full = {{translations.html_code_full|translate}}
translations.html_code_full = {{translations.html_code_full}}

This is the output I get:
translations.html_code = <script>alert('Alert!');</script>
translations.html_code =

translations.html_code_full =
translations.html_code_full =

As it's clear that directive implementation is encoding the translation key to HTML, but filter is not. Why is this difference in output between directive vs filter implementation?
And why am I not getting an alert if it's rendering the HTML?
Here is the plunk I created for demo.

A: The AngularJS frame work is protecting your application from XSS attacks.

Cross-site scripting carried out on websites accounted for roughly 84% of all security vulnerabilities documented by Symantec as of 2007.

-- Wikipedia - Cross-site scripting
So what are you really trying to do? Maybe we can show you how to do it in a safe manner.

A: For me the translate library did not cover all the instances. So I needed to cover a normal script attack and an Angular aimed attack.  We read part of a URL as a key and then display that as a message so open to attack in the URL.
The 2 URLs that I tested against:
/mypage.html#/{{{}.")));alert(1)//";}}

mypage.html#/%3Cscript%3Ealert('foo')%20%3C/script%3E

For me the first one would be escaped correctly if using the translate directive in the page but not the filter. The second one was a successful attack when using the directive in the page but was escaped correctly when using the filter.
In the end I escaped, translated and checked in the controller before assigning the value to the scope variable. So now there is no translate directive or filter in the page.
   function translateParam(paramData, defaultKey){
        var deferred = $q.defer();
        var trusted =  $sce.trustAsHtml(paramData);
        $translate(trusted).then(
            function(translatedString){
                if(translatedString == trusted){
                    //no key has been found so show a default
                    deferred.resolve($translate.instant(defaultKey));
                }
                else{
                    //the key has been found correclty
                    deferred.resolve(translatedString);
                }
            }
        );
        return deferred.promise;
    }

//called like this
  $scope.error = translateParam('keyFromURL','defaultKeyInTranslateFile');

You need to inject $q, $sce and $translate.  For me this is the most secure and reliable solution.


text:
Q: MUD Server and text based client I have started to develop a simple MUD (text based multiplayer dungeon) where client uses only terminal to connect and play.
However i approached it the different way, i want the player to be able to move around the rooms (x,y) and see the map of a room like in the screenshot below

The whole screen as it is seen is being sent out by the server to the client on updates like:
somebody moved, something has changed in the current location, somebody dropped something, etc ...
At the bottom of the screen, there is a place where clients can put commands like:
look, east, west, pick up, drop, inventory, ...
Problem
The problem with the design however is, that when user is in the middle of putting a command and in meantime server has updated it's screen (somebody moved, or some event was generated ) he will loose the command he was typing because the whole screen got refreshed.
How do i send the screen to the player?
I build the view on the server side, and when sending to the client i use ANSI characters to:

*

*Clear the screen (\u001b[H\u001b[2J)

*Locate the cursor in specific areas of the window (\033[....) to draw specific areas of the view

Question
Is it possible, that clients don't loose their input when i send a view to them?
In other words, is it possible (maybe some ANSI code required?) that when i type something in the terminal and meantime if i receive something, my input is not broken by the newly received message?
To visualize the problem:
Good:
from server: aaa
from server: bbb
> input

Current:
from server: aaa
> in
from server: bbb
put

A: Alternative Solution
It's probably a better idea to construct the view on the Client side - then the server only needs to send the "raw information" and the client can display it. In this case, you've said the server sends a new view on events like someone moving - so just send a message to the client saying "Bob has moved", rather than an entirely new rendered screen, and let the client handle the update.
This has multiple advantages - to solve your problem, you can just buffer any server input until the user's finished typing, or redraw any bits of the screen that the client user's not actively changing.
It also allows for more customisation on the client side - if the server sends the view over, how does the client display it on a terminal that's a different resolution to the server's view? With client-side rendering, you can deal with this sort of issue on a per-client basis. You can also open up the door to massively more customisation by letting client users customise their personal views.
Workaround with your existing strategy
If you are fixed on having the server construct the views, then on the client you might be able to read single-character inputs at a time (on windows _getch, on linux ncurses provides this functionality), then if a server update occurs just render the new view and then re-render what the user's entered beforehand.
Another Suggestion
ANSI codes are... messy. Using a library like curses can make console-based-guis much nicer and more maintainable. On linux there's ncurses, and on windows there's an open-source variant called pdcurses (apparently has the same API, just exposed in an independent library. You'd need to change linker settings when compiling on Windows, but hopefully not any code). Thanks to Bartek for mentioning this.


text:
Q: How can I pass arguments to event handlers in jQuery? With jQuery code like:
$("#myid").click(myfunction);

function myfunction(arg1, arg2) {/* something */}

How do I pass arguments to myfunction while using jQuery?

A: $("#myid").on('click', {arg1: 'hello', arg2: 'bye'}, myfunction);

function myfunction(e) {

    var arg1 = e.data.arg1;
    var arg2 = e.data.arg2;

    alert(arg1);
    alert(arg2);

}

//call method directly:
myfunction({
    arg1: 'hello agian',
    arg2: 'bye again'
});

Also allows you to bind and unbind specific event handlers using the on and off methods.
Example:
$("#myid").off('click', myfunction);

This would unbind the myfunction handler from #myid

A: There are great answers already, but anyway, here are my two cents. You can also use:
$("#myid").click({arg1: "foo", arg2: "bar"}, myfunction)
And the listener would look like:
function myfunction(event){
    alert(event.data.arg1);
    alert(event.data.arg2);
}

A: Old thread, but for search purposes; try:
$(selector).on('mouseover',...);

... and check out the "data" parameter:
http://api.jquery.com/on/
e.g.:
function greet( event ) {
  alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {name: "Karl"}, greet );
$( "button" ).on( "click", {name: "Addy"}, greet );

A: Simple:
$(element).on("click", ["Jesikka"],  myHandler);

function myHandler(event){
   alert(event.data);     //passed in "event.data"
}

A: The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)...
$("#myid").click(function() {
    myfunction(arg1, arg2);
});

jsFiddle.
This create an anonymous function, which is called when the click event is triggered. This will in turn call myfunction() with the arguments you provide.
If you want to keep the ThisBinding (the value of this when the function is invoked, set to the element which triggered the event), then call the function with call().
$("#myid").click(function() {
    myfunction.call(this, arg1, arg2);
});

jsFiddle.
You can't pass the reference directly in the way your example states, or its single argument will be the jQuery event object.
If you do want to pass the reference, you must leverage jQuery's proxy() function (which is a cross browser wrapper for Function.prototype.bind()). This lets you pass arguments, which are bound before the event argument.
$("#myid").click($.proxy(myfunction, null, arg1, arg2));

jsFiddle.
In this example, myfunction() would be executed with its ThisBinding intact (null is not an object, so the normal this value of the element which triggered the event is used), along with the arguments (in order) arg1, arg2 and finally the jQuery event object, which you can ignore if it's not required (don't even name it in the function's arguments).
You could also use use the jQuery event object's data to pass data, but this would require modifying myfunction() to access it via event.data.arg1 (which aren't function arguments like your question mentions), or at least introducing a manual proxy function like the former example or a generated one using the latter example.

A: while you should certainly use Alex's answer, the prototype library's "bind" method has been standardized in Ecmascript 5, and will soon be implemented in browsers natively. It works like this:
jQuery("#myid").click(myfunction.bind(this, arg1, arg2));


text:
Q: How to get last word name from a string I have a word such as
var text = 'http://xxx:9696/images/FSDefault.jpg';

How to get only the word  FSDefault.jpg

A: Use String#split method to split based on delimiter / and get the last element of the array using Array#pop method.

var text = 'http://xxx:9696/images/FSDefault.jpg';

console.log(text.split('/').pop())

Or you can use String#lastIndexOf method along with String#substr method.

var text = 'http://xxx:9696/images/FSDefault.jpg';

console.log(text.substr(text.lastIndexOf('/') + 1))

A: This is pretty verbose but conveys the logic.
var text = 'http://xxx:9696/images/FSDefault.jpg';
var parts = text.split('/'); // Split the string into an array of strings by character /
var lastIndexOf = parts.length - 1; // Determine the last word's 0-based index in array (length -1)
var last = parts[lastIndexOf]; // Grab the last part of the array.
alert(last); // Alerts FSDefault.jpg


text:
Q: Does the gold version of the Generalist badge need to be re-evaluated? I've read some of the history on the Generalist badge in these questions:
"The generalist badge should be gold" and "Badge suggestion: Polymath (gold version of Generalist)".
The arguments were made pretty well for a gold level version of Generalist (Polymath, Polyglot or Sage defined it like "Provided non-wiki answers of 75 total score in 20 of top 40 tags") in those questions and I would add the following:

*

*The definition of a gold badge:

Gold badges recognize important contributions from members of the
  community. They are rarely awarded.

The definition of a silver badge:

Silver badges are less common than bronze ones. You'll need to plan
  your strategy to get one of these.

After the Generalist tag has been around for ~4 years it has only a little over 500 people achieving it on SO. It's relatively difficult to achieve and as a silver badge says "You'll need to plan your strategy" to achieve it. You can make a pretty decent case that Generalist is one of the most difficult (if not the most) Silver badges to achieve as well as being good for the site.

*A gold version of Generalist would re-encourage the ~500 users who achieved a score of 15 in 20 of 40 top tags. Specifically this refers to those that just scored 15 in certain tags and moved on, it would give them incentive to go back and visit those tags more often if there were a gold badge to be earned.
Based on the responses in the two threads I posted, it seemed like people think there should be a badge like this, it just didn't seem like there was a consensus on the details back then.
My suggestion would be altering the definition to try and best balance difficulty of achievement and value to the community. Something like this:

Provided non-wiki answers of 50 total score in 20 of top 40 tags

Another possibility to add would be a requirement like "having at least 2 silver tag badges".
So the actual question is: If there was a gold version of Generalist, what should it look like and why?
EDIT
To clarify my read of the situation: It appears the community has decided the original designation of Generalist as a silver badge is acceptable(explicitly by making it Silver originally some what implicitly by leaving it). My example is proposing that the gold version would be set with an equally high bar. The question I am asking is that what it should look like, why or why not?

A: "Encyclopedic" Gold Badge
Could also be called "Omniscient", "Ubiquitous", "All-Around", or "Pantologist".
Here's what I would make it look like:

*

*Provided at least 15 non-wiki answers (each scoring at least 2) of at least 75 total score in 30 of top 40 tags

To satisfy the "Important contributions to the site" requirement for a gold badge, I'm including the requirement of providing at least 15 non-wiki answers in each of the tags.  It must include more than just one good/lucky answer that happens to score very high.  Qualifying answers must each score at least 2, to prevent someone who has 1 answer worth 75 in a tag from providing 14 useless, no-score answers in that tag just to qualify.
I made the total score 75, because it is 5 times the silver "Generalist" amount, and it seems like 75 points worth of non-wiki answers in a tag is an important contribution to the site.
I increased the "20 of top 40" from "Generalist" to "30 of top 40" so that more tags would be required.  I didn't increase the "40" so that we don't accidentally include more tags outside the Top 40 that wouldn't be considered for a "Generalist" Badge.
Yes, these requirements incorporate elements of other answers in the past (in questions you've linked to already) that have made similar suggestions for the requirements of a gold version of "Generalist", but I've added something new -- the requirement of at least 15 answers, each scoring at least 2, in each of the tags.
I don't think "earning n tag badges" should be a requirement.  I don't think that earning any unrelated badges should be required for earning another badge.
The numbers could of course be tweaked; they are somewhat arbitrary.
All these requirements make me wonder if anyone at all would be granted such a badge on day 1 based solely on pre-existing answers.


text:
Q: Regex match through multiple lines For example we have following string:
Something
AnotherThing
Something AnotherThing

If I use RegexOptions.Singleline with pattern Something.+?AnotherThing then I get two matches when I want to match first and second lines only. I want to use something like FirstLine#endofline##startofline#AnotherLine. So i use:
var regex = new Regex(@"Something$^AnotherThing", RegexOptions.Multiline);

but it doesn't work. I know that I can use some hack with Singleline to match first two lines (and not the last one), but the question: Is it even possible to match exact two texts in exact 2 lines without Singleline specifier, with Multiline option only? And why does it behaves like this.

A: How about:
Something\r?\nAnotherThing

\r? in case the string doesn't come from Windows.
The reason Something$^AnotherThing doesn't work with the RegexOptions.Multiline option, is because ^ and $ match at line breaks, not the line breaks themselves, so the following would work:
new Regex(@"Something$\r?\n^AnotherThing", RegexOptions.Multiline);

A: Try to match using the carriage return and line break characters, e.g.
Something\r?\nAnotherThing

Basically, carriage returns are causing you trouble (you're not alone). Do you know which OS your text is coming from? If it's from Windows then there will be a \r before the \n, which you need to account for.


text:
Q: New Relic not loading configuration file Spring Boot App I have a Spring Boot application that I'm trying to monitor with New Relic APM.
On my homologation server running Ubuntu I start the application using the command:
nohup mvn -Drun.jvmArguments=-javaagent:/home/newrelic.jar -Djava.net.preferIPv4Stack=true & tail -f nohup.out

The application starts successfully and the New Relic agent is started along, I have the output
[INFO] Attaching agents: []
INFO: New Relic Agent: Loading configuration file "/home/./newrelic.yml"
Nov 10, 2017 14:03:47 +0000 [3882 1] com.newrelic
INFO: New Relic Agent: Writing to log file: /home/logs/newrelic_agent.log

And the data is sent to my New Relic console.
But when I tried the same command on my production server I only receive the output:
[INFO] Attaching agents: []

The application starts but I do not see the application on my New Relic console. It seems like the agent isn't loading the configuration file. newrelic.yml is on the same file that newrelic.jar. Both are the same application with the difference that on the homologation server, that gets monitored, the MySQL database is on the same machine and on the production server the database is on another machine.
What could be happening?

A: Are you using some other javaagent?
we have found out that the Dynatrace One agent has some issues with new relic. preventing it from starting. in order to the new relic to work we needed to uninstall the Dynatrace agent.


text:
Q: Values related to a max value in a for loop python I'm now able to print the maximum value for profit in my for loop but I also need to print values related to it for the number of passengers and ticket value that allowed for it to be the max value. I haven't been able to figure out how to print those values.
Loop = "y"
FixedCost = 2500

while Loop == "y":

Input
    MP = int(input("1 of 3 - Enter the minimum number of passengers: "))
    print ("The minimum number of passengers is set to ", MP)

    MaxP = int(input("2 of 3 - Enter the maximum number of passengers: "))
    print ("The minimum number of passengers is set to ", MaxP)

    TP = float(input("3 of 3 - Enter the ticket price: "))

Header for the following print in the for loop
    print ("Number of", end="    ")
    print ("Ticket")
    print ("Passengers", end="   ")
    print ("Price", end="             ")
    print ("Gross", end="              ")
    print ("Fixed Cost", end="          ")
    print ("Profit")

For Loop
    profits = []

    for NP in range(MP, MaxP+1, 10):

        CostofTicket = TP - (((NP - MP)/10)*.5)
        Gross = NP * CostofTicket
        Profit = (NP * CostofTicket) - FixedCost

        profits.append(Profit)

        print (NP, end="          ")
        print ("$", format(CostofTicket, "3,.2f"), end="          ")
        print ("$", format(Gross, "3,.2f"), end="          ")
        print ("$", format(FixedCost, "3,.2f"), end="          ")
        print ("$", format(Profit, "3,.2f"))

Print for max value and related values
    greatest_profit = max(profits)
    print ("Maximum Profit: ", end="")
    print (format(greatest_profit, "3,.2f"))

    print ("Maximum Profit Ticket Price: ")

    print ("Maximum Profit Number of Passengers: ")

    Loop = str(input("Run this contract again (Y or N): "))

A: max (and sorting in general) works with collections such as tuple and list as well as integers. Just build a tuple with Profit as the first item and whatever else you want associated with it, and use that instead of Profit itself.
I wasn't sure which variables from the loop you wanted to keep, so I just winged it...
profits = []

for NP in range(MP, MaxP+1, 10):

    CostofTicket = TP - (((NP - MP)/10)*.5)
    Gross = NP * CostofTicket
    Profit = (NP * CostofTicket) - FixedCost

    profits.append((Profit, TP, NP, MP))

    print (NP, end="          ")
    print ("$", format(CostofTicket, "3,.2f"), end="          ")
    print ("$", format(Gross, "3,.2f"), end="          ")
    print ("$", format(FixedCost, "3,.2f"), end="          ")
    print ("$", format(Profit, "3,.2f"))

# find max profits tuple and unpack its values
Profit, TP, NP, MP = max(profits)
# etc...


text:
Q: Thread Background music in MFC single Document i`m trying to implement a background music loop and do other sounds that wont cut it when I use the "PlaySound" function again.
    void CcpPongView::playBGsound(int num)
{
    //added in the linker to additional name : winmm.lib
    if(num)
        PlaySound(L"sound.wav", NULL, SND_LOOP | SND_ASYNC);
}

void CcpPongView::initGame()
{
    std::thread test (playBGsound, 1);
    test.join();
}

this is the second place I use Playsound
    void Ball::playSound()
{
    switch (rand()%2) {
    case 0:PlaySound(sounds[0], NULL, SND_FILENAME | SND_ASYNC);
        break;
    case 1:PlaySound(sounds[1], NULL, SND_FILENAME | SND_ASYNC);
        break;
}

im not sure where I need to place the thread or how to make a thread in mfc Single Document..
(the "num" was to test)

if there is another way to do it i`m all ears
thanks for the help every one :)

A: Your creation of the std::thread needs to be more like this instead:
std::thread test (&CcpPongView::playBGsound, this, 1);

Note that calling join() on the thread immediately after creating it is a waste of a thread. You may as well just call playBGSound() directly.  If you want to create a thread and let it keep running after the std::thread is destroyed, call detach() instead of join(). Otherwise, don't destroy the std::thread until after the thread has stopped running (ie, store it in a member of your CcpPongView class), in which case you can then use join().
And, you can't play multiple sounds simultaneously with PlaySound() using the SND_ASYNC flag.


text:
Q: What is the name of this "Hopf's theorem"? I am reading Agricola & Friedrich's Global Analysis. On page 85 they prove this corollary of the Stokes' Theorem:
Let $\mathcal{M}$ be a compact, connected, oriented manifold without boundary and assume the function $f:\mathcal{M}\to\mathbb{R}$ satisfies at each point $x$ the condition $\Delta(f)(x)\ge 0$, where $\Delta(f)=div(grad(f))$ is the Laplacian of $f$. Then the function $f$ is constant.
According to this question, it also appears as Exercise 3.12 in Do Carmo's Riemannian Geometry.
The proof is easy by using Green's formulas. What puzzles me is that it is called "Hopf's Theorem", and I am unable to find any other reference that attributes this result to Hopf. Is it an obvious (not for me) corollary from one of the more famous Hopf's theorems? Is it known by any other name?

A: If you replace the compact manifold with a compact domain in $\mathbb R^n$ equipped with a Riemannian metric, the corresponding result is the Hopf Maximum Principle.
I'm not sure if Hopf proved the generalization to compact manifolds. Regardless, the main difficulty in generalizing the proof the maximum principle from the Euclidean Laplacian to the Riemannian Laplacian is dealing with the coefficients of the operator - the topology is not really a problem. Thus it still makes sense (to me, at least) to name this result after Hopf.


text:
Q: CSS / JS slider transition effect I recently came across a slider on this website - https://antoni.de/. I really like the transition effect but I can't for the life of me figure out how it's done. I get how the slider works but its the actual transition that is baffling me. I have no idea what this effect is called and I am not sure if it is done by CSS or JS? Would love to be able to imitate the same sort of transition effect. Does anyone know how this done and can point me in the right direction to building something similar?
This is an image of the transition effect:

A: Its made with canvas HTML5, you can see this in source code.

A: I actually messaged the developer to find out how he made this. It is made using webGL!


text:
Q: How do I predict the future closing price of stock after training and testing? I am trying to do multivariate time series forecasting using linear regression model.
In the below code I first split the data in 80-20 ratio for training and testing.
Then I train the model and use the model to predict using test and compute the relevant performance metrics of the model.
    # Split data into testing and training sets
    X_train, X_test, y_train, y_test = train_test_split(df[['EMA_10']], df[['close']], test_size=.2)

    # Create Regression Model
    model = LinearRegression()
    # Train the model
    model.fit(X_train, y_train)
    # Use model to make predictions
    y_pred = model.predict(X_test)

    # Printout relevant metrics
    print("Model Coefficients:", model.coef_)
    print("Mean Absolute Error:", mean_absolute_error(y_test, y_pred))
    print("Coefficient of Determination:", r2_score(y_test, y_pred))

Now how do I predict the next i.e. future value?

A: To predict unseen y, you can simply use .predict(<new x here>).
However, why are you using linear regression to tackle the time series problem? It makes the data lose the time dimension. It's important to note that when performing time series forecasting, it's generally a good idea to use a model specifically designed for time series data, such as an autoregressive model (e.g., ARIMA) or advanced DL (e.g., RNN). These kinds of models are able to account for the temporal dependencies that are present in time series data, which can help improve the accuracy of the forecasts.
There are many good resources for that, such as,
https://machinelearningmastery.com/arima-for-time-series-forecasting-with-python/
https://towardsdatascience.com/temporal-loops-intro-to-recurrent-neural-networks-for-time-series-forecasting-in-python-b0398963dc1f


text:
Q: CSLogItem timestamp format (NSTimeInterval since when?) I'm logging CMAccelerometerData on the iphone. CMAcceleration is a subclass of CMLogItem, which defines a timestamp. The timestamp is very important to me, as I have to match CMAcceleration data to positions obtain via GPS. GPS gives me a NSDate object, which is good; but CMLogItem gives me a number that I cant relate to anything.
It's not UNIX time for sure. This morning (17/11/2010 at 11H17am, in Australia), it was at 4090 seconds.
Any ideas of what that could be?

A: Nevermind I found out, CMLogItem timestamp is a NSTimeInterval starting when the phone last boot up.


text:
Q: PHP Fatal error: Cannot declare class CreateUsersTable, because the name is already in use When I run this command in my terminal, It throws this error.
Actually I had a product table but I deleted it. Then why it is not allowing me to create product table?
$ php artisan make:migration create_products_table

PHP Fatal error:  Cannot declare class CreateUsersTable, because the
name is already in use in
C:\xampp\htdocs\bizzcomputer\database\migrations\2020_08_26_063223_create_users_table.php
on line 37
Symfony\Component\ErrorHandler\Error\FatalError
Cannot declare class CreateUsersTable, because the name is already
in use
at
C:\xampp\htdocs\bizzcomputer\database\migrations\2020_08_26_063223_create_users_table.php:37
33|     public function down()
34|     {
35|         Schema::dropIfExists('users');
36|     }

37| }
38|
39|
40|
41|

Whoops\Exception\ErrorException
Cannot declare class CreateUsersTable, because the name is already
in use
at
C:\xampp\htdocs\bizzcomputer\database\migrations\2020_08_26_063223_create_users_table.php:37
public function down()
34|     {
35|         Schema::dropIfExists('users');
36|     }
37| }
38|
39|
40|
41|
1
C:\xampp\htdocs\bizzcomputer\vendor\filp\whoops\src\Whoops\Run.php:408
Whoops\Run::handleError("Cannot declare class CreateUsersTable, because the name is already in use",
"C:\xampp\htdocs\bizzcomputer\database\migrations\2020_08_26_063223_create_users_table.php")
2   [internal]:0
Whoops\Run::handleShutdown()


text:
Q: Is there any reason to use paracontrolled calculus over regularity structures? Paracontrolled calculus was developed by Gubinelli, Imkeller and Perkowski as a way of treating singular stochastic PDEs such as KPZ, $\Phi_3^4$ or PAM, around the same time regularity structures were introduced by Hairer.
Regularity structures are now the standard treatment of singular stochastic PDEs although I have been reading that there are perhaps potentional benefits to paracontrolled calculus. This paper for example says:

We develop in this work a general version of paracontrolled calculus that allows to treat analytically within this paradigm some singular partial differential equations with the same efficiency as regularity structures, with the benefit that there is no need to introduce the algebraic apparatus inherent to the latter theory.

I'm not sure that this is such a large benefit. Is this the only reason to work with paracontrolled calculus, or are there other benefits? Is there anything you can do in paracontrolled calculus that you can't in regularity structures?

A: I don't think that the reason given in the paper by Bailleul and Bernicot is a good one. Basically, they treat an example which is simple enough so that it is still manageable to describe the various bits and pieces needed to control their solutions "by hand" instead of combining them into a single object in a more coherent way.
This being said, there are certainly situations in which paracontrolled calculus is more efficient than regularity structures thanks to the fact that it provides a more "global" decomposition of the solution. (Think of Fourier decomposition vs Taylor expansion.) For example, it is not clear how one would implement the strategy of proof for the result of this article by Weber and Mourrat in the framework of regularity structures. It also has the advantage of relying solely on concepts that are quite well-known and have been used in other context for a long time, which makes it possible to reuse more existing results. (For example it makes use of classical function spaces, so that embedding theorems and functional inequalities can just be taken "off the shelf". In the theory of regularity structures there are analogues of most function spaces that share many properties with their classical counterparts, but this always has to be proven first...)


text:
Q: Cannot detect faces using MLKit I am using MLKit to try and find the faces within a photo & every time the vision image comes back void of faces.
This is the code I am using currently
  //instantiate MLVision
  lazy var vision = Vision.vision().faceDetector(options: faceDetectionOptions())

 func faceDetectionOptions() -> VisionFaceDetectorOptions {
    let options = VisionFaceDetectorOptions()
    options.performanceMode = .accurate
    options.landmarkMode = .all
    options.classificationMode = .all
    options.minFaceSize = CGFloat(0.1)
    options.isTrackingEnabled = false
    return options
}

then I save the image & within this I process UIImage
func saveImage() {

    let visionImage = VisionImage(image: self.canvasView!.asImage())

    // begin scanning image or video

    self.vision.process(visionImage, completion: { (faces, error) in
        //no faces were detected
        var detectedFaces = [VisionFace]()
        var isSmiling = false
        var smilingFaces = [Bool]()

        guard error == nil, let faces = faces, !faces.isEmpty else {

            return
        }

        for face in faces {

            if face.hasSmilingProbability {
                if face.smilingProbability < 0.3 {
                    isSmiling = false
                } else {
                    isSmiling = true
                }
            }
            //add smiling faces to array
            if isSmiling == true {
                smilingFaces.append(isSmiling)
            }

            //add face to faces array
            detectedFaces.append(face)
        }

        self.contentScore.detectedFaces = detectedFaces.count
        self.contentScore.smilingFaces = smilingFaces.count
       // contentScore.eventAttendees = objEvent.event_users!.count

    })

    photoEditorDelegate?.imageEdited(image: canvasView!.asImage())

    player?.pause()

    self.dismiss(animated: true, completion: nil)

}

Here is the function that converts the UIView to an image
 extension UIView {

// Using a function since `var image` might conflict with an existing variable
// (like on `UIImageView`)
func asImage() -> UIImage {
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { rendererContext in
        layer.render(in: rendererContext.cgContext)
    }
}

Any help would be much appreciated


text:
Q: Evaluating $\lim_{x\to1}{\frac{\sqrt{x^2+3}-2}{\sqrt{x^2+8}-3}}$ without L'Hospital's Theorem I've been trying to evaluate$$\lim_{x\to1}{\frac{\sqrt{x^2+3}-2}{\sqrt{x^2+8}-3}}$$
I tried:
(a) Rationizing the numerator -> Error
(b) Rationizing the denominator -> Error
(c) Factoring out $x$ -> Error

Finally, I used L'Hospital's Rule and got the answer $3/2$, but that is not what I am supposed to do, for not a single word about this Theorem was mentioned during my lectures.
Is there any other way to solve this limit without this Theorem?

A: Notice, $$\lim_{x\to 1}\frac{\sqrt{x^2+3}-2}{\sqrt{x^2+8}-3}$$
$$=\lim_{x\to 1}\frac{(\sqrt{x^2+3}-2)(\sqrt{x^2+3}+2)}{(\sqrt{x^2+8}-3)(\sqrt{x^2+8}+3)}\cdot \frac{(\sqrt{x^2+8}+3)}{(\sqrt{x^2+3}+2)}$$
$$=\lim_{x\to 1}\frac{x^2+3-4}{x^2+8-9}\cdot \frac{(\sqrt{x^2+8}+3)}{(\sqrt{x^2+3}+2)}$$
$$=\lim_{x\to 1}\frac{(x^2-1)}{(x^2-1)}\cdot \frac{(\sqrt{x^2+8}+3)}{(\sqrt{x^2+3}+2)}$$
$$=\lim_{x\to 1}\frac{\sqrt{x^2+8}+3}{\sqrt{x^2+3}+2}$$
$$=\frac{3+3}{2+2}=\color{red}{\frac{3}{2}}$$

A: Rationalize the denominator.I.e multiply the numerator and the denominator by $\sqrt{x^2+8}+3$...

A: Rationalise both numr and denr
$$\frac{x^2+3-4}{x^2 + 8 -9}\times\frac{\sqrt{x^2+8}+3}{\sqrt{x^2+3}+2}$$
apply limit
$$\lim_{x\to1}\frac{\sqrt{x^2+8}+3}{\sqrt{x^2+3}+2} = \frac{3}{2}$$

A: \begin{align*}
\lim_{x\to1}\frac{\sqrt{x^2+3}-2}{\sqrt{x^2+8}-3}
&=\lim_{x\to1}\frac{(\sqrt{x^2+3}-2)(\sqrt{x^2+3}+2)}{(\sqrt{x^2+8}-3)(\sqrt{x^2+8}+3)}\cdot\frac{\sqrt{x^2+8}+3}{\sqrt{x^2+3}+2}\\
&=\lim_{x\to1}\frac{x^2-1}{x^2-1}\cdot\frac{\sqrt{x^2+8}+3}{\sqrt{x^2+3}+2}\\
&=\frac32
\end{align*}
using $(a-b)(a+b)=a^2-b^2$.

A: Hint:
$$\begin{align}
\lim_{x\to1}{\frac{\sqrt{x^2+3}-2}{\sqrt{x^2+8}-3}}&=\lim_{x\to1}\frac{\sqrt{x^2+3}-2}{x-1}\frac{x-1}{\sqrt{x^2+8}-3}\\&=\lim_{x\to1}\frac{\sqrt{x^2+3}-2}{x-1}\left(\frac{\sqrt{x^2+8}-3}{x-1}\right)^{-1}.
\end{align}$$
Notice that it would be sufficient to calculate two derivatives at $x=1$ to evaluate the limit.

A: Here is a same solution:How can I evaluate $\lim_{x\to1}\frac{\sqrt{5-x}-2}{\sqrt{2-x}-1}$ without invoking l'Hôpital's rule?
$\lim_{x\to1}{\frac{\sqrt{x^2+3}-2}{\sqrt{x^2+8}-3} * \frac{\sqrt{x^2+8}+3}{\sqrt{x^2+8}+3}} = lim_{x\to1}{\frac{(\sqrt{x^2+3}-2 )* (\sqrt{x^2+8}+3)}{x^2-1}} = lim_{x\to1}{\frac{(\sqrt{x^2+3}-2 )* (\sqrt{x^2+8}+3)}{x^2-1}*\frac{\sqrt{x^2+3}+2}{\sqrt{x^2+3}+2}} = lim_{x\to1}{\frac{(x^2-1 )* (\sqrt{x^2+8}+3)}{x^2-1}*\frac{1}{\sqrt{x^2+3}+2}} = = lim_{x\to1}{\frac{\sqrt{x^2+8}+3}{\sqrt{x^2+3}+2}} = \frac{\sqrt{1^2+8}+3}{\sqrt{1^2+3}+2} = \frac{6}{4} = \frac{3}{2}$

A: $$\lim_\limits{x\to1} \frac{\sqrt{x^2+3}-2}{\sqrt{x^2+8}-3}$$
$$=\lim_\limits{x\to1} \left[\frac{\frac{\sqrt{x^2+3}-2}{x^2-1}}{\frac{\sqrt{x^2+8}-3}{x^2-1}}\right]$$
$$=\lim_\limits{x\to1} \left[\frac{\frac{\sqrt{x^2+3}-2}{x^2+3-2}}{\frac{\sqrt{x^2+8}-3}{x^2+8-9}}\right]$$
$$=\frac{\lim_\limits{x^2+3\to4} \frac{\sqrt{x^2+3}-\sqrt4}{(x^2+3)-4}}{\lim_\limits{x^2+8\to9} \frac{\sqrt{x^2+8}-\sqrt9}{(x^2+8)-9}}$$
$$=\frac{\frac{1}{2}4^{\frac{1}{2}-1}}{\frac{1}{2}9^{\frac{1}{2}-1}}$$
$$=\frac{\frac{1}{4}}{\frac{1}{6}}$$
$$=\frac{3}{2}$$


text:
Q: How Sort Array Date JavaScript dd/mm/yyyy? How would I sort an array of dates in chronological order?  For example I have:
var dates = [
    '03/03/2014',
    '01/03/2014',
    '02/03/2014',
    '04/03/2014'
];

sortDates = sortDate(dates);

sortDate(array){
    // ?
    returnt arraySort;
}

I'd like the resultant array to look like:
[
    '01/03/2014',
    '02/03/2014',
    '03/03/2014',
    '04/03/2014'
]

A: Try this (feel free to ask for details) :
dates.sort(function (a, b) {
    // '01/03/2014'.split('/')
    // gives ["01", "03", "2014"]
    a = a.split('/');
    b = b.split('/');
    return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
});

Translation of the last line :
return          return
a[2] - b[2]     years comparison if year A - year B is not 0
||              or
a[1] - b[1]     months comparison if month A - month B is not 0
||              or
a[0] - b[0];    days comparison

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.

A: Assuming your date format is consistently DD/MM/YYYY:
dates.sort(function(a, b){
    var aa = a.split('/').reverse().join(),
        bb = b.split('/').reverse().join();
    return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

... otherwise you will have to compare Date objects if you require more flexibility.

A: Please do this the easy way.
Works for dates formatted as 'dd/mm/yy' or 'dd/mm/yyyy'.
var dates = [
    '03/03/2014',
    '01/03/2014',
    '02/03/2014',
    '04/03/2014'
];

dates.sort( function(c,d){
    var rx = /(\d+)\/(\d+)\/(\d+)/;
    var a = Number(c.replace(rx, '$3$1$20000'));
    var b = Number(d.replace(rx, '$3$1$20000'));
    return a > b ? -1 : a == b ? 0 : 1; // for newer on top
    //return a < b ? -1 : a == b ? 0 : 1; // for older on top
  });

A: Just improving @leaf answer as split works on strings so you might get error if the type of 'a' and 'b' is object.
dates.sort(function (a, b) {
        a = a.toString().split('/');
        b = b.toString().split('/');
        return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
    });

A: Digigizmo answer works!
in case: dd/mm/yyyy hh:mm:ss
you can use:
list.sort(function (a, b) {
    var aa = a.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', a.substring(11, 20)),
    bb = b.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', b.substring(11, 20));
    return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

and replaceAll function:
function replaceAll(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

A: let arrayDate = ["11/12/2022", "10/11/2021", "20/01/2001", "30/10/2022"];function formatFrToEn(arg){
let [day, month, year] = arg.split("/");
let newFormatDate = [month, day, year].join("/");
return newFormatDate;}let newArrayDate = arrayDate.map( x => new Date( formatFrToEn(x) ) )console.log(newArrayDate)newArrayDate = newArrayDate.sort( (a, b) => Number(a) - Number(b) )function padTo2Digits(num) {
return num.toString().padStart(2, '0');}function formatDate(date){return[padTo2Digits(date.getDate()),padTo2Digits(date.getMonth() + 1), date.getFullYear(),.join('/');newArrayDate = newArrayDate.map(x=>formatDate(x))console.log(newArrayDate)

A: dates.sort((a, b) => new Date(a).getTime() - new Date(b).getTime())

If you don't want to sort the elements of an array in place, you can try this code
dates.slice().sort((a, b) => new Date(a).getTime() - new Date(b).getTime())


text:
Q: C++ determine if a container has ::find() I have a functor which operates on a container of type U of elements of type T like so
template<typename T, template<typename...> class U>
class asserter
{
public:
    asserter(U<T> &c) : container(c) { };
    void operator()(T lhs)
    {
        CU_ASSERT(container.find(lhs) != container.end());
    };
private:
    U<T>    &container;
};

which I might use as
std::set<std::string> a, c;
...
asserter<std::string, std::set> ass(c);
for_each(a.begin(), a.end(), ass);

Where we are ignoring std::includes() for the moment.
This works great if the container is one where U::find() is defined. If it's not I'd like to fall back to std::find(). On the other hand I'd rather use U::find() over std::find() if it's available.
In C++11 (or 17 if necessary) can I determine if U::find() is available (possibly restricting to the STL) for U and if so use it, otherwise use std::find()?

A: SFINAE on whether the expression c.find(value) is well-formed. Trailing return type is C++11, and not essential here anyway; it just makes the return type easier to write - decltype(c.find(value)) instead of decltype(std::declval<Container&>().find(std::declval<const T&>())).
If the expression would be ill-formed, the first overload of find_impl is removed from the overload set, leaving the second overload as the only viable one. The usual int/long/0 trick for the third parameter makes the first overload preferred when both are viable.
template<class Container, class T>
auto find_impl(Container& c, const T& value, int) -> decltype(c.find(value)){
    return c.find(value);
}

template<class Container, class T>
auto find_impl(Container& c, const T& value, long) -> decltype(std::begin(c)){
    return std::find(std::begin(c), std::end(c), value);
}

template<class Container, class T>
auto find(Container& c, const T& value) -> decltype(find_impl(c, value, 0)) {
    return find_impl(c, value, 0);
}

The usual disclaimer applies: this relies on expression SFINAE, which is not currently supported by MSVC; Microsoft does plan to add support in an update to MSVC 2015.


text:
Q: Jquery validation fails on dynamically added rows I am using jquery validation plugin and it is not applied on dynically added rows
my code is:
Html:
<form action="test.php" onsubmit="return false;">

            <input type="text" required="required" name="qty[]" />

            <textarea required="required" name="test[]" rows='4' cols='15'></textarea>

    <button>Add</button>
</form>

Script:
var frm=$('form').validate({
    submitHandler: function(form) {
        // do other stuff for a valid form
        alert('form submitted');
        return false;
    }
});

$('button').on('click',function(){
    $clone=$('.new-row:first').clone();
    $clone.find('input,textarea').val('');
    $clone.insertAfter($('.new-row:last'));
    $clone.find('input,textarea').rules('add',{required:true});
    $('.new-row:last').find('input,textarea').rules('add',{required:true});
});

Fiddle
Another issue, I have tried it on my system and I got error like : TypeError: e is null
for the line $clone.find('input,textarea').rules('add',{required:true}); if I remove then error not comes,
but this error is not seen in fiddle

A: Try this, i think this is what you wanted
Added unique name to the textarea and input.
var incr = 0;
$('button').on('click',function(){
    incr++;
    $clone=$('.new-row:first').clone();
    $clone.find('input,textarea').val('');
    $clone.find('input').attr('name','qty'+incr+'[]');
    $clone.find('textarea').attr('name','test'+incr+'[]');

Demo  here


text:
Q: Class instance fails isinstance check Hi

I have some code on my CI failing (local runs do not fail).
The problem is that class instance fails isinstance() check.
Code:
File: main.py
class MyController(SuperController):
    # Overrides default definition of get_variables_context()
    from my_options import get_variables_context

File: my_options.py
...
def get_variables_context(self: SuperController, **kwargs):
    from main import MyController
    self: MyController

    print(f"type(self) is {type(self)} (it {'IS' if (isinstance(self, MyController)) else 'IS NOT'} a subclass of MyController)")
    _super = super(MyController, self).get_variables_context(**kwargs) or dict()
    _super.update(result)
    return _super

Got output and error:
type(self) is <class '__main__.SomeController'> (it IS NOT a subclass of SomeController
Traceback (most recent call last):
  File "main.py", line 24, in <module>
    SomeController.main(**params)
  File "/builds/RND/my/rcv-nginx/tests/nginx_tests/flow.py", line 391, in main
    _tests_suite, _, _ = self.prepare()
  File "/builds/RND/my/rcv-nginx/tests/nginx_tests/flow.py", line 359, in prepare
    context['variables_context'] = self.get_variables_context(**context)
  File "/builds/RND/my/tests/integration/my_options.py", line 81, in get_variables_context
    _super = super(SomeController, self).get_variables_context(**kwargs) or dict()
TypeError: super(type, obj): obj must be an instance or subtype of type

A: I've found the solution while investigating the root cause.
In the local run, ...
I actually call the python unittest which then calls main.py which then creates a class MyController which then calls my_options.py, and the class is added to the loaded module 'main'.
Then, MyController.get_variables_context asks for the module 'main', which is already loaded, then for the class MyController in that module, so the same type instance is returned and type check succeeds.
In the CI run, ...
I call directly main.py with the argument "test" (which should create a controller and run all tests from it via unittest), so the class MyController is created inside module __main__. MyController.get_variables_context still asks for the MyController class in main.py, but the module 'main' is not loaded here, so python loads it, creates new class MyController, and then returns it.
So, basically the answer is ...
to move MyController from main.py to the other file, i.e. controller.py


text:
Q: is it possible to set jpeg(or png) types of images to exe(C++)? Now I'm writing an open source project(C++/MFC) and find a beautiful image which is Jpeg type, in Windows API it's easy to change icon with function: SetIcon, but I don't want to convert my jpeg file into icon type.
My question: is there a way to set an application's icon using a .jpeg file?

A: This should do the trick for you:
Bitmap* icon = new Bitmap("myfile.jpg", TRUE);
HICON hIcon;
icon->GetHICON(&hIcon);
SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);

This is of course ignoring error checking, which you might want to add, but otherwise I think this should work. According to Microsoft this should support the following formats: BMP, GIF, JPEG, PNG, TIFF, Exif, WMF, and EMF.


text:
Q: Python iterating over a list in parallel? I have a list created with no more than 8 items in it, right now I loop over the item with a standard for loop "for item in list:" I am wondering if there is a way to check all of the elements at the exact same time? I have seen some posts about using zip to iterate over 2 lists at the same time which could help.
If there is no way to iterate over a lists elements at the same time I would guess I need to split one single list into 4 separate lists and iterate 2 at the same time using zip and do the other 2 on a separate thread, that seems like it could be a clunky fix though.
Any help would be appreciated.
Edit
Sorry to be vague, I have a list
apples = ['green', 'green', 'green', 'red']

right now I use a for loop to go over each element,
for apple in apples:
    checkAppleColour(apple)
    #Do some more stuff depending on colour....

right now it loops over each element in apple one by one, what I would like to be able to do is check each of the items at the exact same time for a colour check as every millisecond counts (example code used, but principle is exactly the same for what I am trying to achieve).
Performance is key here I don't mind if its threading I have to use, but I need maximum speed / efficiency for checking each element and my guess is parallelism is the way to do it, I am just not quite sure how.

A: If you can map a function onto the list, parallelism is easy.
def addOne (x):
    return x + 1

The default map does things on one thread.
map(addOne, range(1, 4)) #When iterated over produces [2, 3, 4]

If your problem is a map, it means that it's trivially parallel.
from multiprocessing import Pool

pool = Pool()
pool.map(addOne, range(1, 4)) ##When iterated over produces [2, 3, 4]

This uses multiple processes. multiprocessing.dummy.Pool is a thread pool. See this article for a great introduction to the rationale behind both.


text:
Q: How defects can influence the electrical conductivity of ionic insulator, semiconductor and metals? Does increasing defects increase the conductivity of the insulator?
The band gap between the conduction band and valence band is large such that electrons cannot flow in-between. Shouldn't increasing the number of defects have no effect on electrical conductivity?
Metal decreases conductivity as defects are a source of resistance.