text:
Q: Base64 Svg to UIImage return nil I'm trying to convert Base64 Svg to UIImage, but I get nil.
Everything is OK on this site https://codebeautify.org/base64-to-image-converter
I try different frameworks on native methods, but all to no avail
I use:

*

*
let dataDecoded : Data = Data(base64Encoded: base64Str, options: .ignoreUnknownCharacters)!
polygonImage.image = UIImage(data: dataDecoded)!

2) ```
   if let url = URL(string: base64StrUrl) {
      if let data = try? Data(contentsOf: url) {
         polygonImage.image = UIImage(data: data)
      }
   }

*
let anSVGImage: SVGKImage = SVGKImage(data: data)
self.polygonImage.image = anSVGImage

Problematic base64:
data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIGhlaWdodD0nMTAwJyB3aWR0aD0nMTAwJyB2aWV3Qm94PSc5MC42NDM5NTE0MTYwMTU2MiAxNTIuMDAzOTg4NjQ3NDYwOTQgMC4wMTE2NDI0NTYwNTQ2ODc1IDAuMDExMzg2MTA4Mzk4NDM3NScgc3R5bGU9J3RyYW5zZm9ybTogc2NhbGVYKC0xKSByb3RhdGUoOTBkZWcpJz48ZyBmaWxsPSdub25lJz48cG9seWdvbiBwb2ludHM9JzkwLjY0Nzc1MDg1NDQ5MjE5LDE1Mi4wMDU2MTUyMzQzNzUgOTAuNjQ1NjE0NjI0MDIzNDQsMTUyLjAwODg5NTg3NDAyMzQ0IDkwLjY0NjYyMTcwNDEwMTU2LDE1Mi4wMTI5Njk5NzA3MDMxMiA5MC42NTI3ODYyNTQ4ODI4MSwxNTIuMDEzNzQ4MTY4OTQ1MyA5MC42NTM5MzA2NjQwNjI1LDE1Mi4wMDY2Mzc1NzMyNDIyICcgc3R5bGU9J2ZpbGw6I0ZGN0EwMDsgZmlsbC1vcGFjaXR5OjAuMjU7IHN0cm9rZTogI0ZGN0EwMDsnIHN0cm9rZS13aWR0aD0nMC4wMDAyMzI4NDkxMjEwOTM3NScgLz48L2c+PC9zdmc+

A: I'm pretty sure it's not a valid base64 string.
The link you have given has used some image processing techniques to generate the image, but in swift you have to provide a valid base64 string and if you download the image from the same website then you cannot open that image.
you can validate your base64 string on https://base64.guru/tools/validator
if you want to convert this base64 to image

*

*paste your base64 string in this website and download .svg file (because you can't get a image file from base64 directly)

*convert your .svg file .png or .jpg with https://svgtopng.com

*convert .png or .jpg file to base64 string with https://www.base64encoder.io/image-to-base64-converter/
then use that base64 string you will definitely get image.


text:
Q: How to make a variable that changes depending on user input in batch I am trying to make something just random for fun, so this is what  i have:
:login
echo Please login.
set /p x=Username:
if %x% == example.user goto home
if not %x% == example.user goto login

:home
echo Welcome 'example.user'!

I want it to change to example.user or whatever the user logs in as, so how would I do that? I don't know how to do that in batch. All code and help are amazing. Thank you all sooooo much.

A: This should work.
:login
echo Please login.
set /p x=Username:
if "%x%" == "%USERNAME%" (goto home)
if not "%x%" == "%USERNAME%" (goto login)

:home
echo Welcome %x%!

redpajama_set_name: RedPajamaStackExchange


text:
Q: SSH.NET SSH Private Key File Lock issue with Multiple Threads I am using SSH.NET to SFTP files from one server to another. I'm using C# .NET 4.5 MVC 4. It works great except in the case where there are multiple requests trying to upload files, at which point I get an error that the SSH private key is currently being used by another process. I would assume that one request sets up the ConnectionInfo object which reads from the private key file, while another request is trying to do the same thing before the first request is done reading from that file.
Any help?
Notice in the code below that I've added "test" to all string obj values. In production this is not the case.
Thanks!
public class SftpService : ISftpService
{
  private static ConnectionInfo _sftpConnectionInfo { get; set; }
  private static readonly string _mediaServerHost = "test";
  private static readonly string _mediaServerUsername = "test";
  private static readonly int _mediaServerPort = 22;
  private static readonly string _privateSshKeyLocation = "test";
  private static readonly string _privateSshKeyPhrase = "test";
  private static readonly string _mediaServerUploadRootLocation = "test";

    public SftpService()
    {

        var authenticationMethod =  new PrivateKeyAuthenticationMethod(_mediaServerUsername, new PrivateKeyFile[]{
                new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)
        });

    // Setup Credentials and Server Information
    _sftpConnectionInfo = new ConnectionInfo(_mediaServerHost, _mediaServerPort, _mediaServerUsername,
        authenticationMethod
    );

  }

  public void UploadResource(Stream fileStream)
  {
    using (var sftp = new SftpClient(_sftpConnectionInfo))
    {
        sftp.Connect();

        //this is not the real path, just showing example
        var path = "abc.txt";

        sftp.UploadFile(fileStream, path, true);

        sftp.Disconnect();
    }
  }
}

A: In short: Your assumptions are correct. Problem is in lock and access to the shared resource.
new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)

You may go ahead and lock the shared resource to resolve this issue with minimal code change. A potential start point would be  SftpService().
Go ahead and create lock on a parent class and wrap content of shared resources with the lock:
 private static object _lock = new object();

 public SftpService()
    {

     lock (_lock)
                {
                   // shared resources
                }
    }


text:
Q: Why is this jquery extension not working? I have this extension function and it seems to be not causing any problems. But as soon as I try to use it, I get an error message: Object doesn't support property or method 'n2name'

No errors are reported in the plug-in code (snippet pasted below for reference, with a link to the full file at the end).
Does anyone have any idea why this isn't working?
Note: I'm trying to fix an issue on this open-source project: https://github.com/n2cms/n2cms/issues/279 and there may be more useful details on that Github bug.
Sorry if this question is too vague, and for the long code snippet (most of it probably isn't relevant). But any help would really be appreciated
/**
* n2name 0.2
*/

(function($) {

    /* some code removed for brevity */

    $.fn.n2name = function(options) {
        var invokeUpdateName = function(){
            updateName(options.titleId, options.nameId, options.whitespaceReplacement, options.toLower, options.replacements, options.keepUpdatedBoxId);
        };
        if(options.keepUpdatedBoxId){
           /* more code removed for brevity */
        }
    };
})(jQuery);;

Link to jquery.n2name.js full source, if the code snippet above is not useful: https://github.com/n2cms/n2cms/blob/4469580fcdd9c91f7576f07c3d2c8a4479ed6ce9/src/Mvc/MvcTemplates/N2/Resources/Js/plugins/jquery.n2name.js

A: The errors "Object doesn't support property or method <name>" (IE) and "<name> is not a function" (Chrome) usually mean that your jQuery plugin didn't successfully load before it was called.
This can be due to a failed request (check Dev Tools' Network tab), forgetting/misplacing the plugin's script tag or the script tag having defer/async attributes. Another possible cause is the plugin's script containing syntax errors (check the Dev Tools' Console tab in that case).
Having multiple versions of jQuery in the same page (as commented in OP's linked GH issue) is another possibility, seeing as plugins wrapped in the (function(){}(jQuery)); boilerplate are only added to the jQuery object referenced by window.jQuery at the time the plugin script loads.

In this specific case, OP was having issues to load the plugin from localhost inside VS.
I've seen similar issues, and I'll just add that it is invalid to use protocol-less URLs (for example: //somecdn.com/library.js) when loading files from a file:/// URI scheme. This is because protocol-less URLs "inherit" the protocol being used from the parent document and file:/// is not a protocol. In case you're loading it from a local server (e.g. parent document served through http as in http://localhost/library.js) the protocol-less URLs should work fine.


text:
Q: I upgraded pyOpenSSL but it is still 0.13.1 version. Unable to upgrade to 18.0.0 I am trying to get pyOpenSSL 18.0.0 but it doesn't work. Here are my commands:
sudo pip install pyOpenSSL==18.0.0

I get this:
The directory '/Users/mac/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/mac/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: pyOpenSSL==18.0.0 in ./Library/Python/2.7/lib/python/site-packages (18.0.0)
Requirement already satisfied: six>=1.5.2 in /Library/Python/2.7/site-packages (from pyOpenSSL==18.0.0) (1.11.0)
Requirement already satisfied: cryptography>=2.2.1 in ./Library/Python/2.7/lib/python/site-packages (from pyOpenSSL==18.0.0) (2.4.2)
Requirement already satisfied: idna>=2.1 in /Library/Python/2.7/site-packages (from cryptography>=2.2.1->pyOpenSSL==18.0.0) (2.7)
Requirement already satisfied: enum34; python_version < "3" in ./Library/Python/2.7/lib/python/site-packages (from cryptography>=2.2.1->pyOpenSSL==18.0.0) (1.1.6)
Requirement already satisfied: cffi!=1.11.3,>=1.7 in ./Library/Python/2.7/lib/python/site-packages (from cryptography>=2.2.1->pyOpenSSL==18.0.0) (1.11.5)
Requirement already satisfied: asn1crypto>=0.21.0 in ./Library/Python/2.7/lib/python/site-packages (from cryptography>=2.2.1->pyOpenSSL==18.0.0) (0.24.0)
Requirement already satisfied: ipaddress; python_version < "3" in ./Library/Python/2.7/lib/python/site-packages (from cryptography>=2.2.1->pyOpenSSL==18.0.0) (1.0.22)
Requirement already satisfied: pycparser in ./Library/Python/2.7/lib/python/site-packages (from cffi!=1.11.3,>=1.7->cryptography>=2.2.1->pyOpenSSL==18.0.0) (2.19)

Looks like pyOpenSSL is already installed. But then I check:
pip list

And I get:
pyOpenSSL    0.13.1

A: The sudo command might be making pip install that version of pyopenssl to the site-packages of the root user. Simply running pip install pyOpenSSL==18.0.0 (outside of a virtual environment) should install it in the site-packages of the current user.
As an aside, you should consider using virtual environments for better dependency management of your python project. For that, please reference {this answer}.


text:
Q: PlotPoints does not work properly in ParametricPlot3D I want to get surface with "bad" quality, so I decrease number of sample points in both parameters:
g = ParametricPlot3D[
   {R Cos[ϕ], R Sin[ϕ], z}
   , {ϕ, 0, 2 π}
   , {z, 0, 1}
   , PlotPoints -> {3, 2}
   , MaxRecursion -> 0
   , PlotRange -> All
]

but g is build of much more points than I expected:
Length@g[[1, 1]]
gives
321
In 2-dim case, it works as I expect:
g = ParametricPlot3D[
{R Cos[ϕ], R Sin[ϕ], 1}
  , {ϕ, 0, 2 π}
  , PlotPoints -> 5
  , MaxRecursion -> 0
]

and
g[[1, 1, 3, 3]]
is a line made of 5 points:
Line[
  {
    {0.4, 6.28319*10^-7, 1.},
    {0.0239846, 0.39928, 1.},
    {-0.39999, -0.00283338, 1.},
    {-0.0137472, -0.399764, 1.},
    {0.4, -6.28319*10^-7, 1.}
  }
]

Mathematica v.10.2

A: The plot corresponding to the first block of code in the question is, with R = 1 for specificity,
g = ParametricPlot3D[{Cos[ϕ], Sin[ϕ], z}, {ϕ, 0, 2 π}, {z, 0, 1},
    PlotPoints -> {3, 2}, MaxRecursion -> 0, PlotRange -> All]

Either by examining
g // Normal // InputForm

or simply by counting mesh lines, we see that the default mesh is given for this plot by Mesh -> 15.  Such a detailed mesh cannot be determined accurately by PlotPoints -> {3, 2}, so Mathematica computes more points.  To illustrate this behavior, generate plots for various numbers of mesh lines:
GraphicsGrid[Partition[Table[
    ParametricPlot3D[{Cos[ϕ], Sin[ϕ], z}, {ϕ, 0, 2 π}, {z, 0, 1},
        PlotPoints -> {3, 2}, MaxRecursion -> 0, PlotRange -> All,
        Mesh -> n, PlotLabel -> n],
{n, 0, 8}], 3], ImageSize -> Large]

The question requests a surface with "bad" quality.  Plots in the first row of the grid above probably qualify.  (By the way, the shading of the n = 0 plot above does not match what Mathematica actually produced, which is shading with a uniform gradient.)


text:
Q: How can I get my form to remember what values have been "unchecked?" I have a form with checkboxes of student names that is displayed on a class detail page. If you submit the form, it allows you to assign students to the class.
If you revisit the page, it remembers which students have been assigned to the class, and automatically checks their corresponding boxes. The form allows you to check additional students and submit the form, and they will added to the class.
What I'm having trouble with is actually removing students from the class. Specifically, how can I track which students have been "unchecked" on the class detail page, and pass them on to the form action page, where I can then loop an SQL DELETE statement over them?
Here is the code that I have been toying with:
$class_id = $_GET['class_id'];
$tid = $_POST['teachers'];
$student_count = $_GET['student_count'];

mysqli_query($db,"UPDATE class SET teacher_id = $tid WHERE id=$class_id");

if (isset($_POST['students'])) {
    $students = $_POST['students'];
    foreach ($students as $student_id) {
        if (count($students) < $student_count) {
            foreach (/*student that was unchecked from the class.php form*/) {
                //delete statement
            }
            break;
        } else {
            mysqli_query($db, "UPDATE student_class SET student_id = $student_id WHERE class_id = $class_id");
            mysqli_query($db,"INSERT INTO student_class (student_id, class_id) VALUES ($student_id, $class_id)");
        }
    }
}

A: A Checkbox does not produce an entry in the $_POST or $_GET Array, when you uncheck it.
but you can simply remove every entry from the database, that is not checked any more.
(cause then it has to be unchecked if your form contains a complete enumeration!)
$checkedStudents = array()

//Exemplary: depends on the format of $students. If just an id-array, this can be skipped.
foreach ($students as $student_id) {
   $checkedStudents[] = $student_id;
}

$inStr = "(" + implode(",",$checkedStudents) + ")";
$query = "DELETE FROM student_class WHERE class_id = $class_id
          AND student_id NOT IN ".$inStr;


text:
Q: Whats the fastest way to load a custom font via Css Which is the fastest way to load the CSS
By using a link ref in the header or by using an @import in the CSS file.
e.g.
<link rel='stylesheet' type='text/css' href='//fonts.googleapis.com/css?family=Gudea:400,700'>

Or
@import url("//fonts.googleapis.com/css?family=Gudea:400,700");

I have run some speed tests but nothing is conclusive.
But including the link this file is seen as render blocking, so even though the link separate file should be faster I can't find out if it actually is..

A: Including a CSS file via HTML link tag should give faster results, as the browser can load the font file even before having loaded the CSS file. In theory the browser should load both files parallel. You can invesatigate this using the brwoser developer tools network tab.


text:
Q: IIS website opening outside of server, but not internally I have multiple sites hosted within an IIS server. Let me give you an example like:
demo.trial.com and demo.web.com
Under both these websites, I have created multiple pages like
trial1 under demo.trial.com and page1 under demo.web.com
The intention is that I should be able to browse demo.trial.com/trial1 and demo.web.com/page1. And I am able to do both these from my laptop.
The problem is that I am able to browse demo.trial.com/trial1 within the server without any issues, but browsing demo.web.com/page1 within the server shows me page cant be displayed. The bindings as well as other settings are same in both the websites, but not sure why demo.web.com/page1 is not opening within the server, but opens outside the server.
Any help would really be appreciated.

A: My first guess is that the server (and it's browser) are unaware that demo.web.com is hosted locally. My recommendation would be to add the following record to the c:\windows\system32\drivers\etc\hosts file:
127.0.0.1  demo.web.com


text:
Q: GCC startup code _start does not end in main() I could only find bits and pieces of information on the symbol _start, which is called from the target startup code in order to establish the C runtime environment.  This would be necessary to ensure that all initialized global/static variables are properly loaded prior to branching to main().
In my case, I am using an MCU with an ARM Cortex-R4F core CPU.  When the device resets, I implement all of the steps recommended by the MCU manufacturer then attempt to branch to the symbol _start using the following lines of code:
extern void _start(void);
_start();

I am using something similar to the following to link the program:
armeb-eabi-gcc-7.5.0" -marm -fno-exceptions -Og -ffunction-sections -fdata-sections -g -gdwarf-3 -gstrict-dwarf -Wall -mbig-endian -mcpu=cortex-r4 -Wl,-Map,"app_tms570_dev.map" --entry main -static -Wl,--gc-sections -Wl,--build-id=none -specs="nosys.specs" -o[OUTPUT FILE NAME HERE] [ALL OBJECT FILES HERE] -Wl,-T[LINKER COMMAND FILE NAME HERE]
My toolchain in this case is gcc-linaro-7.5.0-2019.12-i686-mingw32_armeb-eabi, which is being used since my MCU device is big-endian.
As I trace through the call to symbol _start, I can see my program branch to symbol _start then a few unexpected things happen.
First, there are a couple of places where the following instruction is called:
EF123456  svc   #0x123456
This basically generates a software interrupt, which causes the program to branch to the software interrupt handler that I have configured for the device.
Secondly, the device eventually branches to __libc_init_array then _init.  However, symbol _init does not contain any branch instruction and allows the program to flow into _fini, which also does not contain any branch instruction and allows the program to flow into whatever code was placed next in memory.  This eventually causes some type of abort exception, as would be expected.
The disassembly associated with _init and _fini:
          _init():
00003b00:   E1A0C00D            mov        r12, r13
00003b04:   E92DDFF8            push       {r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r14, pc}
00003b08:   E24CB004            sub        r11, r12, #4
          _fini():
00003b0c:   E1A0C00D            mov        r12, r13
00003b10:   E92DDFF8            push       {r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r14, pc}
00003b14:   E24CB004            sub        r11, r12, #4

Based on some other documentation I read, I also attempted to call main() directly, but this just caused the program to jump to main() without initializing anything.  I also tried to call symbol __main() similar to what is done when using the ARM Compiler in order to execute startup code, but this symbol is not found.
Note that this is for a bare-metal-ish system that does not use semihosting.
My question is: Is there a way to set up the system and call a function that will establish the C runtime environment automatically and branch to main() using the GCC linker?
For the time being, I have implemented my own function to initialize .data sections and the .bss sections are already being zeroed at reset using a built in feature of the MCU device.
Adding some more details here:
The specific MCU that I am using should not be relevant, particularly taking the following discussion into consideration.
First, I have already set up the exception vectors for the device in an assembler file:
    .section .excvecs,"ax",%progbits
    .type   Exc_Vects, %object
    .size   Exc_Vects, .-Exc_Vects

// See DDI0363G, Table 3-6
Exc_Vects:
        b   c_int00        // Reset vector
        b   exc_undef      // Undefined instruction
        b   exc_software   // Software
        b   exc_prefetch   // Pre-fetch abort
        b   exc_data       // Data abort
        b   exc_invalid    // Invalid vector

There are two instructions that follow for the IRQ and FIQ interrupts as well, but they are set according to the MCU datasheet.  I have defined handlers for the undefined instruction, prefetch abort, data abort and invalid vector exceptions.  For the software exception I use some assembly to jump to an address that can be changed at runtime.  My startup sequence begins at c_int00.  These have all been tested and work with no problems.
My reset handler takes care of all of the steps needed for initializing the MCU in accordance with the MCU datasheet.  This include initializing CPU registers and the stack pointers, which are loaded using symbols from the linker file.
The toolchain that I am using, noted above, includes the C standard libraries and other libraries needed to compile and link my program with no problems.  This includes the symbol _start that I mentioned previously.
From what I understand, the function _start typically wraps main().  Before it calls main() it initializes .bss and .data sections, configures the heap, as well as performing some other tasks to set up the environment.  When main() returns, it performs some clean up tasks and branches to a designated exit() function.  (Side note: _start is defined in newlib based on the source code that I downloaded from linaro).
There is some detail regarding this in a separate response here:
What is the use of _start() in C?
I have been using the ARM Compiler as an alternative for the same project.  There, __main performs these functions.  For the stack initialization, I basically provide it an empty hook function and for exit I provide it with a function that safely terminates the program should main() return for some reason.  I am not sure if something like this is needed for GCC.
I would note that I have included option -specs="nosys.specs" without option -nostartfiles.  My understanding is that this avoids implementing some of the functions that do not want to use in my application, such as I/O operations, but links the startup code.
I am not using the heap in my project as dynamic memory use is frowned upon, but I was hoping to be able to use the startup code primarily in order to avoid having to remember to initialize .data sections manually.  Above I noted that my application is baremetal-ish.  I am actually using an RTOS and have the memory partitioned into blocks so that I can use the device MPU.


text:
Q: Javascript Variable is not defined why does it always say undefined when I move the mouse? It should return true, right? I hope somebody can help me :)
Before you ask I called the class in another JavaScript file!
class Block {

 constructor() {

    this.movable = true;
    this.move = false;

    this.div = document.createElement("div");
    this.div.classList.add("block");

    this.div.addEventListener("mousemove", function() {

        console.log(this.movable);

    });
    this.div.addEventListener("mousedown", function() {

        this.move = true;
        console.log("test");

    });
    this.div.addEventListener("mouseup", function() {

        this.move = false;
        console.log("test1");

    });

 }
 add() {

     document.body.appendChild(this.div);

 }
 remove() {

     document.body.removeChild(this.div);

 }

}

A: You can use the ES6 arrow function ()=>{} to solve your problem. The arrow function uses this of the current context of execution. In this case it is the instance of the class having the initialized movable property.
Where a normal anonymous function will use the this of the object on which the listener is attached to, in your case that is the div. As the div has no movable property you are getting undefined.

class Test{

 constructor() {
      this.movable = true;
      this.move = false;

      this.div = document.createElement("div");

      this.div.classList.add("block");

      this.div.addEventListener("mousemove", ()=> {
          console.log(this.movable);
      });
      this.div.addEventListener("mousedown", ()=> {
          this.move = true;
          console.log("test");
      });
      this.div.addEventListener("mouseup", ()=> {
          this.move = false;
          console.log("test1");
      });
    }

 add(){
     this.div.textContent ="Hover over me.";
     document.body.appendChild(this.div);
 }

 remove(){
     document.body.removeChild(this.div);
 }

}
var test = new Test();
test.add();
<body>
</body>

Quoting from MDN:

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

A: You have to study about javascript context.
every each function has own this. so if you apply external this, you should bind this.
reference: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this#bind_method
class Block {
    constructor() {
        this.movable = true;
        this.move = false;

        this.div = document.createElement("div");
        this.div.classList.add("block");

        this.div.addEventListener("mousemove", function() {
            console.log(this.movable);
        }.bind(this)); // bind this!!
        this.div.addEventListener("mousedown", function() {
            this.move = true;
            console.log("test");
        }.bind(this)); // bind this!!
        this.div.addEventListener("mouseup", function() {
            this.move = false;
            console.log("test1");
        }.bind(this)); // bind this!!

    }
    add() {
        document.body.appendChild(this.div);
    }
    remove() {
        document.body.removeChild(this.div);
    }
}

A: It's due to this scoping.
It turns out this from your constructor is not the same as the one from your callback:
class Block {
    constructor() {
        // here this is your instance of your class block
        this.movable = true;

        this.div.addEventListener("mousemove", function() {
            // here it's not since each function get's it's own from how it's called
            // since it is called by `div.addEventListener` and not you directly
            // JS had no way to get the root this
            console.log(this.movable);

        });
    }
}

The simplest solution is to use ES6 arrow functions.
class Block {
    constructor() {
        // here this is your instance of your class block
        this.movable = true;

        this.div.addEventListener("mousemove", () => {
            // this is bound to your instance of class block in this scope too !
            console.log(this.movable);
        });
    }
}

Note the () => { instead of function () { !
This works because arrow function don't have theyre own this but instead keep the one they had access to where they were created, very handy.

A: As the others mentioned, the reason you are getting undefined is this inside your event handler functions is not the instance of the class (as you're expecting).
You have three ways to fix that, two of them based off ES5, one of them based off ES6 (which shouldn't be a problem - you're using ES6 already in your code).
1 Explicitly bind the outer this to your handler functions using Function.prototype.bind().
bind() tells a functions what to use as this inside of its function body.

class Test {
  constructor() {
    this.movable = true;
    this.move = false;
    this.div = document.createElement("div");
    this.div.classList.add("block");
    this.div.addEventListener("mousemove", function() {
      console.log(this.movable);
    }.bind(this)); // .bind(this)
    this.div.addEventListener("mousedown", function() {
      this.move = true;
      console.log("test");
    }.bind(this)); // .bind(this)
    this.div.addEventListener("mouseup", function() {
      this.move = false;
      console.log("test1");
    }.bind(this)); // .bind(this)
  }
  add() {
    this.div.textContent = "Test";
    document.body.appendChild(this.div);
  }
  remove() {
    document.body.removeChild(this.div);
  }
}
var test = new Test();
test.add();
<body>
</body>

2 Store the reference to the class instance in a variable (here: self) and use that inside the handler function.
This used to be a very common pattern to solve the problem you've crashed into as well. With everyone jumping onto the ES6-train nowadays it's becoming less and less used. I do like it also for improved readability.

class Test {
  constructor() {
    const self = this; // reference to this stored in self
    this.movable = true;
    this.move = false;
    this.div = document.createElement("div");
    this.div.classList.add("block");
    this.div.addEventListener("mousemove", function() {
      console.log(self.movable); // self instead of this used
    });
    this.div.addEventListener("mousedown", function() {
      self.move = true; // self instead of this used
      console.log("test");
    });
    this.div.addEventListener("mouseup", fucntion() {
      self.move = false; // self instead of this used
      console.log("test1");
    });
  }
  add() {
    this.div.textContent = "Test";
    document.body.appendChild(this.div);
  }
  remove() {
    document.body.removeChild(this.div);
  }
}
var test = new Test();
test.add();
<body>
</body>

3 Use ES6 arrow function syntax.
Arrow functions don't have their own this (which can be a downside in some cases!), which makes the "outer" this available to them.

class Test {
  constructor() {
    this.movable = true;
    this.move = false;
    this.div = document.createElement("div");
    this.div.classList.add("block");
    this.div.addEventListener("mousemove", () => {
      console.log(this.movable);
    });
    this.div.addEventListener("mousedown", () => {
      this.move = true;
      console.log("test");
    });
    this.div.addEventListener("mouseup", () => {
      this.move = false;
      console.log("test1");
    });
  }
  add() {
    this.div.textContent = "Test";
    document.body.appendChild(this.div);
  }
  remove() {
    document.body.removeChild(this.div);
  }
}
var test = new Test();
test.add();
<body>
</body>

As others mentioned, if not using arrow functions for defining event handlers, this inside the handler willl usually hold a reference to the element the event was raised on (which is often very useful). To still access that despite using arrow functions, you can use the event.target property:
// notice I name a parameter e here
// which will hold the event object
// that is always passed to the event
// handler automatically - it just needs
// a name to make it accessible inside
(e) => { console.log(e.target); }


text:
Q: Me sale error en el editor cuando intento usar módulos creado por mi. Si funciona cuando lo pruebo, pero el error sigue apareciendo
Estoy aprendiendo a usar módulos, me sale esto  cada que intento usar uno (creado por mi). Sí puedo usar el modulo, pero el error sigue estando ahí (el error solo aparece en el editor, mas no en la terminal).

A: basico.py
def sumar(a, b):
    return a + b

def restar(a, b):
    return a - b

def multiplicar(a, b):
    return a * b

def dividir(a, b):
    if b != 0:
        return a / b
    else:
        return "El segundo valor ha de ser distinto de 0"

pruebas.py
Si basico.py y pruebas.py están en la misma carpeta no es necesario indicar calculos.basico, puedes simplemente escribir basico.
from basico import sumar

print(sumar(2, 3))

Resultado de ejecutar pruebas.py
5

Explicación
Tu código está bien, no tienes ningún error, simplemente el editor de código te indica que estás importando sumar, restar, multiplicar y dividir de basico.py. Y solo estás usando sumar en pruebas.py.
Unused import restar from wildcard importpylint(unused-wildcard-import) te indica que estás importando restar pero no lo usas. Lo mismo con multiplicar y dividir.
Si solo quieres usar sumar y quieres que desaparezca la sugerencia del editor, escribe en pruebas.py lo siguiente: from basico import sumar
De todas formas, puedes importar todo, como ya estás haciendo, por si más tarde necesitas usar una función diferente: from basico import *. Simplemente ignora la advertencia del editor.


text:
Q: MySQL SELECT query performance I have a query which has a list of values for checking against a single column in a multi column table.
Example query ONE......
SELECT `name`, `sleeps`
FROM `properties`
WHERE `town`='bude' OR `town`='newquay' OR `town`='widemouth' OR `town`='polzeath' OR `town`='crantock' OR `town`='perranporth' OR `town`='Porthmeor' OR `town`='St Ives' OR `town`='porthtowan'

Example query TWO......
SELECT `name`, `sleeps`
FROM `properties`
WHERE `town` IN ('bude', 'newquay', 'widemouth', 'polzeath', 'crantock', 'wadebridge', 'Porthmeor', 'St Ives', 'porthtowan')

*

*
*
-

I have run both in phpmyadmin and found the query speed to be very similar, all be it with a table of approx 5,000 records.
In terms of performance and durability when the table contains more data is is best to go for the 'IN' style query or use multiple instances OR?
Thanks

A: This is a simple test result,
SELECT * FROM item WHERE id = 1 OR id = 2 ... id = 10000
This query took 0.1139 seconds

SELECT * FROM item WHERE id IN (1,2,3,...10000)
This query took 0.0413 seconds

IN faster than OR

A: Convert the less efficient one into the other. So I think the answer should rather depend on the readability of each (where I think that IN is more efficient)
IN is 3 times faster than OR

A: I tried some querys, IN is faster everytime.


text:
Q: PostgreSQL select items of an array that are not in another array PostgreSQL table with two integer array columns, say a = [1,2,3,4] and b = [1,2,3,4,5,6]. The items of b that are not in a are 5,6, so as a query result I want an array [5,6].
How to achieve this in PostgreSQL?

A: with intarray extension installed, one may simply select a-b, cp. https://www.postgresql.org/docs/current/static/intarray.html


text:
Q: How can I convert the coordinates that are in aoiAreas in processedArea? I need to send the processed area element in a json
"aoiAreas": "R[-13.4838609810849, 46.16220269399153 -6.413637778339, 40.05118714878472]"
"processedArea": "-11.4838609810849, 44.16220269399153 -11.4838609810849, 42.05118714878472 -8.413637778339, 42.05118714878472 -8.413637778339, 44.16220269399153"
fun getRectStringFromBounds(bounds: LatLngBounds): String {
            return "R[${bounds.southwest.latitude},${bounds.southwest.longitude} " +
                    "${bounds.northeast.latitude},${bounds.northeast.longitude}]"
        }


text:
Q: Inverse of $f(x)=x^n(1-x)^k$ I am trying to find an inverse of a function
\begin{align}
f(x)=x^n(1-x)^k, x \in (0,1)
\end{align}
where $n$ and $k$ are some positive integers.
I know that his function doesn't have a 'pure' inverse. However, it should have upper and lower branches.
Also, the inverse cannot be written in terms of elementary functions. Therefore, it has to be written in terms of some generalized functions like the Lambert-W function.
Question: Does $f$ have an inverse in terms of some generalized functions?

A: The Lagrange inversion formula gives
$$a_i = \frac 1 {i!} \left. \frac {d^{i - 1}} {dy^{i - 1}}
 \left( \frac y {f(y)^{1/n}} \right)^{\! i} \, \right|_{y = 0} =
\frac 1 {i!} \left( \frac {i k} n \right)_{\! i - 1}, \\
f^{-1}(y) = \sum_{i \geq 1} a_i y^{i/n} =
y^{1/n} \hspace {1.5px} {_2 \hspace {-1px} \Psi_2} {\left( y^{1/n} \middle|
 {(1, 1), (\frac k n, 1 + \frac k n) \atop
  (2, 1), (\frac k n, \frac k n)} \right)},$$
where $(b)_i$ is the rising factorial and $\Psi$ is the Fox-Wright function. The second branch taking the values in $(0, 1)$ is $1 - f^{-1}(y)$ with $n$ and $k$ interchanged.


text:
Q: Class for picture view that change pic on mouse click I want to make a class that has a picture and it is changed to the next one by mouse click.I'm new to oop, my idea here was to make class similar to real life where there is new class instance for every new picture, is it possible to do it this way? Here is my code
import tkinter as tk
from PIL import Image,ImageTk
class Picture():
    _count=1
    def __init__(self,window):
        self.id=Picture._count
        Picture._count+=1
        self.img=Image.open(r'C:\ImgArchive\img%s.png' % self.id)
        self.pimg = ImageTk.PhotoImage(self.img)
        self.lab=tk.Label(window,image=self.pimg)
        self.lab.pack()
        self.lab.bind('<1>',self.click)
    def click(self,event):
        self.lab.destroy()
        self=self.__init__(window)
window = tk.Tk()
window.title('Album')
window.geometry('1200x900')
pic=Picture(window)
window.mainloop()

It works fine, but i'm not sure that old instances of my class is deleted, are they? And i use self.lab.destroy() because if i dont new picture appears down, like this

instead of this

So why it happens?What is elegant way for it?

A: Below example produces a simple image viewer tested with path of C:\Users\Public\Pictures\Sample Pictures, let me know if anything's unclear:
import tkinter as tk
from PIL import Image, ImageTk
#required for getting files in a path
import os

class ImageViewer(tk.Label):
    def __init__(self, master, path):
        super().__init__(master)

        self.path = path
        self.image_index = 0

        self.list_image_files()
        self.show_image()

        self.bind('<Button-1>', self.show_next_image)

    def list_files(self):
        (_, _, filenames) = next(os.walk(self.path))
        return filenames

    def list_image_files(self):
        self.image_files = list()
        for a_file in self.list_files():
            if a_file.lower().endswith(('.jpg', '.png', '.jpeg')):
                self.image_files.append(a_file)

    def show_image(self):
        img = Image.open(self.path + "\\" + self.image_files[self.image_index])
        self.img = ImageTk.PhotoImage(img)
        self['image'] = self.img

    def show_next_image(self, *args):
        self.image_index = (self.image_index + 1) % len(self.image_files)
        self.show_image()

root = tk.Tk()

mypath = r"C:\Users\Public\Pictures\Sample Pictures"
a = ImageViewer(root, mypath)
a.pack()

root.mainloop()


text:
Q: Call/Assign a variable of a Class that implements an Interface I wrote an easy interface-inheritance example to illustrate what I'm trying to do.
interface Fruit{
     public void taste();
}

class Banana implements Fruit {
     public String name = "Banana";
     public void taste(){
         System.out.println("yummy banana!");
     }

class Strawberry implements Fruit {
     public String name = "Strawberry";
     public void taste(){
         System.out.println("yummy strawberry!");
     }
}

class Lunch<Fruittype implements Fruit> {
     public Fruittype fruit;

     public void tasteit() {
         System.out.println("I'm going to eat a"+ fruit.name + "!" );
         // error: name cannot be resolved or is not a field
         fruit.taste();
     }
}

class exec {
     public static void main(String[] args) {
          Lunch<Banana> bananalunch  = new Lunch<>;
          bananalunch.fruit = new Banana();
          bananalunch.tasteit();
     }
}

So Banana and Strawberry are implementing Fruit. In the class Lunch I'm trying to call the fruit name and its function taste();
While calling the Function taste works just fine, i can't call the name (see: error in the comment)
Wanted Output:
I'm going to eat a Banana!
yummy banana!
Like I said, yummy banana works but the name can't be resolved. I tried to declare "public String name = "default""; in the Fruit interface. Then you can call it, but it will always say "default" and not the name in the actual class.
Is there a way to get a member of a generic Type that implements an interface?
P.S. I need to do it like this, of course this code was only for representation but I have a much larger more complicated code in which i encountered this problem- And I don't want to restructure it if not necessary.
Thank you in advance!

A: Your problem is caused by trying to access an instance member directly - fruit.name - instead of via a method - fruit.getName().
If you use a getter method, the correct method will be executed and return the required output.
That said, in this particular example it would make more sense to have a single getName() method in a base class, and a single _name variable in that base class, which is initialized to a different value based on the actual type of fruit class.
On the other hand, seeing that your Fruit is an interface rather than a base class, you can have each of the classes which implement that interface have a getName() method returning a different value.
For example:
class Strawberry implements Fruit {
     public String name = "Strawberry";
     public void taste(){
         System.out.println("yummy strawberry!");
     }
}

would become:
class Strawberry implements Fruit {
     public String getName () {
         return "Strawberry";
     }
     public void taste() {
         System.out.println("yummy strawberry!");
     }
}

You would have to add getName() to the interface:
interface Fruit {
     public String getName();
     public void taste();
}

Finally, your Lunch class becomes:
class Lunch<Fruittype implements Fruit> {
     public Fruittype fruit;

     public void tasteit() {
         System.out.println("I'm going to eat a "+ fruit.getName() + "!" );
         fruit.taste();
     }
}

A: Case, when class implements interface, means that object of this class can do something that described in interface.
For example, every plane shape has area. So we can determine interface:
interface PlaneShape {
    int getArea();
}

Area of square is product of edges. And area of circle is product of
squared radius by pi number divided by 2. So:
class Square implements PlaneShape {
    public int edge = 5;

    public int getArea() {
        return edge*edge;
    }
}

class Circle implements PlaneShape {
    public int radius = 5;
    public int pi = 3.14;

    public int getArea() {
        return radius*radius*pi/2;
    }
}

Interfaces use for abstraction. AreaCalculator operates with plane shapes, so it abstracts from any specific kind of plane shapes. AreaCalculator just knows that any shape can give him area  value by executing method getArea(). AreaCalculator don't know anything about special shape fields, like edge or radius.
class AreaCalculator<S implemets PlaneShape> {
    public S shape;

    public int calculateArea() {
        shape.getArea();
    }
}

By this way, in your example,Lunch<Fruittype implements Fruit> class don't know anything about fruits inner names, it doesn't "see" this fields, it only can invocate method taste(). You need to add method getName() to interface, and implement it.
On the subject of name="default" in interface. It declared in context of interface and hasn't any relation to implementations.


text:
Q: msaccess-like forms in a C# application I am using ms-access for developing front-end solutions for database management. I must admit that ms-access VBA is a solid limitation to the development of large-scale apps, and this is why I have been turning around the idea of using c# instead of VBA.
In fact, it's quite easy to get rid of everything in ms-access, except one stuff: the forms. These are particularly quick and efficient when it comes to data display and edit. In the latest versions of ms-access, forms act like classes, so you can specifically manage one or multiple instances of the same form at runtime. When used in continuous mode, they can be used to manipulate data "the excel way", with lines and columns display, filtering and ordering possibilities. In short, I like it.
It would be of course possible to reverse-engineer this form object under c# (or another similar language), but this might have already been done: have you ever used a library, an activeX control or any other kind of add-on that offered the possibility to manipulate msacces-like forms in c#?
EDIT: following Renaud's comment, I do admit there is no interest in converting only the layout part of a form, and there is no way to convert its customized/VBA part. In our specific situation, we stopped using customized VBA code in forms a long time ago, and forms properties, methods and events are managed from modules. This has even been discussed here.
In fact, all our forms rely on a common template and are automatically built out of a 'forms' and a 'controls' table. All underlying event-management code production is automated: depending on their type, controls are associated with selected events, and the event's code gives hand to standard\generic procedures held in the app's modules. This is what makes me think it is possible to transfer our 'ms-access forms technology' to a .NET platform.

A: I am not aware of any project that would let you take an Access application and reconstruct it in .Net or anything else.
I believe that there are some good reasons why such tools can only be very limited in what they offer.
A tool that would only converts the form's layout is going to be vastly lacking in purpose: it's very easy to (re-)create functional layouts manually in .Net, be it WinForms or WPF.
It can take a few hours per screen, but it's fast enough to be feasible.
An automated tool would have a hard time translating Access forms to look good in .Net though:
a lot of Access apps are poorly designed in term of UI, with poor choice of control placement, reliance on custom colour schemes and tricks to bend the limited access controls to one's will.
On top of that, you have a lot of object properties that are very specific to Access and would not translate well into .Net without requiring a fair amount of additional supporting code.
But I think the elephant in the room is VBA: most complex Access forms are customized with VBA controlling the UI and Business logic, and that can't be translated into .Net without some significant efforts.
The fact that MS Access apps are built around a procedural, module-centric approach rather than object oriented, and that Access apps invariably have very poor separation of UI and Business logic, doesn't help the cause.
Direct translation -if it was possible at all- would just create a crappy .Net application.
There are frameworks for building simple/complex business apps that are similar to Access in many ways.
Developer Express have eXpressApp Framework which allows you to build and customize UI, generating the database, manage users, security, etc and will easily allow you to construct data views with close to no code (you can add as much code as you need though, it's all .Net). The UI uses their excellent controls, which are far superior in terms of behaviour and being customizable than those in Access.
That framework targets both desktop and web (you make a single project and you get both automatically).
Alas, it's not really cheap you must have a Universal Subscription that costs $2200 at this date (yearly renewal is $800).
Another product, free or cheap, depending on your MSDN subscription, is LightSwitch.
LightSwitch is being viewed by some as a modern, developer-centric- successor of Access.
It was originally targeting Silverlight for easy deployment in the enterprise, but recent versions are also targeting HTML5, so you can 'run your app anywhere', even tablets.
The principle here is to easily construct decent data-oriented forms and views that allow fast data entry and customized reports.
Like you, I regularly think about how existing MS Access apps could be converted into .Net, but the more I think about the details, the hairier it gets, and then you look at what people have been doing with Access, and you know that for any tool to be successful, it would have to handle all the horrible ways that office users have constructed their apps, and that's just insane.
There are just too many ways to build an Access application, and most of them are very poor and have no chance of allowing an easy conversion without changing paradigm completely, usually forcing a complete rewrite.


text:
Q: When getting an answer back from WCF i get a "Strongly-typed" error
System.InvalidOperationException:
Operation 'procWsDocumentAsync' contains a message with parameters. Strongly-typed or untyped message can be paired only with strongly-typed, untyped or void message.

    MsgBody.Text = "<OPERVALS><BOOKINpG_ID>BK170001194</BOOKING_ID><DATE>20180828</DATE></OPERVALS>";

    senderId.Text = "DSVWS";
    acessCode.Text = "DSVWS2018";
    operationCode.Text = "BKCARGORECEPTION";
    senderMsgId.Text = "DSV321123134";

    StrMsgBody = MsgBody.Text;
    StrsenderId = senderId.Text;
    StracessCode = acessCode.Text;
    StroperationCode = operationCode.Text;
    StrsenderMsgId = senderMsgId.Text;
}

private async void Submit_Clicked_1(object sender, EventArgs e)
{
    string resposta;
    string resposta1;

    SCPCon.ScpWSIntegrationClient cli = new SCPCon.ScpWSIntegrationClient();
    SCPCon.procWsOperationResponse resp = await cli.procWsOperationAsync

    (
        new SCPCon.procWsOperationRequest
        {
            ScpOperWsmsgRecUser_1 = new SCPCon.ScpWsmsgRecUser
            {
                wsMsgBody = StrMsgBody,
                wsMsgHeader = new SCPCon.ScpWsmsgHdrRecUser
                {
                   sentDatetime = DateTime.Now,
                   senderId = StrsenderId,
                   accessCode = StracessCode,
                   operationCode = StroperationCode,
                   senderMsgId = StrsenderMsgId,
                }
            }
        }
    );
    resposta = resp.ScpOperWsmsgResRecUser_2.resultText;
    resposta1 = resp.ScpOperWsmsgResRecUser_2.resultCode;
}


text:
Q: Is there any way of getting the audio level of an audio device using the AudioSwitcher.AudioApi? Is there any way of getting the volume level of an audio device in C# using the AudioSwitcher.AudioAPI.
I'm able to set and get the MAX volume of the audio device using:
deviceName.volume;

But is there any way of getting the CURRENT volume of the audio device. E.g. there is a YouTube video playing and I want to get the percentage of the audio level (Like in windows)
I would like to use the same API already used (AudioSwitcher.AudioAPI) to keep the application light. But, if there isn't any other solution, I can use another API.


text:
Q: Isolation of linux distro (ubuntu 18.04 and 20.04) in wsl In Windows 10 I have installed 2 type of linux distro ubuntu 18.04 and ubuntu 20.04 using WSL.
I want to configure 20.04 for ssh port 22 and 18.04 for ssh port 2222 .
Will doing these changes affect either distro?
When we installed these distro are they isolated or will they affect each other ?

A: You can change the SSH port as much as you like on either (or both) of your systems. It will have no impact; your systems will run normally with the changed port settings.
SSH is for your interaction with the system. No internal process uses it. A stock install of Ubuntu Desktop doesn't even have an SSH server at all.

A: Well, there's the "simple answer" which answers your question, but probably doesn't really help you all that much.  And then there's the "what you really need to do to run an SSH server on WSL."
Simple answer, as others have already said -- Each instance can operate its own SSH server in relative isolation.
Longer answer ... it's complicated.  Running an SSH server on WSL is one thing.  Actually being able to connect to it remotely is another thing entirely.  You have to worry about port forwarding, firewalls, and service start-up (not something that WSL does well in the absence of systemd).
First, it would be helpful to know your use-case(s) for ssh in WSL.
If you just want to access your instances remotely, then I find it is easiest to just install the Windows 10 OpenSSH server on the host itself.  With this in place, the only real configuration you need to do is open port 22 on the Windows Firewall.  And the one-liner for that is included in the Microsoft instructions linked above for the install.
With OpenSSH server installed in Windows, you can use:
ssh -t <user@windows_host_or_ip> wsl -d <wsl_instance_name>

... to get to your WSL instance.  The -d <wsl_instance_name> isn't needed for your default WSL instance.
But perhaps you have some other reason for needing SSH access to the WSL instances.  For instance, I use Ansible to connect to and configure some of my WSL instances across multiple machines.  This requires a "real" SSH server be running for each instance.
In that case, you need to come up with solutions for:

*

*Port-forwarding from the Windows host to WSL2 instances (WSL1 does not require port forwarding, as its network runs "bridged" with the Windows network interface.)

*Starting the sshd service in each instance (it isn't automatic)

In my opinion, the easiest solution here is still to install Windows OpenSSH server on port 22, then configure each WSL instance with its own OpenSSH server as well, but (of course) on different ports.  You can then use the Windows host as a "jumphost" for accessing the instances inside it.  Detailed directions for this can be found in this answer on Super User.
This also solves the "starting sshd in WSLproblem, because you can use a syntax similar to the earlier one I mentioned (using thewsl` command through Windows ssh) to start the service remotely.  In other words, as long as the Windows SSH server is set to start automatically, you can use this to start any of the WSL instances SSH servers.  The details, again, can be found in that answer.
Also worth reading is this answer on Super User regarding general port forwarding scenarios in WSL.


