问:
How to hide a text and make it accessible by screen reader?
I have a simple text that gets updated on an action and I want that to be announced by the screen reader. But I don't want that text to be visible on the web page. I tried display: none and visibility: hidden, but seems like they are not accessible by the screen reader softwares. I found a way to make this work - that is by absolute positioning the element all the way with negative 999999 value which will make it off screen and hidden from the webpage. I am not really a fan of this solution. Is there a more elegant way to achieve this?

```<code><span class="aria-invisible" aria-live="polite">5 selections have been made.</span>

.aria-invisible {
   display: none; //either of these two attributes
   visibility: hidden;
}
</code>```

答:
A better solution to the bootstrap "sr-only" class.

There are numerous problems with the Bootstrap "sr-only" class.

First of all you will see from this discussion that a negative margin can cause issues on VoiceOver.

Secondly you must account for words wrapping one per line as screen readers do not read line breaks

Finally clip has been deprecated.

To fix point 1 simply don't add a negative margin.

To fix point 2 add white-space: no-wrap to ensure words do not end up 'one per line' and cause words to get smushed together.

To fix point 3 we add clip-path: inset(50%) as this clips to a 0px square, we keep clip as at the moment this has great coverage, clip-path is used to future-proof your solution.

Please find below a much more robust class, as of yet I have not found a screen reader / browser combo that does not work as expected with this.

I have this class on a few different forums being tested, so far so good but if someone can find a problem with it please let me know as I will be submitting it everywhere.