text:
Q: Problem Involving Finite Fields I've arrived at a Theorem in text that I'm confused about:
Note: My question below is about the statement of this theorem, not about a proof for it.  (The proof is supplied in the text)
Theorem:  Let $E$ be a field of $p^{n}$ elements contained in an algebraic closure $\tilde{\mathbb{Z}_{p}}$ of $\mathbb{Z}_{p}$.  The elements of $E$ are precisely the zeros in $\tilde{\mathbb{Z}_{p}}$ of the polynomial $x^{p^{n}} - x$ in $\mathbb{Z}_{p}[x]$.
The first line startles me somewhat.  So far in this book we have never considered the algebraic closure of any structure which wasn't a field.  And for $\mathbb{Z}_{p}$ to be a field, we must have that $p$ is prime.  This is not given in the theorem, and there was no blanket statement at the beginning of the section as there sometimes is.
My Question:  Have I missed some key fact regarding the orders of a finite field needing to be prime powers?
To give perspective to my background and where this chapter fits into development, the purpose of the chapter I am reading is to build the Galois Field of order $p^{n}$, with which I am not yet familiar.

A: The theorem states that $E$ is a field. For a field to have $p^n$ elements, $p$ must be prime (unless the author is a psycho, see comments); since all finite fields have order $p^n$ for $p$ prime. So the statement that $E$ is a field of order $p^n$ already determines the fact that $p$ is prime, and so (provided this result is known) there is no need to mention that $p$ is prime in the statement of the theorem. If this is not a known result, then I refer you to almost any undergraduate algebra textbook which covers fields for a proof.

A: I'm writing this answer both to satisfy myself and to address the key problem in my question.
Fact:  A finite field must have a prime-power order
The proof is an easy application of the immediately preceding Corollary to this theorem which I have already asked about here:  Question about a corollary about Finite Fields
Proof:  Since the preceding corollary states that if a field has characteristic $p$, then it must have $p^n$ elements for some $n\geq 1$, all that needs to be shown is that a field cannot have a non-prime characteristic.
If $F$ has characteristic $p$, and $p = xy$ for some $1 < x,y < p$, then $x = x\cdot 1\neq 0$ and $y = y\cdot 1\neq 0$ by definition of characteristic.  But then $xy = xy\cdot 1 = p\cdot 1 = 0$ by assumption.  Therefore $x$ and $y$ are zero divisors contained in the field $F$ which is a contradiction.
Thanks to everyone as usual for their seemingly infinite patience with my questions.


text:
Q: Showing when the spectral sequence associated to a filtered complex $C$ collapses using a similar complex $C\otimes\mathbb{F}[t]$ Let $\mathbb{F}$ be a field, and let $C=\bigoplus_{i,j\in\mathbb{Z}} C^{i,j}$ be a bigraded $\mathbb{F}$-vector space of finite total dimension. Suppose there are two differentials $d$ and $\widetilde{d}$ on $C$ such that