.visually-hidden {
    border: 0;
    padding: 0;
    margin: 0;
    position: absolute !important;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
    clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */
    clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/
    white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>visible text <span class="visually-hidden">hidden text</span></p></code>```

Body:
I have a simple text that gets updated on an action and I want that to be announced by the screen reader. But I don't want that text to be visible on the web page. I tried display: none and visibility: hidden, but seems like they are not accessible by the screen reader softwares. I found a way to make this work - that is by absolute positioning the element all the way with negative 999999 value which will make it off screen and hidden from the webpage. I am not really a fan of this solution. Is there a more elegant way to achieve this?

5 selections have been made.

.aria-invisible {
   display: none; //either of these two attributes
   visibility: hidden;
}

Body:
A better solution to the bootstrap "sr-only" class.

There are numerous problems with the Bootstrap "sr-only" class.

First of all you will see from this discussion that a negative margin can cause issues on VoiceOver.

Secondly you must account for words wrapping one per line as screen readers do not read line breaks

Finally clip has been deprecated.

To fix point 1 simply don't add a negative margin.

To fix point 2 add white-space: no-wrap to ensure words do not end up 'one per line' and cause words to get smushed together.

To fix point 3 we add clip-path: inset(50%) as this clips to a 0px square, we keep clip as at the moment this has great coverage, clip-path is used to future-proof your solution.

Please find below a much more robust class, as of yet I have not found a screen reader / browser combo that does not work as expected with this.

I have this class on a few different forums being tested, so far so good but if someone can find a problem with it please let me know as I will be submitting it everywhere.

.visually-hidden {
    border: 0;
    padding: 0;
    margin: 0;
    position: absolute !important;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
    clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */
    clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/
    white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */
}

<p>visible text <span class="visually-hidden">hidden text</span></p>


来源: stackexchange

问:
Visual Studio UML Sequence Diagram
I was wondering if there was a Sequence Diagram generator for C#?

Im using Visual Studio 2008 Professional.

If not is there a quick and simple software?

Im finding Enterprise Architect and Visio a bit too cryptic for a beginner.

I have found the Class Diagram feature on Visual Studio, which s very useful and am hoping for a equally useful simple program to generate Sequence Diagrams.

Thanks.

答:
Well, if you ever choose to install VS2010 and would still like to create a sequence diagram from code:

1.  Open the source code of the method that you would like to generate from it the sequence diagram.

2.  Press the right mouse button on the method body and select ‘Generate Sequence Diagram’.

If you have a special folder for sequence diagrams:
3.  Deselect the ‘Add diagram to current project’.
4.  Save the diagram in right location (Sequence Diagrams) and add it to the Source Control. (We're working with TFS).

ContentLicense: CC BY-SA 2.5

Title: Visual Studio UML Sequence Diagram

ContentLicense: CC BY-SA 3.0


问:
Search in an ArrayList C#
```<code>class EmployeeDAL
{
    private ArrayList _employees;

    public EmployeeDAL()
    {
        _employees = new ArrayList();
        _employees.Add(new Employee { EmployeeID = 1, EmployeeName = "Ram", Salary = 50000 });
        _employees.Add(new Employee { EmployeeID = 2, EmployeeName = "Sahaym", Salary = 40000 });
        _employees.Add(new Employee { EmployeeID = 3, EmployeeName = "Gopi", Salary = 55000 });
        _employees.Add(new Employee { EmployeeID = 4, EmployeeName = "Prakash", Salary = 45000 });
        _employees.Add(new Employee { EmployeeID = 5, EmployeeName = "Dheeraj", Salary = 60000 });
        _employees.Add(new Employee { EmployeeID = 6, EmployeeName = "Shibhu", Salary = 50000 });
    }

    public bool DeleteEmployee(int id)
    {
        if (_employees.Contains(id))
        {
            _employees.Remove(id);
            return true;
        }
        else
            return false;
    }
}
</code>```

I want to delete an employee with specific id using DeleteEmployee(id) method. How can I do this in ArrayList ?

答:
Forgive the crudeness of my code.  But, sample of using a List follows:</p>

```<code>using System;
using System.Collections.Generic;
using Gtk;

public partial class MainWindow : Gtk.Window
{
    public class Employee
    {
        public int EmployID;
        public string EmployeeName;
        public int Salary;

        public Employee(int v1, string v2, int v3)
        {
            this.EmployID = v1;
            this.EmployeeName = v2;
            this.Salary = v3;
        }
    }

    public class Employees
    {
        public List<Employee> employees = null;

        public bool Delete(int inID)
        {
            Employee buffer = employees.Find(x => x.EmployID == inID);
            if (buffer != null)
            {
                employees.Remove(buffer);
                return true;
            }

            return false;
        }
    }

    public Employees Listof = new Employees();

    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();

        Listof.employees = new List<Employee>()
        {
            new Employee(1, "Ram", 50000),
            new Employee(2, "Sahaym", 40000),
            new Employee(3, "Gopi", 55000),
            new Employee(4, "Prakash", 45000),
            new Employee(5, "Dheeraj", 60000),
            new Employee(6, "Shibhu", 50000)
        };

        label1.Text = "Employee Count: " + Listof.employees.Count.ToString();
    }

    protected void OnDeleteEvent(object sender, DeleteEventArgs a)
    {
        Application.Quit();
        a.RetVal = true;
    }

    protected void OnButton3Pressed(object sender, EventArgs e)
    {
        label1.Text = $"Deleted Employee 3 successful : {Listof.Delete(3)}" +
            " Employee Count: " + Listof.employees.Count.ToString();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Search in an ArrayList C#

Body:
class EmployeeDAL
{
    private ArrayList _employees;

    public EmployeeDAL()
    {
        _employees = new ArrayList();
        _employees.Add(new Employee { EmployeeID = 1, EmployeeName = "Ram", Salary = 50000 });
        _employees.Add(new Employee { EmployeeID = 2, EmployeeName = "Sahaym", Salary = 40000 });
        _employees.Add(new Employee { EmployeeID = 3, EmployeeName = "Gopi", Salary = 55000 });
        _employees.Add(new Employee { EmployeeID = 4, EmployeeName = "Prakash", Salary = 45000 });
        _employees.Add(new Employee { EmployeeID = 5, EmployeeName = "Dheeraj", Salary = 60000 });
        _employees.Add(new Employee { EmployeeID = 6, EmployeeName = "Shibhu", Salary = 50000 });
    }

    public bool DeleteEmployee(int id)
    {
        if (_employees.Contains(id))
        {
            _employees.Remove(id);
            return true;
        }
        else
            return false;
    }
}

I want to delete an employee with specific id using DeleteEmployee(id) method. How can I do this in ArrayList ?

Body:
Forgive the crudeness of my code.  But, sample of using a List follows:

using System;
using System.Collections.Generic;
using Gtk;

public partial class MainWindow : Gtk.Window
{
    public class Employee
    {
        public int EmployID;
        public string EmployeeName;
        public int Salary;

        public Employee(int v1, string v2, int v3)
        {
            this.EmployID = v1;
            this.EmployeeName = v2;
            this.Salary = v3;
        }
    }

    public class Employees
    {
        public List<Employee> employees = null;

        public bool Delete(int inID)
        {
            Employee buffer = employees.Find(x => x.EmployID == inID);
            if (buffer != null)
            {
                employees.Remove(buffer);
                return true;
            }

            return false;
        }
    }

    public Employees Listof = new Employees();

    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();

        Listof.employees = new List<Employee>()
        {
            new Employee(1, "Ram", 50000),
            new Employee(2, "Sahaym", 40000),
            new Employee(3, "Gopi", 55000),
            new Employee(4, "Prakash", 45000),
            new Employee(5, "Dheeraj", 60000),
            new Employee(6, "Shibhu", 50000)
        };

        label1.Text = "Employee Count: " + Listof.employees.Count.ToString();
    }

    protected void OnDeleteEvent(object sender, DeleteEventArgs a)
    {
        Application.Quit();
        a.RetVal = true;
    }

    protected void OnButton3Pressed(object sender, EventArgs e)
    {
        label1.Text = $"Deleted Employee 3 successful : {Listof.Delete(3)}" +
            " Employee Count: " + Listof.employees.Count.ToString();
    }


问:
ARM Thumb BL instruction loops to itself
I'm trying to assemble this code using Keystone and execute it with the Unicorn engine:

```<code>start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start
</code>```

In my opinion, the bl instruction should save the address of the next instruction to the lr register and then jump to start. So it'll be an infinite loop that adds 1 to r0 and 2 to r1.

Apparently, I'm wrong, because bl start branches to itself instead!

I'm using Python wrappers for Keystone, Capstone and Unicorn to process the assembly. Here's my code:

```<code>import keystone as ks
import capstone as cs
import unicorn as uc

print(f'Keystone {ks.__version__}\nCapstone {cs.__version__}\nUnicorn {uc.__version__}\n')

code = '''
start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start
'''

assembler = ks.Ks(ks.KS_ARCH_ARM, ks.KS_MODE_THUMB)
disassembler = cs.Cs(cs.CS_ARCH_ARM, cs.CS_MODE_THUMB)
emulator = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_THUMB)

machine_code, _ = assembler.asm(code)
machine_code = bytes(machine_code)
print(machine_code.hex())

initial_address = 0
for addr, size, mnem, op_str in disassembler.disasm_lite(machine_code, initial_address):
    instruction = machine_code[addr:addr + size]
    print(f'{addr:04x}|\t{instruction.hex():<8}\t{mnem:<5}\t{op_str}')

emulator.mem_map(initial_address, 1024)  # allocate 1024 bytes of memory
emulator.mem_write(initial_address, machine_code)  # write the machine code
emulator.hook_add(uc.UC_HOOK_CODE, lambda uc, addr, size, _: print(f'Address: {addr}'))
emulator.emu_start(initial_address | 1, initial_address + len(machine_code), timeout=500)
</code>```

This is what it outputs:

```<code>Keystone 0.9.1
Capstone 5.0.0
Unicorn 1.0.2

00f1010001f10201fff7fefff8e7
0000|   00f10100    add.w   r0, r0, #1
0004|   01f10201    add.w   r1, r1, #2
0008|   fff7feff    bl      #8         ; why not `bl #0`?
000c|   f8e7        b       #0
Address: 0
Address: 4
Address: 8  # OK, we arrived at BL start
Address: 8  # we're at the same instruction again?
Address: 8  # and again?
Address: 8
< ... >
Address: 8
Address: 8
Traceback (most recent call last):
  File "run_ARM_bug.py", line 32, in <module>
    emulator.emu_start(initial_address | 1, initial_address + len(machine_code), timeout=500)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/unicorn-1.0.2rc3-py3.7.egg/unicorn/unicorn.py", line 317, in emu_start
unicorn.unicorn.UcError: Emulation timed out (UC_ERR_TIMEOUT)
</code>```

The exception is not a problem (I set the timeout myself). The problem is that bl start always jumps to itself instead of start.

If I jump forward, however, everything will work as expected, so this works - bl jumps to the correct address:

```<code>start:
    ; stuff
    bl next
    ; hello

next:
    add r0, r0, #1
    bkpt
</code>```

EDIT

I went on and assembled this code with Clang:

```<code>; test.s

.text
.syntax unified
.globl  start
.p2align    1
.code   16
.thumb_func
start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start
</code>```

Used the following commands:

```<code>$ clang -c test.s -target armv7-unknown-linux -o test.bin -mthumb
clang-11: warning: unknown platform, assuming -mfloat-abi=soft
</code>```

And then disassembled test.bin with objdump:

```<code>$ objdump -d test.bin

test.bin:       file format elf32-littlearm

Disassembly of section .text:

00000000 <start>:
       0: 00 f1 01 00                   add.w   r0, r0, #1
       4: 01 f1 02 01                   add.w   r1, r1, #2
       8: ff f7 fe ff                   bl      #-4
       c: ff f7 fe bf                   b.w     #-4 <start+0x10>
$
</code>```

So bl's argument is actually an offset. It's negative because we're going backwards. BUT, as the documentation says:

For B, BL, CBNZ, and CBZ instructions, the value of the PC is the address of the current instruction plus 4 bytes.

So bl #-4 will jump to (the address of bl) + 4 bytes - 4 bytes, or, in other words, itself, again!

So, I can't bl backwards for some reason? What's happening here and how to fix it?

答:
All tool "chain" linkers have to deal with function calls or other to external resources, you will see instructions like bl encoded as a branch to self or branch to zero or some such incomplete instruction (certainly for external labels).  The tangent here is that some versions of clang appear to sometimes encode for a local address and sometimes not (at the assembler level).  But when linked the offset/address is patched up (as in this case).

A generic clang (all targets, default x86 host) 3.7 at the object level gives the right instruction.  3.8 doesn't. That appears to be the time this change happened.  Clang 10 generic doesn't but a hand built clang 10.0.0 specific to one target, does give the right answer at assemble time.

All of this is a tangent because that is at assembly time not final output.  When linked you get the right answer (thus far, the OP may have other cases where it didn't).

```<code>.thumb
.syntax unified
.thumb_func
start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start

clang-3.8 -c so.s -target armv7-unknown-linux -o so.o
clang: warning: unknown platform, assuming -mfloat-abi=soft
arm-none-eabi-objdump -D so.o

so.o:     file format elf32-littlearm

Disassembly of section .text:

00000000 <start>:
   0:   f100 0001   add.w   r0, r0, #1
   4:   f101 0102   add.w   r1, r1, #2
   8:   f7ff fffe   bl  0 <start>
   c:   e7f8        b.n 0 <start>
</code>```

bl here is a branch to self, incomplete.

But take that object and link it

```<code>arm-none-eabi-ld -Ttext=0 so.o -o so.elf
arm-none-eabi-ld: warning: cannot find entry symbol _start; defaulting to 0000000000000000
arm-none-eabi-objdump -d so.elf

so.elf:     file format elf32-littlearm

Disassembly of section .text:

00000000 <start>:
   0:   f100 0001   add.w   r0, r0, #1
   4:   f101 0102   add.w   r1, r1, #2
   8:   f7ff fffa   bl  0 <start>
   c:   e7f8        b.n 0 <start>
</code>```

And you get the correct answer.

Sorry for the misleading answer before I was off on a tangent there for a bit.

Now if linking doesn't fix it for you in all cases then, please comment.

Another part of the problem here is the tools not helping you:

```<code>0008|   fff7feff    bl      #8         ; why not `bl #0`?

8: ff f7 fe ff                   bl      #-4
</code>```

This is the same instruction formerly pair of thumb instructions 0xF7FF, 0xFFFE but for armv7-ar it is considered one instruction, inseparable
0xF7FFFFFE.

Thanks to looking this up again to work on this question I found this out since I either knew it and forgot or didn't know.

Before ARMv6T2, J1 and J2 in encodings T1 and T2 were both 1, resulting in a smaller branch range. The instructions could be executed as two separate 16-bit instructions

I have demonstrated the two instructions being separate from each other on prior to armv7 architectures and showing they are not one instruction.

Anyway:

Same instruction as this from gnu

```<code>   8:   f7ff fffe   bl  0 <start>
</code>```

The gnu one is a little better but still has issues, the encoding is not bl 0 <start> but that output indicates the ultimate desire and in the end is re-encoded to be correct when linked.

So the tools were also likely part of the problem understanding what is going on by not representing the machine code in a properly decodable format.

Body:
I'm trying to assemble this code using Keystone and execute it with the Unicorn engine:

start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start

In my opinion, the bl instruction should save the address of the next instruction to the lr register and then jump to start. So it'll be an infinite loop that adds 1 to r0 and 2 to r1.

Apparently, I'm wrong, because bl start branches to itself instead!

I'm using Python wrappers for Keystone, Capstone and Unicorn to process the assembly. Here's my code:

import keystone as ks
import capstone as cs
import unicorn as uc

print(f'Keystone {ks.__version__}\nCapstone {cs.__version__}\nUnicorn {uc.__version__}\n')

code = '''
start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start
'''

assembler = ks.Ks(ks.KS_ARCH_ARM, ks.KS_MODE_THUMB)
disassembler = cs.Cs(cs.CS_ARCH_ARM, cs.CS_MODE_THUMB)
emulator = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_THUMB)

machine_code, _ = assembler.asm(code)
machine_code = bytes(machine_code)
print(machine_code.hex())

initial_address = 0
for addr, size, mnem, op_str in disassembler.disasm_lite(machine_code, initial_address):
    instruction = machine_code[addr:addr + size]
    print(f'{addr:04x}|\t{instruction.hex():<8}\t{mnem:<5}\t{op_str}')

emulator.mem_map(initial_address, 1024)  # allocate 1024 bytes of memory
emulator.mem_write(initial_address, machine_code)  # write the machine code
emulator.hook_add(uc.UC_HOOK_CODE, lambda uc, addr, size, _: print(f'Address: {addr}'))
emulator.emu_start(initial_address | 1, initial_address + len(machine_code), timeout=500)

This is what it outputs:

Keystone 0.9.1
Capstone 5.0.0
Unicorn 1.0.2

00f1010001f10201fff7fefff8e7
0000|   00f10100    add.w   r0, r0, #1
0004|   01f10201    add.w   r1, r1, #2
0008|   fff7feff    bl      #8         ; why not `bl #0`?
000c|   f8e7        b       #0
Address: 0
Address: 4
Address: 8  # OK, we arrived at BL start
Address: 8  # we're at the same instruction again?
Address: 8  # and again?
Address: 8
< ... >
Address: 8
Address: 8
Traceback (most recent call last):
  File "run_ARM_bug.py", line 32, in <module>
    emulator.emu_start(initial_address | 1, initial_address + len(machine_code), timeout=500)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/unicorn-1.0.2rc3-py3.7.egg/unicorn/unicorn.py", line 317, in emu_start
unicorn.unicorn.UcError: Emulation timed out (UC_ERR_TIMEOUT)

The exception is not a problem (I set the timeout myself). The problem is that bl start always jumps to itself instead of start.

If I jump forward, however, everything will work as expected, so this works - bl jumps to the correct address:

start:
    ; stuff
    bl next
    ; hello

next:
    add r0, r0, #1
    bkpt

EDIT

I went on and assembled this code with Clang:

; test.s

.text
.syntax unified
.globl  start
.p2align    1
.code   16
.thumb_func
start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start

Used the following commands:

$ clang -c test.s -target armv7-unknown-linux -o test.bin -mthumb
clang-11: warning: unknown platform, assuming -mfloat-abi=soft

And then disassembled test.bin with objdump:

$ objdump -d test.bin

test.bin:       file format elf32-littlearm

Disassembly of section .text:

00000000 <start>:
       0: 00 f1 01 00                   add.w   r0, r0, #1
       4: 01 f1 02 01                   add.w   r1, r1, #2
       8: ff f7 fe ff                   bl      #-4
       c: ff f7 fe bf                   b.w     #-4 <start+0x10>
$

So bl's argument is actually an offset. It's negative because we're going backwards. BUT, as the documentation says:

For B, BL, CBNZ, and CBZ instructions, the value of the PC is the address of the current instruction plus 4 bytes.

So bl #-4 will jump to (the address of bl) + 4 bytes - 4 bytes, or, in other words, itself, again!

So, I can't bl backwards for some reason? What's happening here and how to fix it?

Body:
All tool "chain" linkers have to deal with function calls or other to external resources, you will see instructions like bl encoded as a branch to self or branch to zero or some such incomplete instruction (certainly for external labels).  The tangent here is that some versions of clang appear to sometimes encode for a local address and sometimes not (at the assembler level).  But when linked the offset/address is patched up (as in this case).

A generic clang (all targets, default x86 host) 3.7 at the object level gives the right instruction.  3.8 doesn't. That appears to be the time this change happened.  Clang 10 generic doesn't but a hand built clang 10.0.0 specific to one target, does give the right answer at assemble time.

All of this is a tangent because that is at assembly time not final output.  When linked you get the right answer (thus far, the OP may have other cases where it didn't).

.thumb
.syntax unified
.thumb_func
start:
    add r0, r0, #1
    add r1, r1, #2
    bl start
    b start

clang-3.8 -c so.s -target armv7-unknown-linux -o so.o
clang: warning: unknown platform, assuming -mfloat-abi=soft
arm-none-eabi-objdump -D so.o

so.o:     file format elf32-littlearm

Disassembly of section .text:

00000000 <start>:
   0:   f100 0001   add.w   r0, r0, #1
   4:   f101 0102   add.w   r1, r1, #2
   8:   f7ff fffe   bl  0 <start>
   c:   e7f8        b.n 0 <start>

bl here is a branch to self, incomplete.

But take that object and link it

arm-none-eabi-ld -Ttext=0 so.o -o so.elf
arm-none-eabi-ld: warning: cannot find entry symbol _start; defaulting to 0000000000000000
arm-none-eabi-objdump -d so.elf

so.elf:     file format elf32-littlearm

Disassembly of section .text:

00000000 <start>:
   0:   f100 0001   add.w   r0, r0, #1
   4:   f101 0102   add.w   r1, r1, #2
   8:   f7ff fffa   bl  0 <start>
   c:   e7f8        b.n 0 <start>

And you get the correct answer.

Sorry for the misleading answer before I was off on a tangent there for a bit.

Now if linking doesn't fix it for you in all cases then, please comment.

Another part of the problem here is the tools not helping you:

0008|   fff7feff    bl      #8         ; why not `bl #0`?

8: ff f7 fe ff                   bl      #-4

This is the same instruction formerly pair of thumb instructions 0xF7FF, 0xFFFE but for armv7-ar it is considered one instruction, inseparable
0xF7FFFFFE.

Thanks to looking this up again to work on this question I found this out since I either knew it and forgot or didn't know.

Before ARMv6T2, J1 and J2 in encodings T1 and T2 were both 1, resulting in a smaller branch range. The instructions could be executed as two separate 16-bit instructions

I have demonstrated the two instructions being separate from each other on prior to armv7 architectures and showing they are not one instruction.

Anyway:

Same instruction as this from gnu

   8:   f7ff fffe   bl  0 <start>

The gnu one is a little better but still has issues, the encoding is not bl 0 <start> but that output indicates the ultimate desire and in the end is re-encoded to be correct when linked.

So the tools were also likely part of the problem understanding what is going on by not representing the machine code in a properly decodable format.


问:
How do I add a new column to a Spark DataFrame (using PySpark)?
I have a Spark DataFrame (using PySpark 1.5.1) and would like to add a new column.

I've tried the following without any success:

```<code>type(randomed_hours) # => list

# Create in Python and transform to RDD

new_col = pd.DataFrame(randomed_hours, columns=['new_col'])

spark_new_col = sqlContext.createDataFrame(new_col)

my_df_spark.withColumn("hours", spark_new_col["new_col"])
</code>```

Also got an error using this:

```<code>my_df_spark.withColumn("hours",  sc.parallelize(randomed_hours))
</code>```

So how do I add a new column (based on Python vector) to an existing DataFrame with PySpark?

答:
There are multiple ways we can add a new column in pySpark.

Let's first create a simple DataFrame.

```<code>date = [27, 28, 29, None, 30, 31]
df = spark.createDataFrame(date, IntegerType())
</code>```

Now let's try to double the column value and store it in a new column. PFB few different approaches to achieve the same.

```<code># Approach - 1 : using withColumn function
df.withColumn("double", df.value * 2).show()

# Approach - 2 : using select with alias function.
df.select("*", (df.value * 2).alias("double")).show()

# Approach - 3 : using selectExpr function with as clause.
df.selectExpr("*", "value * 2 as double").show()

# Approach - 4 : Using as clause in SQL statement.
df.createTempView("temp")
spark.sql("select *, value * 2 as double from temp").show()
</code>```

For more examples and explanation on spark DataFrame functions, you can visit my blog.

I hope this helps.

Body:
I have a Spark DataFrame (using PySpark 1.5.1) and would like to add a new column.

I've tried the following without any success:

type(randomed_hours) # => list

# Create in Python and transform to RDD

new_col = pd.DataFrame(randomed_hours, columns=['new_col'])

spark_new_col = sqlContext.createDataFrame(new_col)

my_df_spark.withColumn("hours", spark_new_col["new_col"])

Also got an error using this:

my_df_spark.withColumn("hours",  sc.parallelize(randomed_hours))

So how do I add a new column (based on Python vector) to an existing DataFrame with PySpark?

Body:
There are multiple ways we can add a new column in pySpark.

Let's first create a simple DataFrame.

date = [27, 28, 29, None, 30, 31]
df = spark.createDataFrame(date, IntegerType())

Now let's try to double the column value and store it in a new column. PFB few different approaches to achieve the same.

# Approach - 1 : using withColumn function
df.withColumn("double", df.value * 2).show()

# Approach - 2 : using select with alias function.
df.select("*", (df.value * 2).alias("double")).show()

# Approach - 3 : using selectExpr function with as clause.
df.selectExpr("*", "value * 2 as double").show()

# Approach - 4 : Using as clause in SQL statement.
df.createTempView("temp")
spark.sql("select *, value * 2 as double from temp").show()

For more examples and explanation on spark DataFrame functions, you can visit my blog.

I hope this helps.


问:
Is there an easier way to make these axios post reqest?
I'm trying to upload multiple images to cloudinary via api in my react app using axios.
I'm new to promises, so I'm not sure if I'm using the right approach here.

I am able to upload all the images to cloudinary; however, the response I get is the confusing part, as with the response I need to pass the images' urls to an object, so I can send them to an email using mailgun.

Here is my code to upload the images:

```<code>if(payment === "success") {
axios
    .all([
        props.imgForProduct.map((img) => {
            const fd = new FormData();
            fd.append("file", img);
            fd.append("upload_preset", "sublimation");
            return axios
                .post(
                    "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload",
                    fd
                )
                .then(async (res) => {
                    return (imgUrl = res.data.secure_url);
                })
                .catch((err) => console.log(err));
        }),

        props.screenshot.map((img) => {
            const fd = new FormData();
            fd.append("file", img);
            fd.append("upload_preset", "sublimation");
            return axios
                .post(
                    "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload",
                    fd
                )
                .then(async (res) => {
                    return (imgScrSht = res.data.secure_url);
                })
                .catch((err) => console.log(err));
        }),
    ])
    .then(
        axios.spread(async (...res) => {
            imgUrl.push(res[0][0]);
            imgScrSht.push(res[1][0]);

            let dataObj = {
                email: props.email,
                img: imgUrl,
                screenshot: imgScrSht,
            };
            console.log(dataObj);

            new Promise((resolve, reject) => {
                axios.post("/email_to_ayp_sublimation", dataObj);
                resolve((res) => {
                    console.log(res);
                });
                reject((err) => {
                    console.log(err);
                });
            });
        })
    )
    .catch((err) => console.error(err));
}
</code>```

When I console log the dataObj this is what I'm sending in the last call (the new Promise):

```<code>screenshot: Array(1)
0: Promise {<resolved>: "https://res.cloudinary.com/ahkji7ation/image/u…
590871936/ahkji7ation/kqebmkjfj0prmyygls2y.jpg"}
length: 1
__proto__: Array(0)
</code>```

I'm receiving [object Object] in the backend, instead of the url I need. Can anybody help me sort this out?
Thanks in advance

答:
I think the issue is with your axios.all(...) code. You are passing in two values but the values have .map inside them which are returning urls. Because of this, axios.post() on both indexes will upload the images but axios.all() will have the return values from the .map() function which is an array of promises. You can try something like this.

```<code>async function uploadImages(imgForProduct, screenshots) {
  const URL = "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload";

  //Collect all the form datas for img and screenshots
  const imgForProductFormData = imgForProduct.map((img) => {
    const fd = new FormData();
    fd.append("file", img);
    fd.append("upload_preset", "sublimation");
    return fd;
  });
  const screenShotsFormData = screenshots.map((img) => {
    const fd = new FormData();
    fd.append("file", img);
    fd.append("upload_preset", "sublimation");
    return fd;
  });

  const imgForProductRequests = imgForProductFormData.map(
    async (fd) => await axios.post(URL, fd).catch((err) => null)
  );
  const screenshotsRequests = screenShotsFormData.map(
    async (fd) => await axios.post(URL, fd).catch((err) => null)
  );

  try {
    const imgForProductResponses = await axios.all(imgForProductRequests);
    imgForProductResponses.map((res) => (res[0] ? imgUrl.push(res.data.secure_url) : null));

    const screenshotsResponses = await axios.all(screenshotsRequests);
    screenshotsResponses.map((res) => (res[0] ?imgScrSht.push(res.data.secure_url) : null));

    let dataObj = {
      email: props.email,
      img: imgUrl,
      screenshot: imgScrSht,
    };
    console.log(dataObj);

    new Promise((resolve, reject) => {
      axios.post("/email_to_ayp_sublimation", dataObj);
      resolve((res) => {
        console.log(res);
      });
      reject((err) => {
        console.log(err);
      });
    });
  } catch(err) {console.log(err)}
}
</code>```

Hope this works!

Body:
I'm trying to upload multiple images to cloudinary via api in my react app using axios.
I'm new to promises, so I'm not sure if I'm using the right approach here.

I am able to upload all the images to cloudinary; however, the response I get is the confusing part, as with the response I need to pass the images' urls to an object, so I can send them to an email using mailgun.

Here is my code to upload the images:

if(payment === "success") {
axios
    .all([
        props.imgForProduct.map((img) => {
            const fd = new FormData();
            fd.append("file", img);
            fd.append("upload_preset", "sublimation");
            return axios
                .post(
                    "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload",
                    fd
                )
                .then(async (res) => {
                    return (imgUrl = res.data.secure_url);
                })
                .catch((err) => console.log(err));
        }),

        props.screenshot.map((img) => {
            const fd = new FormData();
            fd.append("file", img);
            fd.append("upload_preset", "sublimation");
            return axios
                .post(
                    "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload",
                    fd
                )
                .then(async (res) => {
                    return (imgScrSht = res.data.secure_url);
                })
                .catch((err) => console.log(err));
        }),
    ])
    .then(
        axios.spread(async (...res) => {
            imgUrl.push(res[0][0]);
            imgScrSht.push(res[1][0]);

            let dataObj = {
                email: props.email,
                img: imgUrl,
                screenshot: imgScrSht,
            };
            console.log(dataObj);

            new Promise((resolve, reject) => {
                axios.post("/email_to_ayp_sublimation", dataObj);
                resolve((res) => {
                    console.log(res);
                });
                reject((err) => {
                    console.log(err);
                });
            });
        })
    )
    .catch((err) => console.error(err));
}

When I console log the dataObj this is what I'm sending in the last call (the new Promise):

screenshot: Array(1)
0: Promise {<resolved>: "https://res.cloudinary.com/ahkji7ation/image/u…
590871936/ahkji7ation/kqebmkjfj0prmyygls2y.jpg"}
length: 1
__proto__: Array(0)

I'm receiving [object Object] in the backend, instead of the url I need. Can anybody help me sort this out?
Thanks in advance

Body:
I think the issue is with your axios.all(...) code. You are passing in two values but the values have .map inside them which are returning urls. Because of this, axios.post() on both indexes will upload the images but axios.all() will have the return values from the .map() function which is an array of promises. You can try something like this.

async function uploadImages(imgForProduct, screenshots) {
  const URL = "https://api.cloudinary.com/v1_1/ahkji7ation/image/upload";

  //Collect all the form datas for img and screenshots
  const imgForProductFormData = imgForProduct.map((img) => {
    const fd = new FormData();
    fd.append("file", img);
    fd.append("upload_preset", "sublimation");
    return fd;
  });
  const screenShotsFormData = screenshots.map((img) => {
    const fd = new FormData();
    fd.append("file", img);
    fd.append("upload_preset", "sublimation");
    return fd;
  });

  const imgForProductRequests = imgForProductFormData.map(
    async (fd) => await axios.post(URL, fd).catch((err) => null)
  );
  const screenshotsRequests = screenShotsFormData.map(
    async (fd) => await axios.post(URL, fd).catch((err) => null)
  );

  try {
    const imgForProductResponses = await axios.all(imgForProductRequests);
    imgForProductResponses.map((res) => (res[0] ? imgUrl.push(res.data.secure_url) : null));

    const screenshotsResponses = await axios.all(screenshotsRequests);
    screenshotsResponses.map((res) => (res[0] ?imgScrSht.push(res.data.secure_url) : null));

    let dataObj = {
      email: props.email,
      img: imgUrl,
      screenshot: imgScrSht,
    };
    console.log(dataObj);

    new Promise((resolve, reject) => {
      axios.post("/email_to_ayp_sublimation", dataObj);
      resolve((res) => {
        console.log(res);
      });
      reject((err) => {
        console.log(err);
      });
    });
  } catch(err) {console.log(err)}
}

Hope this works!


问:
How to calculate sum of 2d vector by accessing objects
I am working on an assignment where we must create vehicles, store them in a showroom, then store showrooms in a dealership. To do I have established, vector (Vehicle) carVector; in "Showroom.h", and vector(vector(Vehicle)) showroomVector; in "Dealsership.h"

at the moment I am trying to display the average price of a car in the dealership. my current function looks like this

```<code>float Dealership::GetAveragePrice() {

    vector<vector<Vehicle>> showroomVector;

    float sum = 0.0f;
    float avgSum = 0.0f;
    unsigned int i;
    unsigned int j;

    for (i = 0; i < showroomVector.size(); i++) {
        for (j = 0; j < showroomVector.at(i).size(); j++) {
            sum = sum + showroomVector.at(i).at(j).GetPrice;
        }
    }
    avgSum = sum/((float)(i*j));

    return avgSum;
}
</code>```

The getprice function is in Vehicle.cpp and it is the following

```<code>float Vehicle::GetPrice() {
    return this->price;
}
</code>```

I basically need to add the price of every vehicle across all showrooms and then divide by i*j to find the average of the dealership but am having trouble accessing the data in my 2d vector correctly

Function that adds to showroom(was mentioned in the comments)

```<code>void Dealership::AddShowroom(Showroom s) {
        if (showroomVector.size() == capacity) {
            cout << "Dealership is full, can't add another showroom!\n";

        }

        else if (showroomVector.size() < capacity) {
            vector<Vehicle> s;
            showroomVector.push_back(s);
        }
    }
</code>```

答:
Your code is a bit confusing, vector<vector<Vehicle>> showroomVector; should be a class member and not a function member.

As stated GetPrice is missing brackets in the call.

Showroom s parameter is never used in the AddShowroom function.

Here is a simplified possible implementation that would make some sense with some comments:

Live demo

```<code>#include <iostream>
#include <vector>

class Vehicle {

    float price;

public:
    Vehicle(int price) : price(price) {} //ctor for sample

    float GetPrice() {
        return this->price;
    }
};

//for test purposes
class Showroom {

public:
    std::vector<Vehicle> vehicles = {Vehicle(500), Vehicle(1000), Vehicle(2350)};
};

class Dealership {
    std::vector<std::vector<Vehicle>> showroomVector;
    size_t capacity = 15;

public:
    //your function, unaltered, except for the brackets
    float GetAveragePrice() {

        float sum = 0.0f;
        float avgSum = 0.0f;
        unsigned int i = 0;
        unsigned int j = 0;

        for (i = 0; i < showroomVector.size(); i++) {
            for (j = 0; j < showroomVector.at(i).size(); j++) {
                sum = sum + showroomVector.at(i).at(j).GetPrice();
            }
        }
        avgSum = sum / ((float)(i * j));

        return avgSum;
    }

    //Showroom parameter is never used
    //a logic move would be to have a vector of vehicles in each showroom
    void AddShowroom(Showroom s) {
        if (showroomVector.size() == capacity) {
            std::cout << "Dealership is full, can't add another showroom!\n";
            return;
        }

        if (showroomVector.size() < capacity) {   //add all prices of vehicles in showroom
            showroomVector.push_back(s.vehicles);
        }
    }
};

int main() {
    Dealership d;
    Showroom s;
    d.AddShowroom(s); //add a showroom
    Showroom s2;
    d.AddShowroom(s); //add another

    std::cout << d.GetAveragePrice();
    return EXIT_SUCCESS;
}
</code>```

Body:
I am working on an assignment where we must create vehicles, store them in a showroom, then store showrooms in a dealership. To do I have established, vector (Vehicle) carVector; in "Showroom.h", and vector(vector(Vehicle)) showroomVector; in "Dealsership.h"

at the moment I am trying to display the average price of a car in the dealership. my current function looks like this

float Dealership::GetAveragePrice() {

    vector<vector<Vehicle>> showroomVector;

    float sum = 0.0f;
    float avgSum = 0.0f;
    unsigned int i;
    unsigned int j;

    for (i = 0; i < showroomVector.size(); i++) {
        for (j = 0; j < showroomVector.at(i).size(); j++) {
            sum = sum + showroomVector.at(i).at(j).GetPrice;
        }
    }
    avgSum = sum/((float)(i*j));

    return avgSum;
}

The getprice function is in Vehicle.cpp and it is the following

float Vehicle::GetPrice() {
    return this->price;
}

I basically need to add the price of every vehicle across all showrooms and then divide by i*j to find the average of the dealership but am having trouble accessing the data in my 2d vector correctly

Function that adds to showroom(was mentioned in the comments)

void Dealership::AddShowroom(Showroom s) {
        if (showroomVector.size() == capacity) {
            cout << "Dealership is full, can't add another showroom!\n";

        }

        else if (showroomVector.size() < capacity) {
            vector<Vehicle> s;
            showroomVector.push_back(s);
        }
    }

Body:
Your code is a bit confusing, vector<vector<Vehicle>> showroomVector; should be a class member and not a function member.

As stated GetPrice is missing brackets in the call.

Showroom s parameter is never used in the AddShowroom function.

Here is a simplified possible implementation that would make some sense with some comments:

Live demo

#include <iostream>
#include <vector>

class Vehicle {

    float price;

public:
    Vehicle(int price) : price(price) {} //ctor for sample

    float GetPrice() {
        return this->price;
    }
};

//for test purposes
class Showroom {

public:
    std::vector<Vehicle> vehicles = {Vehicle(500), Vehicle(1000), Vehicle(2350)};
};

class Dealership {
    std::vector<std::vector<Vehicle>> showroomVector;
    size_t capacity = 15;

public:
    //your function, unaltered, except for the brackets
    float GetAveragePrice() {

        float sum = 0.0f;
        float avgSum = 0.0f;
        unsigned int i = 0;
        unsigned int j = 0;

        for (i = 0; i < showroomVector.size(); i++) {
            for (j = 0; j < showroomVector.at(i).size(); j++) {
                sum = sum + showroomVector.at(i).at(j).GetPrice();
            }
        }
        avgSum = sum / ((float)(i * j));

        return avgSum;
    }

    //Showroom parameter is never used
    //a logic move would be to have a vector of vehicles in each showroom
    void AddShowroom(Showroom s) {
        if (showroomVector.size() == capacity) {
            std::cout << "Dealership is full, can't add another showroom!\n";
            return;
        }

        if (showroomVector.size() < capacity) {   //add all prices of vehicles in showroom
            showroomVector.push_back(s.vehicles);
        }
    }
};

int main() {
    Dealership d;
    Showroom s;
    d.AddShowroom(s); //add a showroom
    Showroom s2;
    d.AddShowroom(s); //add another

    std::cout << d.GetAveragePrice();
    return EXIT_SUCCESS;
}


问:
How do I make event callbacks into my win forms thread safe?
When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread.

The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.

答:
To simplify Simon's code a bit, you could use the built in generic Action delegate.  It saves peppering your code with a bunch of delegate types you don't really need.  Also, in .NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array.</p>

```<code>void SomethingHappened(object sender, EventArgs ea)
{
   if (InvokeRequired)
   {
      Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea);
      return;
   }

   textBox1.Text = "Something happened";
}
</code>```

LastEditorDisplayName: Alex Miller

Body:
To simplify Simon's code a bit, you could use the built in generic Action delegate.  It saves peppering your code with a bunch of delegate types you don't really need.  Also, in .NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array.

void SomethingHappened(object sender, EventArgs ea)
{
   if (InvokeRequired)
   {
      Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea);
      return;
   }

   textBox1.Text = "Something happened";
}

LastEditorDisplayName: Jakers


问:
Avoiding Global State
Currently I'm writing an app. If I want to avoid Singletons, do I have to simply pass references of everything around?

For example,

I have a "main" class.

Class: Main

+---- Screen

+---- Camera

+---- Terrain

+---- Vehicle

+---- PhysicsWorld

It contains my Camera, Terrain, and Vehicle,etc classes.  Now, I have issues when I'm creating say, the Terrain object.  Terrain wants to access Main classes Screen object so it can add its Terrain Graphics to the screen.  It also wants to know about the Camera object for when it is drawing so it knows what scale to draw it.  It also wants to know about my PhysicsWorld object so it can add itself to the physics engine.

Do I have to always lug these objects back and forth between constructors?  I mean, when I create a Terrain object, do I simply have to pass around my screen object, my physicsWorld, camera, etc?

Another random scenario I have, is now.. inside my Vehicle class I need to call a Restart() method on my Main class.  Does this mean I have to pass an instance of main to Vehicle?  Really??

It feels cumbersome to constantly have to pass 4-5 things to my classes, especially in my scenario now where almost every in-game object I have needs a screen, physics, camera info, etc.

Any suggestions?

答: I don't know ActionScript, but assuming variables are passed by reference, the least you could do is construct a 'Environment' class holding Camera, Screen, Terrain, PhysicsWorld which you pass to the instances.</p>

OwnerDisplayName: KingNestor

Title: Avoiding Global State

LastEditorDisplayName: KingNestor

OwnerDisplayName: jjungnickel


问:
Python Tkinter button width and heigth
I'm new to tkinter, trying to create a square botton but I can't.

```<code>from tkinter import *

root = Tk()
button1 = Button(text = "Cuadrado", height = 10, width = 10).pack()

root.mainloop()
</code>```

The widht and the height are the same valor, but the button that create with the code is a rectangle.
Why does it happen?

答:
The width and height of a button that has text but no image are in the number of characters (ie: height=10 means it should be 10 characters tall).

The average character in your font is almost certainly not a square -- fonts are typically taller than they are wide. Thus, 10 characters wide will likely be fewer pixels than 10 characters tall.

Title: Python Tkinter button width and heigth

Body:
I'm new to tkinter, trying to create a square botton but I can't.

from tkinter import *

root = Tk()
button1 = Button(text = "Cuadrado", height = 10, width = 10).pack()

root.mainloop()

The widht and the height are the same valor, but the button that create with the code is a rectangle.
Why does it happen?


问:
Is BASH very slow?
I was solving this question on SPOJ - http://www.spoj.com/problems/ALICESIE/

What the question boils down to print (n+1)/2

This is my C code which passes in 0.03s

```<code>    #include <stdio.h>
    int main() {
        int test, n;
        scanf("%d", &test);
        while(test--) {
            scanf("%d", &n);
            printf("%d\n", (n + 1) >> 1);
        }
        return 0;
    }
</code>```

while this is my BASH code which gives Time Limit Exceeded ( i.e. > 1s )

```<code>read test
while (( test-- ))
do
    read n
    echo "$(((n+1)/2))"
done
</code>```

Can anyone let me know why is this happening ? Is BASH very slow ?
Thanks.

答:
The shebang is not added.

```<code>#!/bin/bash

read test
while (( test-- ))
do
    read n
    echo "$(((n+1)/2))"
done
</code>```

This code I submitted, ran in 0.14 time in SPOJ and was accepted. I don't see any difference in the question code, except the shebang!!

(For the reader)

Title: Is BASH very slow?

Body:
I was solving this question on SPOJ - http://www.spoj.com/problems/ALICESIE/

What the question boils down to print (n+1)/2

This is my C code which passes in 0.03s

    #include <stdio.h>
    int main() {
        int test, n;
        scanf("%d", &test);
        while(test--) {
            scanf("%d", &n);
            printf("%d\n", (n + 1) >> 1);
        }
        return 0;
    }

while this is my BASH code which gives Time Limit Exceeded ( i.e. > 1s )

read test
while (( test-- ))
do
    read n
    echo "$(((n+1)/2))"
done

Can anyone let me know why is this happening ? Is BASH very slow ?
Thanks.

Body:
The shebang is not added.

#!/bin/bash

read test
while (( test-- ))
do
    read n
    echo "$(((n+1)/2))"
done

This code I submitted, ran in 0.14 time in SPOJ and was accepted. I don't see any difference in the question code, except the shebang!!

(For the reader)


问:
Node JS fs.unlink not working Static folder
I have static folder, this:

```<code>App.use('/getUnity', Express.static(__dirname + '/uax_vr_uploads/unityFiles'));
</code>```

I want delete file in folder, not working this 2 fs.unlink:

```<code>fs.unlink('http://localhost:3002/getUnity/' + response[0][item].varyant_object, (error) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Deleted');
  }
});
</code>```

OR

```<code>fs.unlink('http://localhost:3002/uax_vr_uploads/unityFiles/' + response[0][item].varyant_object, (error) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Deleted');
  }
});
</code>```

Console LOG:

```<code>[Error: ENOENT: no such file or directory, unlink 'http://localhost:3002/getUnity/file-1590880543263.unity3d'] {
      errno: -2,
      code: 'ENOENT',
      syscall: 'unlink',
      path: 'http://localhost:3002/getUnity/file-1590880543263.unity3d'
    }
</code>```

答:
If you're trying to remove a file from your static folder, then you need to pass a valid OS path name to fs.unlink() not a URL that only your server would know about.

If the file on your disk that you're actually trying to remove is this:

```<code>/uax_vr_uploads/unityFiles/file-1590880543263.unity3d
</code>```

Then, judging by your code, it looks like you want this:

```<code>fs.unlink('/uax_vr_uploads/unityFiles/' + response[0][item].varyant_object);
</code>```

Body:
I have static folder, this:

App.use('/getUnity', Express.static(__dirname + '/uax_vr_uploads/unityFiles'));

I want delete file in folder, not working this 2 fs.unlink:

fs.unlink('http://localhost:3002/getUnity/' + response[0][item].varyant_object, (error) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Deleted');
  }
});

OR

fs.unlink('http://localhost:3002/uax_vr_uploads/unityFiles/' + response[0][item].varyant_object, (error) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Deleted');
  }
});

Console LOG:

[Error: ENOENT: no such file or directory, unlink 'http://localhost:3002/getUnity/file-1590880543263.unity3d'] {
      errno: -2,
      code: 'ENOENT',
      syscall: 'unlink',
      path: 'http://localhost:3002/getUnity/file-1590880543263.unity3d'
    }

Body:
If you're trying to remove a file from your static folder, then you need to pass a valid OS path name to fs.unlink() not a URL that only your server would know about.

If the file on your disk that you're actually trying to remove is this:

/uax_vr_uploads/unityFiles/file-1590880543263.unity3d

Then, judging by your code, it looks like you want this:

fs.unlink('/uax_vr_uploads/unityFiles/' + response[0][item].varyant_object);