*

*$d$ is of bidegree $(1,0)$, i.e. $d:C^{i,j}\to C^{i+1,j}$,

*$\widetilde{d}$ is of bidegree $(1,1)$, i.e. $d:C^{i,j}\to C^{i+1,j+1}$, and

*$d$ and $\widetilde{d}$ anti-commute, i.e. $\widetilde{d}\circ d = -d \circ\widetilde{d}$.

Then $d+\widetilde{d}$ is a differential on $C$. There is a filtration $\mathcal{F}^p C = \bigoplus_{i\in\mathbb{Z}, j\geq p} C^{i,j}$ which induces a spectral sequence on the complex $(C,d+\widetilde{d})$. See Wikipedia reference. Since $C$ is of finite total dimension, the spectral sequence is guaranteed to collapse at some point.
I am interested in relating the homology of $(C,d+\widetilde{d})$ and the page at which the above spectral sequence collapses to the following construction.
Consider the complex $C\otimes \mathbb{F}[t]$ where $t$ has bidegree $(0,-1)$. If $x_0\in C^{i,j}$, then the bidegree of $x_0 t^k$ in $C\otimes \mathbb{F}[t]$ is $(i,j-k)$. The differential in the complex is $d + t\widetilde{d}$. Since multiplication by $t$ is of bidegree $(0,-1)$ and $\widetilde{d}$ is of bidegree $(1,1)$, the map $t\widetilde{d}$ is of bidegree $(1,0)$. Thus the map $d+t\widetilde{d}$ preserves the second grading on $C\otimes \mathbb{F}[t]$.
Let's denote the homology of $(C,d+\widetilde{d})$ by $H=\bigoplus_{i\in\mathbb{Z}} H^i$, and let's denote the homology of $(C\otimes\mathbb{F}[t],d+t\widetilde{d})$ by $\mathcal{H} = \bigoplus_{i,j\in\mathbb{Z}} \mathcal{H}^{i,j}$. Suppose that the homology of $(C,d+\widetilde{d})$ is $H\cong\mathbb{F}^N=\underbrace{\mathbb{F}\oplus\cdots\oplus\mathbb{F}}_{N}$.
Let $\operatorname{T}(\mathcal{H})$ consist of those elements $\alpha\in\mathcal{H}$ such that $t^n\;\alpha=0$ for some nonnegative integer $n$. If $\alpha\in\operatorname{T}(\mathcal{H})$ and $n$ is the smallest integer in $\mathbb{Z}_+$ such that $t^n\; \alpha=0$, then we say the order of $\alpha$ is $n$. The order of the zero element in $\mathcal{H}$ is declared to be zero.

*

*Prove that $\mathcal{H}\cong \operatorname{T}(\mathcal{H})\oplus\mathbb{F}[t]^N = \operatorname{T}(\mathcal{H})\oplus\underbrace{\mathbb{F}[t]\oplus\cdots\mathbb{F}[t]}_{N}$.

*Prove that the page where the spectral sequence for $(C,d+\widetilde{d})$ collapses is one more than the maximum order of any element in $\operatorname{T}(\mathcal{H})$.

I am especially interested in Problem 2 above.


text:
Q: Is hardcode float precise if it can be represented by binary format in IEEE 754? for example, 0 , 0.5, 0.15625 , 1 , 2 , 3... are values converted from IEEE 754. Are their hardcode version precise?
for example:
is
float a=0;
if(a==0){
    return true;
}

always return true? other example:
float a=0.5;
float b=0.25;
float c=0.125;

is a * b always equal to 0.125 and a * b==c always true? And one more example:
int a=123;
float b=0.5;

is a * b always be 61.5? or in general, is integer multiply by IEEE 754 binary float precise?
Or a more general question: if the value is hardcode and both the value and result can be represented by binary format in IEEE 754 (e.g.:0.5 - 0.125), is the value precise?

A: There is no inherent fuzzyness in floating-point numbers. It's just that some, but not all, real numbers can't be exactly represented.
Compare with a fixed-width decimal representation, let's say with three digits. The integer 1 can be represented, using 1.00, and 1/10 can be represented, using 0.10, but 1/3 can only be approximated, using 0.33.
If we instead use binary digits, the integer 1 would be represented as 1.00 (binary digits), 1/2 as 0.10, 1/4 as 0.01, but 1/3 can (again) only be approximated.
There are some things to remember, though:

*

*It's not the same numbers as with decimal digits. 1/10 can be
written exactly as 0.1 using decimal digits, but not using binary
digits, no matter how many you use (short of infinity).

*In practice, it is difficult to keep track of which numbers can be
represented and which can't. 0.5 can, but 0.4 can't. So when you need
exact numbers, such as (often) when working with money, you shouldn't
use floating-point numbers.

*According to some sources, some processors do strange things
internally when performing floating-point calculations on numbers
that can't be exactly represented, causing results to vary in a way
that is, in practice, unpredictable.

(My opinion is that it's actually a reasonable first approximation to say that yes, floating-point numbers are inherently fuzzy, so unless you are sure your particular application can handle that, stay away from them.)
For more details than you probably need or want, read the famous What Every Computer Scientist Should Know About Floating-Point Arithmetic. Also, this somewhat more accessible website: The Floating-Point Guide.

A: No, but as Thomas Padron-McCarthy says, some numbers can be exactly represented using binary but not all of them can.
This is the way I explain it to non-developers who I work with (like Mahmut Ali I also work on an very old financial package): Imagine having a very large cake that is cut into 256 slices.  Now you can give 1 person the whole cake, 2 people half of the slices but soon as you decide to split it between 3 you can't - it's either 85 or 86 - you can't split the cake any further.  The same is with floating point.  You can only get exact numbers on some representations - some numbers can only be closely approximated.

A: C++ does not require binary floating point representation. Built-in integers are required to have a binary representation, commonly two's complement, but one's complement and sign and magnitude are also supported. But floating point can be e.g. decimal.
This leaves open the question of whether C++ floating point can have a radix that does not have 2 as a prime factor, like 2 and 10. Are other radixes permitted? I don't know, and last time I tried to check that, I failed.
However, assuming that the radix must be 2 or 10, then all your examples involve values that are powers of 2 and therefore can be exactly represented.
This means that the single answer to most of your questions is "yes". The exception is the question "is integer multiply by IEEE 754 binary float [exact]". If the result exceeds the precision available, then it can't be exact, but otherwise it is.
See the classic "What Every Computer Scientist Should Know About Floating-Point Arithmetic" for background info about floating point representation & properties in general.

If a value can be exactly represented in 32-bit or 64-bit IEEE 754, then that doesn't mean that it can be exactly represented with some other floating point representation. That's because different 32-bit representations and different 64-bit representations use different number of bits to hold the mantissa and have different exponent ranges. So a number that can be exactly represented in one way, can be beyond the precision or range of some other representation.

You can use std::numeric_limits<T>::is_iec559 (where e.g. T is double) to check whether your implementation claims to be IEEE 754 compatible. However, when floating point optimizations are turned on, at least the g++ compiler (1)erroneously claims to be IEEE 754, while not treating e.g. NaN values correctly according to that standard. In effect, the is_iec559 only tells you whether the number representation is IEEE 754, and not whether the semantics conform.

(1) Essentially, instead of providing different types for different semantics, gcc and g++ try to accommodate different semantics via compiler options. And with separate compilation of parts of a program, that can't conform to the C++ standard.

A: In principle, this should be possible. If you restrict yourself to exactly this class of numbers with a finite 2-power representation.
But it is dangerous: what if someone takes your code and changes your 0.5 to 0.4 or your .0625 to .065 due to whatever reasons? Then your code is broken. And no, even excessive comments won't help about that - someone will always ignore them.


text:
Q: Non instatiable class by deleting destructor? I have a class that I use for purely syntactic purposes, to call a function in a certain way. This is a simplified example:
#include<iostream>

template<class T1>
struct make{
    template<class T2>
    static T1 from(T2 const& t2){
        return T1{}; //or something more complicated
    }
};

int main(){
    double d = make<double>::from(2);
    std::cout << d << '\n';
}

Now, suppose I want to warn the user that this class should not be instantiated. There may be uses for the class to be instatiable but
 I have the curiosity if it is possible to forbid that?
First I tried deleting the default constructor
template<class T1>
struct make{
    make() = delete;
    template<class T2>
    static T1 from(T2 const& t2){
        return T1{}; //or something more complicated
    }
};

But then this is still possible:
make<double> m{}; // valid

Finally, I tried deleting the destructor and that seemed to work
template<class T1>
struct make{
    ~make() = delete;
    template<class T2>
    static T1 from(T2 const& t2){
        return T1{}; //or something more complicated
    }
};

But it seems that then the class can still be allocated by new.
Should I delete both the destructor and the delete constructor, (what about the copy and move constructor?)
Is this the best way to disallow instantiation?
code here: http://coliru.stacked-crooked.com/a/0299c377c129fffb
#include<iostream>

template<class T1>
struct make{
    make() = delete;
    ~make() = delete;
    template<class T2>
    static T1 from(T2 const& t2){
        return T1{}; //or something more complicated
    }
};

int main(){
    double d = make<double>::from(2);
    std::cout << d << '\n';
    make<double> m{}; // compile error (no destructor)
    auto p = new make<double>{}; // compile error (no constructor)
}

A:
But then this is still possible:
make<double> m{}; // valid

... I did not know that would work. But now that I do, I also know why it works. And therefore, how to stop it.
It works because make<T> as you declared it is an aggregate. Even though it has a deleted default constructor, C++ still considers it an aggregate. And if you use braced-init-lists on an aggregate, you get aggregate initialization.
The way to stop it is simple: make it no longer an aggregate:
template<class T1>
struct make{
    template<class T2>
    static T1 from(T2 const& t2){
        return T1{}; //or something more complicated
    }

    make() = delete;

private:
    char c; //Not an aggregate
};

That private member forces make<T> to no longer be an aggregate. Therefore, it cannot be used with aggregate initialization, so {} will attempt to call the default constructor. Which naturally will fail since it's deleted.
Trivially copyable gymnastics might still be used to create instances of make<T>. You could shut those down by giving it a virtual destructor:
template<class T1>
struct make{
    template<class T2>
    static T1 from(T2 const& t2){
        return T1{}; //or something more complicated
    }

    make() = delete;

private:
    char c; //Not an aggregate
    virtual ~make() = default;
};

That ought to be sufficient to prevent legal C++ code from creating an object of that type.


text:
Q: Blazor, select an item in for loop of components and deselect the others In Blazor Webassembly version 5:
I have a for loop which iterates over data items to show them and a user should be able to select the items by clicking. What is the best way to achieve that?
I want to select the selected PersonItem but deselect the other components. The problem is with deselecting the others.
PersonItem.Razor:
@if (Person!= null)
{

@Person.Name

}
@code {

    [Parameter] public PersonPerson { get; set; } = null;
    [Parameter] public bool IsSelected { get; set; }=false;
    [Parameter] public EventCallback<Person> OnClick { get; set; }
    private string GetStyle() => IsSelected ? "cursor:default;color:blue" : "cursor:pointer";

    protected override Task OnParametersSetAsync()
    {
        StateHasChanged();
        return base.OnParametersSetAsync();
    }

    private async Task InvokeOnClick()
    {
      IsSelected = true;
      await OnClick.InvokeAsync(Person);
    }
}

MyPage.razor :
@inject IPersonRepo personRepo;

@if (PersonList !)
{
    foreach (var person in PersonList)
    {
        <PersonItem Person="@person"></PersonItem>
    }
}
else
{

Not Yet!

}

@code {
    public List<Person>? PersonList { get; set; } = null;

    protected async override Task OnInitializedAsync()
    {
        await GetAllPersons(null);
        await base.OnInitializedAsync();
    }

    public async Task GetAllPersons(EventArgs e)
    {
        PersonList = await personRepo.GetAllPersons();
    }
}

A: You already have most of the ingredients.
The requirement is fulfilled when you use OnCLick and IsSelected:
foreach (var person in PersonList)
{
    <PersonItem Person="@person"
           OnClick="SelectPerson"
           IsSelected="person==selectedPerson" />
}

and in @code:

Person selectedPerson = null;

void SelectPerson(Person person)
{
   selectedPerson = person;
}


text:
Q: Is this expression always irrational? Is it right that
$$\sqrt[a]{2^{2^n}+1}$$
for every $$a>1,n \in \mathbb N $$
is always irrational?

A: As lhf notes, we just have to see that $2^{2^n}+1$ can never be a perfect power. However, since $2^{2^n}$ is a perfect power, using Mihailescu's theorem the only pair of perfect powers differing by $1$ is $8$ and $9$, but $2^{2^n}$ can't be equal to $8$ for $n$ natural. So your expression is, indeed, always irrational.
(I guess I should note that using full Mihailescu's theorem here might be an overkill - 2 being a prime should let us give a relatively simple argument... but hey, whatever works :) )

A: $\sqrt[a]{m}$ is rational iff it is an integer iff $m$ is an $a$-th power.
The question deals with Fermat numbers.
Apart from the easy counterexamples, Wikipedia says that even a weaker version of the question is an open problem:

Does a Fermat number exist that is not square-free?

A: $$a=1\to 2^{2^n}\in \Bbb Q$$
$$a=2\to \sqrt{2^{2^n}} \in \Bbb Q$$


text:
Q: Как сохранить данные в txt.файл по нажатию кнопки asp.net mvc Допустим я хочу добавить книгу\товар\пользователя без разницы что ,у меня есть форма с полями для ввода ,и после того как я заполнил поля ,я хочу по нажатию кнопки сохранить данные в txt.файл. Я искал в интернете ответ на данный вопрос ,но конкретно ничего не нашел ,может вы сможете что-то посоветовать ? Если вопрос не совсем понятен и нужно больше информации ,пишите - я добавлю инфу .

A: Используйте Json.Net для сериализации формы, полученной от пользователя.
Используйте System.IO.File для сохранения файла. Пользуйтесь асинхронными версиями методов, если это возможно

A: Создай форму с кнопкой:
<form action="" method="post">
  <input type="text" name="book_name" placeholder="book name">
  <input type="text" name="book_describe" placeholder="describe your book">
  <button name="success">Send</button>
</form>

теперь обработай в php коде:
if(isset($_POST['success'])){
  $book_name = $_POST['book_name'];
  $book_describe = $_POST['book_describe'];

и код записи в файл(почитай о нем больше):
 $file = fopen("адрес файла например: logs/text.txt", "a+t");
 fwrite($file, "$book_name\n$book_describe");
 fclose($file);
}

все) код создает, или, если такой файл есть - записывает в него текст, введенный в форму)


text:
Q: Include PHP code with the same ID My problem is include() doesn't work in this example:
...

$lang = $_GET["lang"];
$id = $_GET["id"];

if ($lang == "fr"){
    include ('indexFr.php?id='.$id);
}
else if ($lang == "ar"){
    include ('indexFr.php?id='.$id);
}
else if ($lang == "en"){
    include ('indexFr.php?id='.$id);
}

...

I work with this:
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

switch ($lang){
    case "fr":
        header("Location: indexFr.php?id=".$id);
        break;
    case "ar":
        header("Location: indexAr.php?id=".$id);
        break;
    case "en":
        header("Location: indexEn.php?id=".$id);
        break;
    default:
        header("Location: indexEn.php?id=".$id);
        break;
}

But if I want to include something else (not language page) I think this is the right code but, it doesn't work:
include ('www.monsite.com/indexFr.php?id='.$id);

How can I do it?

A: If your $_GET array already has a value for id, you don't need that query string on the end if you're doing an include. It will use the $_GET array you already have and get the same $_GET['id'] value.
include is, in effect, putting the code of the external file into the PHP code that is already running. So, for example, if you have this file:
index.php?id=5
echo $_GET['id'];
include "otherfile.php";

And then this other file:
otherfile.php
echo $_GET['id'];

The output will be:
55

Because you are effectually creating a file that looks like this:
echo $_GET['id'];
echo $_GET['id'];

The include tag doesn't work with query strings because since it's a local file, the query string isn't used.
If you want to include the file from a different domain, you could try:
include ('http://www.monsite.com/indexFr.php?id='.$id);

That said, including files cross-domain is considered bad practice and will possibly just include the generated HTML and not the PHP. If you're including a file from your local filesystem, you really should just use the $_GET variable that's already there.

A: You need to specify a full URL for this to work. What you're specifying will look for a file on your local filesystem called indexFr.php?id=123, which is not what you're trying to do. You need an http:// or https:// in there, so it knows to go through a web-server, which will pass your arguments.
http://www.php.net/manual/en/function.include.php
Indeed, they provide an example case which matches yours quite closely:
// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';


text:
Q: Optional input variables in scanf is there a way to have optional input variables in scanf ?
I have a program that scans input until EOF. That input can look like this:
+ 10 20 30
- 10 20 30
? 10

When I type (or read from a file) + or - it is always followed by three numbers but when I type in ? it is only followed by one number (always).
My current code looks like this:
#include <stdio.h>
#include <stdlib.h>

int main(){
  char action;
  int dc1,dc2,cable;
  while(scanf(" %c %d %d %d",&action,&dc1,&dc2,&cable)!=EOF){
    if((dc1==dc2)||(cable<1)||(dc1>999)||(dc2>999)||(dc1<0)||(dc2<0)){
      printf("Wrong input.\n");
      return 0;
    }
    else{
      if(action=='+'){
      /*code*/
      }
      else if(action=='-'){
      /*code*/
      }
      else if(action=='?'){
      /*code*/
      }
      else{
        printf("Wrong input.\n");
        return 0;
      }
    }
  }
  return 0;
}

Right now it requires me to type in three numbers all the time, even if I want to type in the "?" action.
Is there a way to make some of the variables in scanf optional so the input "? 10" would also be valid.
PS.
I have stripped the code so it is not too long. I hope I have included everything that is necessary.
I would also appreciate if I didn't have to rework the code too much because it is basically done, everything works like it needs to. This is the only thing that is stopping me from turning in my code.
PPS. This is for a homework.

A: As mentioned in comment this can be easily checked with sscanf() and fgets.
We are using the fgets to read a line and then pass it to the parser function. That function tries to parse the line. sscanf returns the successful number of parameters passed. Based on that count we are deciding which input it is.
This code is just a starting point for how to start. It avoids the lots of error checking and concentrates on the technique as discussed above by Jonathan Leffler.
Code example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 256

void add (int b,int c,int d){
    printf("%d+%d+%d=%d\n",b,c,d,b+c+d);
}
void sub (int b,int c,int d){
    printf("%d-%d-%d=%d\n",b,c,d,b-c-d);
}
void query (int a){
    printf("?%d\n",a);
}
void parseAndProcess(const char *buf){
    char a;
    int  b, c, d;
    size_t ct;
    ct  = sscanf(buf,"%c%d%d%d",&a,&b,&c,&d);
    if( ct <= 1){
        //error
    }
    else if( ct==2 ) {
        if( a == '?'){
            query(b);
        }
        else{
            //error
        }
    }
    else if( ct == 3){
        // error
    }
    else if( ct == 4){
        if( a == '+') add(b,c,d);
        else if( a == '-') sub(b,c,d);
        else{
            //error
        }
    }
    else{
        // error
    }

}

int main(void){
    char buf[BUFFSIZE];
    while(fgets(buf,BUFFSIZE,stdin)){
        parseAndProcess(buf);
    }
    return EXIT_SUCCESS;
}

Here add,sub methods are to be implemented for actual code. A demo implementation is shown here above. For example here in add,sub no overflow checking is there.


text:
Q: Delegate does not conform to protocol when using IBMCloudAppID Authorization delegate I'm trying to use IBM App ID cloud sign in for my iOS application and when I add the Authorization Delegate it keeps saying "Type 'SigninDelegate' does not conform to protocol 'TokenResponseDelegate'",  but the protocol stubs are in my class that do conform to the protocol?
What I've tried is to create my own protocol that uses the same functions and parameters but that didn't work.
This is what it looks like to inherit the protocol and the stubs that are required to use if I want to use the IBMCloudApp id sign in functionality.
import UIKit
import IBMCloudAppID
import BMSCore

class SigninDelegate: AuthorizationDelegate {

   func onAuthorizationSuccess(accessToken: AccessToken?, identityToken: IdentityToken?, refreshToken: RefreshToken?, response: Response?)

   func onAuthorizationFailure(error: AuthorizationError)

   func onAuthorizationCanceled(error: AuthorizationError)

}

Inside the AuthorizationDelegate there's this
public protocol AuthorizationDelegate : TokenResponseDelegate {

    func onAuthorizationCanceled()
}

then inside the TokenResponseDelegate there's this
import Foundation
import BMSCore

public protocol TokenResponseDelegate {

    func onAuthorizationFailure(error: AuthorizationError)

    func onAuthorizationSuccess(accessToken: AccessToken?, identityToken: IdentityToken?, refreshToken: RefreshToken?, response:Response?)
}

The expected result is this should be working fine since I am implementing the necessary protocol stubs...

A: According to IBM docs your SigninDelegate should look something like this
import IBMCloudAppID

class delegate : AuthorizationDelegate {
    public func onAuthorizationSuccess(accessToken: AccessToken, identityToken: IdentityToken, response:Response?) {
        //User authenticated
    }

    public func onAuthorizationCanceled() {
        //Authentication cancelled by the user
    }

    public func onAuthorizationFailure(error: AuthorizationError) {
        //Exception occurred
    }
}

Unless you are using a different version


text:
Q: 18.04 dual boot problems with ASUS FX503 I am having some problems installing 18.04 and showing the screen.
My laptop has a GTX 1050 Graphics,and a I-7 with integrated graphics. I've tried nomodeset and nouveau.modeset=0, i915.modeset=0 and various other kernel params I have seen online.
I have also tried a fresh install of Ubuntu,reformatting the drive, etc. All with no luck. Here is some stuff I have found out along the way.
When I run Ubuntu in the try without installing,  It does in fact load the OS fully; I know this for a fact because I hear a camera noise when I hit print screen. Also, I can connect a additional monitor and combined with the kernel params(nomodeset, nouveau.modeset=0, i915.modeset=0) and I can finally see the UI.
I was able to install Ubuntu from this, load up the OS, and I tried to purge all NVidia packages, add in beta drivers, install them. After doing all that I have had still no luck.
How can I debug/fix this?
EDIT. I've done some more research and the problem still happens once i disable the splash screen by removing quiet splash from the kernel parameters.

A: I just ended up ditching Ubuntu 18.04 and I am sticking with 17.10 for now.
I ran the installer with nomodeset as a kernel parameter and I was able to install Ubuntu. Once it was installed i reran Ubuntu and followed the normal steps for installing beta drivers and I do not have any display problems at all.


text:
Q: How does this site know that I am opening another tab? When I login to a site, which is a "learning system" at my university, I have found that I cannot open a new tab with the same site open. When I do so, somehow the site is aware and displays the following message?

How on earth does the site know what tabs I have open on my computer? As far as I know, the front-end code shouldn't have any access to my private browser information. What accessible information could this site be using to determine that I have another tab open already?
I am accessing the site using a private computer, and the site being accessed isn't on a local network, it is being accessed through the internet. Therefore there is no internal monitoring software that could be causing this. I am using Google Chrome 24 Beta for Mac.

A: One way to do this is via cookies and ids. Firstly, you are logged in to the site and have a session on there. This is managed using cookies; whenever you visit a page on the site, your browser will send a cookie which normally contains some kind of id. That way the server can identify any request coming from you, is really from you. So, in this case, both your original tab and your new tab will send the same cookie.
Secondly, it can also add another, different id (call it the page id), to any link or form you submit on the site. So a form on a page might contain the id 1234, and any links will also contain that id. Each new page you visit might contain a new id. So at any point, the site knows that next request from your browser (identified by the cookies) should also contain this other id. If you navigate around the site in a normal way, clicking on links, submitting forms, this will be true and all will be good.
Cases when your next request would NOT submit the expected, second id are:

*

*you hit the back button (you would be sending an old page id)

*you open a new tab (this depends on the browser, but if it opens the
same page you are already on in the original tab, it would be sending the current page
id, not the next page id, which the server expects)

Either way, you send a request with a page id the server doesn't expect and it can make a best guess as to what you did.

A: They track your mouse cursor movement while visiting their website. It's a great way to get the attention of a visitor. They put some query programmatically when you move your mouse and when you wish to close.
It's good UX.

A: Another way the site may know that you have another tab open is through broadcasting channels. To put it simply, broadcasting channels are a means for windows, tabs, etc; to communicate (correct me if I am wrong). Here is a simple implementation:
//Channel to post and receive messages from
const bc = new BroadcastChannel("Check-tabs");

//On message receive
bc.onmessage = (event) => {
  if (event.data === `First tab?`) {

    //Post that there is already a tab open
    bc.postMessage(`Tab already open`);
  }

  //Check if a tab is open
  if (event.data === `Tab already open`) {
    alert(`Another tab is already open.`);
  }

//Posts message to check whether another tab is open
bc.postMessage(`First tab?`);


text:
Q: What was the communication protocol used on board the Apollo moon lander? It seems that the development of TTL was contemporary ~1961 the maiden moon landing of the Apollo vehicle, while the development of one of the oldest digital signalling standards RS232 using the UART hardware was crystallized later, and that of the advent of the USB hardware, transmission standard and related communication protocols occurred much later.

What was the communication protocol used on the controllers and processers on board the Apollo lander vehicle?

A: Dig in here: ftp://ssh.esac.esa.int/pub/ekuulker/Apollo15/The-Apollo-Guidance-Computer-Architecture-and-Operation.pdf
And here: https://arstechnica.com/science/2020/01/a-deep-dive-into-the-apollo-guidance-computer-and-the-hack-that-saved-apollo-14/3/
tl; dr: a bespoke binary stream format for telemetry uplink and downlink.

A: Encoding of characters into digital data streams is rather older than Apollo. Émile Baudot's system was patented in 1874, about the time when Jules Verne was writing of the US sending a ship to the moon in the immediate postbellum period.
The USB communication system used for the Apollo mission integrated a bunch of different data and analog streams. Digital commands were encoded with many extra bits so that errors would be detected with a probability of erroneous decoding of \$ \lt 10^{-9}\$. Redundancy and fail-over modes of operation were strong concerns.
Here, for example, from this document is the LEM (Lunar Excursion Module) down link summary:

Terrestrial communication (to remote base stations) used Western Electric 2400 baud modems.
There is quite a bit of fascinating information in that overview document, including a brief description of the console displays which used special data display CRTs with both magnetic and electrostatic deflection (the latter for vector character generation).


text:
Q: tf.browser.fromPixels() not working because "DOM is not ready yet" I'm trying to play with TensorFlow.js's tf.browser.fromPixels() function. Unfortunately, I get the following error:
backend_webgl.ts:309 Uncaught Error: The DOM is not ready yet. Please call tf.browser.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object
    at e.fromPixels (backend_webgl.ts:309)
    at t.fromPixels (engine.ts:870)
    at fromPixels_ (browser.ts:55)
    at Object.fromPixels (operation.ts:45)
    at ex4.html:10

But I'm calling tf.browser.fromPixels() from inside a function passed to window.addEventListener('DOMContentLoaded', ...). Any idea why I'm getting this error and how to get the fromPixels function to work?

<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.2.7/dist/tf.min.js"></script>
</head>
<body>
    <img id="test" src="https://jpeg.org/images/jpeg-home.jpg">
    <script>
        window.addEventListener('DOMContentLoaded', ev => {
            const img = document.getElementById('test')
            tf.browser.fromPixels(img).print()
        })
    </script>
</body>
</html>

A:         if (document.readyState !== 'complete') {
          throw new Error(
              'The DOM is not ready yet. Please call ' +
              'tf.browser.fromPixels() once the DOM is ready. One way to ' +
              'do that is to add an event listener for `DOMContentLoaded` ' +
              'on the document object');
        }

Github tensorflow/tfjs
According to the code above, the error is thrown because document.readyState isn't complete.

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
  https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
The readyState of a document can be one of following:
loading
  The document is still loading.
interactive
  The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.
complete
  The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.
https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState

DOMContentLoaded is called before any sub-resources aren't loaded yet.So At the time of your code is executed, document.readyState is still interactive.
Just ignore what the error says and try load event listener instead.


text:
Q: Running multiple dependent apps each with their own docker compose file I have two apps that I would like to somehow combine with docker and docker compose. The apps are:
API
This I have been able to get running on docker.
Consists of the following containers: Web (rails app), postgres, and redis.
Scraping app
This app scrapes other websites, makes sure the data is consistent, and sends it to the API. This is the app I dunno how to get running on docker.
Its a node app and would consist of the following containers: Web (sails app), mongodb, redis, the API.
My question is if its possible to write the Dockerfile or docker-compose.yml file for the scraping app such that it is linked to the API app, which itself is linked to at least two other containers. Or do I have to manually boot the API app before booting the scraping app?


text:
Q: How to re-run only failed JUnit test classes using Gradle? Inspired by this neat TestNG task, and this SO question I thought I'd whip up something quick for re-running of only failed JUnit tests from Gradle.
But after searching around for awhile, I couldn't find anything analogous which was quite as convenient.
I came up with the following, which seems to work pretty well and adds a <testTaskName>Rerun task for each task of type Test in my project.
import static groovy.io.FileType.FILES

import java.nio.file.Files
import java.nio.file.Paths

// And add a task for each test task to rerun just the failing tests
subprojects {
    afterEvaluate { subproject ->
        // Need to store tasks in static temp collection, else new tasks will be picked up by live collection leading to StackOverflow
        def testTasks = subproject.tasks.withType(Test)
        testTasks.each { testTask ->
            task "${testTask.name}Rerun"(type: Test) {
                group = 'Verification'
                description = "Re-run ONLY the failing tests from the previous run of ${testTask.name}."

                // Depend on anything the existing test task depended on
                dependsOn testTask.dependsOn

                // Copy runtime setup from existing test task
                testClassesDirs = testTask.testClassesDirs
                classpath = testTask.classpath

                // Check the output directory for failing tests
                File textXMLDir = subproject.file(testTask.reports.junitXml.destination)
                logger.info("Scanning: $textXMLDir for failed tests.")

                // Find all failed classes
                Set<String> allFailedClasses = [] as Set
                if (textXMLDir.exists()) {
                    textXMLDir.eachFileRecurse(FILES) { f ->
                        // See: http://marxsoftware.blogspot.com/2015/02/determining-file-types-in-java.html
                        String fileType
                        try {
                            fileType = Files.probeContentType(f.toPath())
                        } catch (IOException e) {
                            logger.debug("Exception when probing content type of: $f.")
                            logger.debug(e)

                            // Couldn't determine this to be an XML file.  That's fine, skip this one.
                            return
                        }

                        logger.debug("Filetype of: $f is $fileType.")

                        if (['text/xml', 'application/xml'].contains(fileType)) {
                            logger.debug("Found testsuite file: $f.")

                            def testSuite = new XmlSlurper().parse(f)
                            def failedTestCases = testSuite.testcase.findAll { testCase ->
                                testCase.children().find { it.name() == 'failure' }
                            }

                            if (!failedTestCases.isEmpty()) {
                                logger.info("Found failures in file: $f.")
                                failedTestCases.each { failedTestCase ->
                                    def className = failedTestCase['@classname']
                                    logger.info("Failure: $className")
                                    allFailedClasses << className.toString()
                                }
                            }
                        }
                    }
                }

                if (!allFailedClasses.isEmpty()) {
                    // Re-run all tests in any class with any failures
                    allFailedClasses.each { c ->
                        def testPath = c.replaceAll('\\.', '/') + '.class'
                        include testPath
                    }

                    doFirst {
                        logger.warn('Re-running the following tests:')
                        allFailedClasses.each { c ->
                            logger.warn(c)
                        }
                    }
                }

                outputs.upToDateWhen { false } // Always attempt to re-run failing tests
                // Only re-run if there were any failing tests, else just print warning
                onlyIf {
                    def shouldRun = !allFailedClasses.isEmpty()
                    if (!shouldRun) {
                        logger.warn("No failed tests found for previous run of task: ${subproject.path}:${testTask.name}.")
                    }

                    return shouldRun
                }
            }
        }
    }
}

Is there any easier way to do this from Gradle?  Is there any way to get JUnit to output a consolidated list of failures somehow so I don't have to slurp the XML reports?
I'm using JUnit 4.12 and Gradle 4.5.

A: Here is one way to do it. The full file will be listed at the end, and is available here.
Part one is to write a small file (called failures) for every failed test:
test {
    // `failures` is defined elsewhere, see below
    afterTest { desc, result ->
        if ("FAILURE" == result.resultType as String) {
            failures.withWriterAppend {
                it.write("${desc.className},${desc.name}\n")
            }
        }
    }
}

In part two, we use a test filter (doc here) to restrict the tests to any that are present in the failures file:
def failures = new File("${projectDir}/failures.log")
def failedTests = []
if (failures.exists()) {
    failures.eachLine { line ->
        def tokens = line.split(",")
        failedTests << tokens[0]
    }
}
failures.delete()

test {
    filter {
        failedTests.each {
            includeTestsMatching "${it}"
        }
    }
    // ...
}

The full file is:
apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    testCompile('junit:junit:4.12')
}

def failures = new File("${projectDir}/failures.log")
def failedTests = []
if (failures.exists()) {
    failures.eachLine { line ->
        def tokens = line.split(",")
        failedTests << tokens[0]
    }
}
failures.delete()

test {
    filter {
        failedTests.each {
            includeTestsMatching "${it}"
        }
    }

    afterTest { desc, result ->
        if ("FAILURE" == result.resultType as String) {
            failures.withWriterAppend {
                it.write("${desc.className},${desc.name}\n")
            }
        }
    }
}

A: The Test Retry Gradle plugin is designed to do exactly this.  It will rerun each failed test a certain number of times, with the option of failing the build if too many failures have occurred overall.
plugins {
    id 'org.gradle.test-retry' version '1.2.1'
}

test {
    retry {
        maxRetries = 3
        maxFailures = 20 // Optional attribute
    }
}


text:
Q: use videojs plugins in react Video JS As doc mentioned I ve initialized video js in react by doing something like this ...
    import React from 'react';
    import videojs from 'video.js'

    export default class VideoPlayer extends React.Component {
      componentDidMount() {
        // instantiate video.js
        this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
          console.log('onPlayerReady', this)
        });
      }

      // destroy player on unmount
      componentWillUnmount() {
        if (this.player) {
          this.player.dispose()
        }
      }

      // wrap the player in a div with a `data-vjs-player` attribute
      // so videojs won't create additional wrapper in the DOM
      // see https://github.com/videojs/video.js/pull/3856
      render() {
        return (
          <div data-vjs-player>
            <video ref={ node => this.videoNode = node } className="video-js"></video>
          </div>
        )
      }
    }

I want to integrate VideoJs Overlay plugin in this...
so i ve done something like this...
import React from 'react';
import videojs from 'video.js'

export default class VideoPlayer extends React.Component {
  componentDidMount() {
    // instantiate video.js
    this.player = videojs(this.videoNode, this.props, function onPlayerReady() {

player.overlay({
            content: 'Default overlay content',
            debug: true,
            overlays: [{
              content: 'The video is playing!',
              start: 'play',
              end: 'pause'
            }, {
              start: 0,
              end: 15,
              align: 'bottom-left'
            }, {
              start: 15,
              end: 30,
              align: 'bottom'
            }, {
              start: 30,
              end: 45,
              align: 'bottom-right'
            }, {
              start: 20,
              end: 'pause'
            }]
          });
            });
      }

  // destroy player on unmount
  componentWillUnmount() {
    if (this.player) {
      this.player.dispose()
    }
  }

  render() {
    return (
      <div data-vjs-player>
        <video ref={ node => this.videoNode = node } className="video-js" id="videojs-overlay-player"></video>
      </div>
    )
  }
}

While doing this it give me error like player.overlay is not function...
and if i do     videojs.registerPlugin('overlay', overlay);
and call overlay function it gives me error like component Overlay is undefined
How to workout videojs plugins in react way????

A: You need to import videojs-overlay package before you use it.
Follow these steps :

*

*Install the plugin: npm i videojs-overlay --save

*Import the package in Player class : import overlay from 'videojs-overlay';

*Register the plugin before instantiating the player: videojs.registerPlugin('overlay', overlay);
Then, player.overlay({... will work as intended.