问:
Use animatedVectorDrawable in custom view
I know we can draw a vector drawable like this on canvas:

```<code>vectorDrawable.setBounds(left, top, right, bottom);
vectorDrawable.draw(canvas);
</code>```

but Is it possible to use animatedVectorDrawables in custom view?

答:
Yes, it is possible, and looks like the snippet you have would work.  Be sure to set bounds and call the start() method on the drawable to start the animation.

```<code>class MyCustomView : View {

  lateinit var animVectDrawable: AnimatedVectorDrawable

  fun startAnim() {
    animVectDrawable.setBounds(left, top, right, bottom)
    animVectDrawable.start()
    shouldDrawAnim = true
  }

  override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    if (shouldDrawAnim) {
      animVectDrawable.draw(canvas)
    }
  }
}
</code>```

Body:
I know we can draw a vector drawable like this on canvas:

vectorDrawable.setBounds(left, top, right, bottom);
vectorDrawable.draw(canvas);

but Is it possible to use animatedVectorDrawables in custom view?

Body:
Yes, it is possible, and looks like the snippet you have would work.  Be sure to set bounds and call the start() method on the drawable to start the animation.

class MyCustomView : View {

  lateinit var animVectDrawable: AnimatedVectorDrawable

  fun startAnim() {
    animVectDrawable.setBounds(left, top, right, bottom)
    animVectDrawable.start()
    shouldDrawAnim = true
  }

  override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    if (shouldDrawAnim) {
      animVectDrawable.draw(canvas)
    }
  }
}


来源: stackexchange

问:
Query multiple Firestore Collections for same field
I am looking to find documents across several Collections where they have documents with no description field, I want to avoid looping but want to find the most efficient way of doing this. This code works in one collection.</p>

```<code>            firebase
            .firestore()
            .collection('creators') // ### Would need to loop for 4 others like this #####
            .where('description', '==', '')
            .get()
            .then((snapshot) => {
                if (snapshot.empty) {
                    console.log('No matching documents.')
                    return
                }

                snapshot.forEach((doc) => {
                    console.log(doc.id, '=>', doc.data())
                })
            })
            .catch((err) => {
                console.log('Error getting documents', err)
            })
</code>```

答:
You could use Promise.all() to execute all the queries in parallel, as follows:

```<code>   const db = firebase.firestore();

   const q1 = db.collection('creators').where('description', '==', '...').get();
   const q2 = db.collection('xyz').where('description', '==', '...').get();

   return Promise.all([q1, q2])
   .then(snapshotsArray => {

       snapshotsArray.forEach(snap => {
            snap.forEach(doc => {
                console.log(doc.id, '=>', doc.data())
            })
       })

   })
</code>```

You could simplify it as follows:

```<code>   const collectionNames = ['creators', 'klmn', 'opqr', 'stuv']
   const promises = collectionNames.map(x => db.collection(x).where('description', '==', '...').get());

   Promise.all(promises)
   .then(snapshotsArray => {

       snapshotsArray.forEach(snap => {
            snap.forEach(doc => {
                 console.log(doc.id, '=>', doc.data())
            })
       })

   })
</code>```

As explained in the doc referred to above:

The Promise.all() method returns a single Promise that fulfills when
  all of the promises passed as an iterable have been fulfilled

...

The returned promise is fulfilled with an array containing all the
  values of the iterable passed as argument (also non-promise values).

HOWEVER,

there is an important point to note, based on this sentence in your question: "find documents across several Collections where they have documents with no description field".

You cannot build a query in Firestore that will return document without a given field. The reason (indexing mechanism) is well explained in this official video .

On the other hand, you can query for a document with an empty field:

```<code>db.collection('creators').where('description', '==', '').get();
</code>```

or with a field with null value:

```<code>db.collection('creators').where('description', '==', null).get();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am looking to find documents across several Collections where they have documents with no description field, I want to avoid looping but want to find the most efficient way of doing this. This code works in one collection.

            firebase
            .firestore()
            .collection('creators') // ### Would need to loop for 4 others like this #####
            .where('description', '==', '')
            .get()
            .then((snapshot) => {
                if (snapshot.empty) {
                    console.log('No matching documents.')
                    return
                }

                snapshot.forEach((doc) => {
                    console.log(doc.id, '=>', doc.data())
                })
            })
            .catch((err) => {
                console.log('Error getting documents', err)
            })

Body:
You could use Promise.all() to execute all the queries in parallel, as follows:

   const db = firebase.firestore();

   const q1 = db.collection('creators').where('description', '==', '...').get();
   const q2 = db.collection('xyz').where('description', '==', '...').get();

   return Promise.all([q1, q2])
   .then(snapshotsArray => {

       snapshotsArray.forEach(snap => {
            snap.forEach(doc => {
                console.log(doc.id, '=>', doc.data())
            })
       })

   })

You could simplify it as follows:

   const collectionNames = ['creators', 'klmn', 'opqr', 'stuv']
   const promises = collectionNames.map(x => db.collection(x).where('description', '==', '...').get());

   Promise.all(promises)
   .then(snapshotsArray => {

       snapshotsArray.forEach(snap => {
            snap.forEach(doc => {
                 console.log(doc.id, '=>', doc.data())
            })
       })

   })

As explained in the doc referred to above:

The Promise.all() method returns a single Promise that fulfills when
  all of the promises passed as an iterable have been fulfilled

...

The returned promise is fulfilled with an array containing all the
  values of the iterable passed as argument (also non-promise values).

HOWEVER,

there is an important point to note, based on this sentence in your question: "find documents across several Collections where they have documents with no description field".

You cannot build a query in Firestore that will return document without a given field. The reason (indexing mechanism) is well explained in this official video .

On the other hand, you can query for a document with an empty field:

db.collection('creators').where('description', '==', '').get();

or with a field with null value:

db.collection('creators').where('description', '==', null).get();


问:
How to save multiple data on mongoose
Current code can save single data. I have multiple data at incoming request. How can i save the multiple data to mongodb? As you can see in the image there are 3 different objects.

Orders route

router.route("/api/orders").post((req, res) => {
  const body = req.body;
  console.log(body);

  const orderid = req.body.id;
  const ordername = req.bodyname;
  const orderdescription = req.bodydescription;
  const orderquantity = req.bodyquantity;
  const ordertotalprice = req.bodytotalPrice;
  const newOrder = new Orders({
    orderid,
    ordername,
    orderdescription,
    orderquantity,
    ordertotalprice
  });

  newOrder
    .save()
    .then(() => {
      console.log("Order Added!");
      res.status(200).json("Order Added!");
    })
    .catch(err => res.status(400).json("Error: " + err));
});

module.exports = router;
```

答:
Your request body is an array of objects.

You can use Model.insertMany() method to insert multiple documents.
Before using insertMany be sure, you convert the objects in request body to the mongoose model object correctly. Here I used javascript map method to show a sample, you may need to change that transformation.

router.route("/api/orders").post((req, res) => {
  const body = req.body;
  console.log(body);

  let items = req.body.map(item => {
    return {
      orderid: item.id,
      ordername: item.name,
      orderdescription: item.description,
      orderquantity: item.quantity,
      ordertotalprice: item.totalPrice
    };
  });

  Orders.insertMany(items)
    .then(() => {
      console.log("Orders Added!");
      res.status(200).json("Order Added!");
    })
    .catch(err => res.status(400).json("Error: " + err));
});

module.exports = router;
```

Title: How to save multiple data on mongoose


问:
How to identify the operation type(insert,update,delete) in SQL Server trigger
We are using the following trigger in SQL Server to maintain the history now I need to identify the operations just like insert,update or delete. I found some information HERE but it doesn't works with the SQL Server.

```<code>CREATE TRIGGER audit_guest_details ON [PMS].[GSDTLTBL]
FOR INSERT,UPDATE,DELETE
AS
    DECLARE @SRLNUB1 INT;
    DECLARE @UPDFLG1 DECIMAL(3,0);

    SELECT @SRLNUB1 = I.SRLNUB FROM inserted I;
    SELECT @UPDFLG1 = I.UPDFLG FROM inserted I;

    BEGIN
       /* Here I need to identify the operation and insert the operation type in the GUEST_ADT 3rd field */
       insert into dbo.GUEST_ADT values(@SRLNUB1,@UPDFLG1,?);

       PRINT 'BEFORE INSERT trigger fired.'
    END;
GO
</code>```

But here I need to identify the operation and want to insert operation type accordingly.

Here I don't want to create three trigger for every operations

答:
This is a simplified version of Mikhail's answer that uses a searched CASE expression. </p>

```<code>DECLARE @Operation varchar(7) =
    CASE WHEN EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted)
        THEN 'Update'
    WHEN EXISTS(SELECT * FROM inserted)
        THEN 'Insert'
    WHEN EXISTS(SELECT * FROM deleted)
        THEN 'Delete'
    ELSE
        NULL --Unknown
    END;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We are using the following trigger in SQL Server to maintain the history now I need to identify the operations just like insert,update or delete. I found some information HERE but it doesn't works with the SQL Server.

CREATE TRIGGER audit_guest_details ON [PMS].[GSDTLTBL]
FOR INSERT,UPDATE,DELETE
AS
    DECLARE @SRLNUB1 INT;
    DECLARE @UPDFLG1 DECIMAL(3,0);

    SELECT @SRLNUB1 = I.SRLNUB FROM inserted I;
    SELECT @UPDFLG1 = I.UPDFLG FROM inserted I;

    BEGIN
       /* Here I need to identify the operation and insert the operation type in the GUEST_ADT 3rd field */
       insert into dbo.GUEST_ADT values(@SRLNUB1,@UPDFLG1,?);

       PRINT 'BEFORE INSERT trigger fired.'
    END;
GO

But here I need to identify the operation and want to insert operation type accordingly.

Here I don't want to create three trigger for every operations

Body:
This is a simplified version of Mikhail's answer that uses a searched CASE expression.

DECLARE @Operation varchar(7) =
    CASE WHEN EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted)
        THEN 'Update'
    WHEN EXISTS(SELECT * FROM inserted)
        THEN 'Insert'
    WHEN EXISTS(SELECT * FROM deleted)
        THEN 'Delete'
    ELSE
        NULL --Unknown
    END;


问:
string value obtained from reading from json file , displays weirdly when using Path.Combine
I have a functionality where I would scan a given path for a certain file and process some information based on the information in that file . this file info.json in json syntax has a name and a relative path to a certain  directory .
What I am trying to do is simply obtain the relative path from the json file and print out an absoulute path

the relative file specified in the info.json file is as below,

```<code>{
  "Name": "testName",
  "OriginalPath": "new/File"
}
</code>```

The absolute path that I am trying to print out is something like :- D:\testDel\new\File but the actual value is always something like D:\testDel\new/File , while I must say this path is still a valid path (when I do a win key + R I can navigate to that directory) but in terms of how its been displayed it looks messy .

Any Idea as to why I might be facing this problem , am I doing something wrong ,

my code is as follows

```<code>string path = @"D:\testDel";
            IEnumerable<string> foundFiles = Directory.EnumerateFiles(path, "info.json", SearchOption.AllDirectories);

            foreach (string file in foundFiles)
            {

                DataModel data = JsonConvert.DeserializeObject<DataModel>(File.ReadAllText(file));

                string Name = data.Name;
                string absolutePath = data.OriginalPath;
                string folderpath = Path.GetDirectoryName(file);
                string fullPath = Path.Combine(folderpath, absolutePath);
                Console.WriteLine(fullPath);

            }
    public class DataModel
    {
        public string Name { get; set; }
        public string OriginalPath { get; set; }
    }
</code>```

答:
You can update a path, coming from JSON using Replace method and built-in Path.AltDirectorySeparatorChar and Path.DirectorySeparatorChar fields

string absolutePath = data.OriginalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string folderpath = Path.GetDirectoryName(file);
```

You are right, that path D:\testDel\new/File is valid, because Windows supports both, forward slash and backslash

Body:
I have a functionality where I would scan a given path for a certain file and process some information based on the information in that file . this file info.json in json syntax has a name and a relative path to a certain  directory .
What I am trying to do is simply obtain the relative path from the json file and print out an absoulute path

the relative file specified in the info.json file is as below,

{
  "Name": "testName",
  "OriginalPath": "new/File"
}

The absolute path that I am trying to print out is something like :- D:\testDel\new\File but the actual value is always something like D:\testDel\new/File , while I must say this path is still a valid path (when I do a win key + R I can navigate to that directory) but in terms of how its been displayed it looks messy .

Any Idea as to why I might be facing this problem , am I doing something wrong ,

my code is as follows

string path = @"D:\testDel";
            IEnumerable<string> foundFiles = Directory.EnumerateFiles(path, "info.json", SearchOption.AllDirectories);

            foreach (string file in foundFiles)
            {

                DataModel data = JsonConvert.DeserializeObject<DataModel>(File.ReadAllText(file));

                string Name = data.Name;
                string absolutePath = data.OriginalPath;
                string folderpath = Path.GetDirectoryName(file);
                string fullPath = Path.Combine(folderpath, absolutePath);
                Console.WriteLine(fullPath);

            }
    public class DataModel
    {
        public string Name { get; set; }
        public string OriginalPath { get; set; }
    }

Body:
You can update a path, coming from JSON using Replace method and built-in Path.AltDirectorySeparatorChar and Path.DirectorySeparatorChar fields

string absolutePath = data.OriginalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string folderpath = Path.GetDirectoryName(file);

You are right, that path D:\testDel\new/File is valid, because Windows supports both, forward slash and backslash


问:
How do I write a function that returns another function?
In Python, I'd like to write a function make_cylinder_volume(r) which returns another function. That returned function should be callable with a parameter h, and return the volume of a cylinder with height h and radius r.

I know how to return values from functions in Python, but how do I return another function?

答:
I know I am too late to the party, but I think you might find this solution interesting.

from math import pi
from functools import partial

def cylinder_volume(r, h):
    return pi * r * r * h

make_cylinder_with_radius_2 = partial(cylinder_volume, 2)
make_cylinder_with_height_3 = partial(cylinder_volume, h=3)

print(cylinder_volume(2, 3))            # 37.6991118431
print(make_cylinder_with_radius_2(3))   # 37.6991118431
print(make_cylinder_with_height_3(2))   # 37.6991118431
```

Here is documentation about how partial works.

Body:
I know I am too late to the party, but I think you might find this solution interesting.

from math import pi
from functools import partial

def cylinder_volume(r, h):
    return pi * r * r * h

make_cylinder_with_radius_2 = partial(cylinder_volume, 2)
make_cylinder_with_height_3 = partial(cylinder_volume, h=3)

print(cylinder_volume(2, 3))            # 37.6991118431
print(make_cylinder_with_radius_2(3))   # 37.6991118431
print(make_cylinder_with_height_3(2))   # 37.6991118431

Here is documentation about how partial works.


问:
What is the alternation operator in Lua patterns?
In regex, | is used for alternation. What is the corresponding character in Lua patterns?

答: Lua does not have alternations in patterns you cannot use (test1|test2). You can only choose between multiple characters like [abcd] will match a, b, c or d.


问:
How to show full width video in exoplayer plugin in nativescript?
Use this property in file but video was not display in full width which is shown below::

fill="true"

答: Kindly check your width and height of layout . Also if any other parameter is reducing the layout size </p>


问:
How to compile and dump assembly for a c library (string.h)?
For a school project I have to do a large amount of string manipulation in assembly.  Since this is a pain to do I was trying to come up with innovative ways to use already programmed string operations.  My idea is to compile and dump the assembly from the string.h library in c.  Then I would copy paste the dumped assembly into my program.  After figuring out the memory location of each function and it's parameters I figure I would essentially be able to call up the function.

To dump the assembly I first wrote a program that included the libraries I wanted:

```<code>#include <stdio.h>
#include <string.h>

int main() {

  return 0;
}
</code>```

Then I compiled and dumped the assembly using

```<code>gcc -o lib lib.c
objdump -d  *o
</code>```

When I looked at the output I noticed that it didn't include any of the assembly for the libraries.  My guess is there is either a compiler optimization that doesn't include unused functions, or the library output is hidden when I use objdump:

```<code>lib:    file format Mach-O 64-bit x86-64

Disassembly of section __TEXT,__text:
__text:
100000fa0:  55  pushq   %rbp
100000fa1:  48 89 e5    movq    %rsp, %rbp
100000fa4:  31 c0   xorl    %eax, %eax
100000fa6:  c7 45 fc 00 00 00 00    movl    $0, -4(%rbp)
100000fad:  5d  popq    %rbp
100000fae:  c3  retq

_main:
100000fa0:  55  pushq   %rbp
100000fa1:  48 89 e5    movq    %rsp, %rbp
100000fa4:  31 c0   xorl    %eax, %eax
100000fa6:  c7 45 fc 00 00 00 00    movl    $0, -4(%rbp)
100000fad:  5d  popq    %rbp
100000fae:  c3  retq
</code>```

As a side note I am running OSX Catalina, but I can switch to Ubuntu or a different OS if it would be easier.

How can I go about dumping the asm for the string.h library?

答:
Generic method:

find package, for Debian-like Linux:

```<code>$ apt-file search string.h
</code>```

Of course, this is glibc.

get source e.g. glibc 2.31 and compile it:

```<code>$ ./configure --prefix=/usr --enable-kernel=4.0.0 --disable-profile --with-gnu-ld --enable-stack-protector=strong
$ make
</code>```

implementations of functions usually have the same name, so find source:

```<code>$ find . -type f -name "strstr.c"
</code>```

this is strings/strstr.c

disassemble default compiled version:

```<code>$ objdump -d string/strstr.o > strstr1.asm
</code>```

make new version with customized optimization:
delete object file:

```<code>$ rm string/strstr.o`
</code>```

remake with commands output:

```<code>$ make V=1 &>strstrr.txt
</code>```

this is for "bash", otherwise use "script" command

get gcc command from strstrr.txt, modify it as you want (optimization, processor type...), e.g. change -O2 to O10, and run:

```<code>$ cd strings
$ gcc ../sysdeps/x86_64/multiarch/strstr.c -c -std=gnu11 -fgnu89-inline  -g -O10 -Wall -Wwrite-strings -Wundef -Werror -fmerge-all-constants -frounding-math -fstack-protector-strong -Wstrict-prototypes -Wold-style-definition -fmath-errno      -ftls-model=initial-exec      -I../include -I/home/yury/LFSC/cross1/src/bglibcn/string  -I/home/yury/LFSC/cross1/src/bglibcn  -I../sysdeps/unix/sysv/linux/x86_64/64  -I../sysdeps/unix/sysv/linux/x86_64  -I../sysdeps/unix/sysv/linux/x86/include -I../sysdeps/unix/sysv/linux/x86  -I../sysdeps/x86/nptl  -I../sysdeps/unix/sysv/linux/wordsize-64  -I../sysdeps/x86_64/nptl  -I../sysdeps/unix/sysv/linux/include -I../sysdeps/unix/sysv/linux  -I../sysdeps/nptl  -I../sysdeps/pthread  -I../sysdeps/gnu  -I../sysdeps/unix/inet  -I../sysdeps/unix/sysv  -I../sysdeps/unix/x86_64  -I../sysdeps/unix  -I../sysdeps/posix  -I../sysdeps/x86_64/64  -I../sysdeps/x86_64/fpu/multiarch  -I../sysdeps/x86_64/fpu  -I../sysdeps/x86/fpu/include -I../sysdeps/x86/fpu  -I../sysdeps/x86_64/multiarch  -I../sysdeps/x86_64  -I../sysdeps/x86  -I../sysdeps/ieee754/float128  -I../sysdeps/ieee754/ldbl-96/include -I../sysdeps/ieee754/ldbl-96  -I../sysdeps/ieee754/dbl-64/wordsize-64  -I../sysdeps/ieee754/dbl-64  -I../sysdeps/ieee754/flt-32  -I../sysdeps/wordsize-64  -I../sysdeps/ieee754  -I../sysdeps/generic  -I.. -I../libio -I.   -D_LIBC_REENTRANT -include /home/yury/LFSC/cross1/src/bglibcn/libc-modules.h -DMODULE_NAME=libc -include ../include/libc-symbols.h       -DTOP_NAMESPACE=glibc -o /home/yury/LFSC/cross1/src/bglibcn/string/strstr.o -MD -MP -MF /home/yury/LFSC/cross1/src/bglibcn/string/strstr.o.dt -MT /home/yury/LFSC/cross1/src/bglibcn/string/strstr.o
$ objdump -d string/strstr.o > strstr2.asm
</code>```

the code will be different:

```<code>$ diff strstr1.asm strstr2.asm
</code>```

So, you can copy-paste code you want into your assembler program to save your time.

Body:
For a school project I have to do a large amount of string manipulation in assembly.  Since this is a pain to do I was trying to come up with innovative ways to use already programmed string operations.  My idea is to compile and dump the assembly from the string.h library in c.  Then I would copy paste the dumped assembly into my program.  After figuring out the memory location of each function and it's parameters I figure I would essentially be able to call up the function.

To dump the assembly I first wrote a program that included the libraries I wanted:

#include <stdio.h>
#include <string.h>

int main() {

  return 0;
}

Then I compiled and dumped the assembly using

gcc -o lib lib.c
objdump -d  *o

When I looked at the output I noticed that it didn't include any of the assembly for the libraries.  My guess is there is either a compiler optimization that doesn't include unused functions, or the library output is hidden when I use objdump:

lib:    file format Mach-O 64-bit x86-64

Disassembly of section __TEXT,__text:
__text:
100000fa0:  55  pushq   %rbp
100000fa1:  48 89 e5    movq    %rsp, %rbp
100000fa4:  31 c0   xorl    %eax, %eax
100000fa6:  c7 45 fc 00 00 00 00    movl    $0, -4(%rbp)
100000fad:  5d  popq    %rbp
100000fae:  c3  retq

_main:
100000fa0:  55  pushq   %rbp
100000fa1:  48 89 e5    movq    %rsp, %rbp
100000fa4:  31 c0   xorl    %eax, %eax
100000fa6:  c7 45 fc 00 00 00 00    movl    $0, -4(%rbp)
100000fad:  5d  popq    %rbp
100000fae:  c3  retq

As a side note I am running OSX Catalina, but I can switch to Ubuntu or a different OS if it would be easier.

How can I go about dumping the asm for the string.h library?

Body:
Generic method:

find package, for Debian-like Linux:

$ apt-file search string.h

Of course, this is glibc.

get source e.g. glibc 2.31 and compile it:

$ ./configure --prefix=/usr --enable-kernel=4.0.0 --disable-profile --with-gnu-ld --enable-stack-protector=strong
$ make

implementations of functions usually have the same name, so find source:

$ find . -type f -name "strstr.c"

this is strings/strstr.c

disassemble default compiled version:

$ objdump -d string/strstr.o > strstr1.asm

make new version with customized optimization:
delete object file:

$ rm string/strstr.o`

remake with commands output:

$ make V=1 &>strstrr.txt

this is for "bash", otherwise use "script" command

get gcc command from strstrr.txt, modify it as you want (optimization, processor type...), e.g. change -O2 to O10, and run:

$ cd strings
$ gcc ../sysdeps/x86_64/multiarch/strstr.c -c -std=gnu11 -fgnu89-inline  -g -O10 -Wall -Wwrite-strings -Wundef -Werror -fmerge-all-constants -frounding-math -fstack-protector-strong -Wstrict-prototypes -Wold-style-definition -fmath-errno      -ftls-model=initial-exec      -I../include -I/home/yury/LFSC/cross1/src/bglibcn/string  -I/home/yury/LFSC/cross1/src/bglibcn  -I../sysdeps/unix/sysv/linux/x86_64/64  -I../sysdeps/unix/sysv/linux/x86_64  -I../sysdeps/unix/sysv/linux/x86/include -I../sysdeps/unix/sysv/linux/x86  -I../sysdeps/x86/nptl  -I../sysdeps/unix/sysv/linux/wordsize-64  -I../sysdeps/x86_64/nptl  -I../sysdeps/unix/sysv/linux/include -I../sysdeps/unix/sysv/linux  -I../sysdeps/nptl  -I../sysdeps/pthread  -I../sysdeps/gnu  -I../sysdeps/unix/inet  -I../sysdeps/unix/sysv  -I../sysdeps/unix/x86_64  -I../sysdeps/unix  -I../sysdeps/posix  -I../sysdeps/x86_64/64  -I../sysdeps/x86_64/fpu/multiarch  -I../sysdeps/x86_64/fpu  -I../sysdeps/x86/fpu/include -I../sysdeps/x86/fpu  -I../sysdeps/x86_64/multiarch  -I../sysdeps/x86_64  -I../sysdeps/x86  -I../sysdeps/ieee754/float128  -I../sysdeps/ieee754/ldbl-96/include -I../sysdeps/ieee754/ldbl-96  -I../sysdeps/ieee754/dbl-64/wordsize-64  -I../sysdeps/ieee754/dbl-64  -I../sysdeps/ieee754/flt-32  -I../sysdeps/wordsize-64  -I../sysdeps/ieee754  -I../sysdeps/generic  -I.. -I../libio -I.   -D_LIBC_REENTRANT -include /home/yury/LFSC/cross1/src/bglibcn/libc-modules.h -DMODULE_NAME=libc -include ../include/libc-symbols.h       -DTOP_NAMESPACE=glibc -o /home/yury/LFSC/cross1/src/bglibcn/string/strstr.o -MD -MP -MF /home/yury/LFSC/cross1/src/bglibcn/string/strstr.o.dt -MT /home/yury/LFSC/cross1/src/bglibcn/string/strstr.o
$ objdump -d string/strstr.o > strstr2.asm

the code will be different:

$ diff strstr1.asm strstr2.asm

So, you can copy-paste code you want into your assembler program to save your time.


问:
Find the location nearest to the current location from an array of three locations and compare that which one is nearest to the current location
```<code>ArrayList<LatLng> arrayList= new ArrayList<LatLng>();
LatLng near = new LatLng(33.549232, 73.125256);
LatLng pass = new LatLng(33.549844, 73.125849);
LatLng qareeb = new LatLng(33.549603, 73.124201);

public void onMapReady(GoogleMap googleMap) {
    mMap= googleMap;
    for (int i =0; i<arrayList.size();i++){
        mMap.addMarker(new MarkerOptions().position(arrayList.get(i)).title("Marker").snippet("and snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        LatLng latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Main Yahan hn");
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(arrayList.get(i),15));
        mMap.animateCamera(CameraUpdateFactory.zoomIn());
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
        /*mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));*/
        mMap.moveCamera(CameraUpdateFactory.newLatLng(arrayList.get(i)));
        googleMap.addMarker(markerOptions);

    }
}
</code>```

Above is my code and I want to create 3 points which compare to my current location that which one is near to the current location.

答:
You can calculate distance between two location and then compare the distance.

```<code> private double distance(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1))
            * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lat1))
            * Math.cos(deg2rad(lat2))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}
</code>```

You can use this as below code

```<code>  LatLng near = new LatLng(33.549232, 73.125256);
        LatLng pass = new LatLng(33.549844, 73.125849);
        LatLng qareeb = new LatLng(33.549603, 73.124201);
        double distance = distance(near.latitude, near.longitude, pass.latitude, pass.longitude);
</code>```

Body:
ArrayList<LatLng> arrayList= new ArrayList<LatLng>();
LatLng near = new LatLng(33.549232, 73.125256);
LatLng pass = new LatLng(33.549844, 73.125849);
LatLng qareeb = new LatLng(33.549603, 73.124201);

public void onMapReady(GoogleMap googleMap) {
    mMap= googleMap;
    for (int i =0; i<arrayList.size();i++){
        mMap.addMarker(new MarkerOptions().position(arrayList.get(i)).title("Marker").snippet("and snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
        LatLng latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Main Yahan hn");
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(arrayList.get(i),15));
        mMap.animateCamera(CameraUpdateFactory.zoomIn());
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
        /*mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));*/
        mMap.moveCamera(CameraUpdateFactory.newLatLng(arrayList.get(i)));
        googleMap.addMarker(markerOptions);

    }
}

Above is my code and I want to create 3 points which compare to my current location that which one is near to the current location.

Body:
You can calculate distance between two location and then compare the distance.

 private double distance(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1))
            * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lat1))
            * Math.cos(deg2rad(lat2))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

You can use this as below code

  LatLng near = new LatLng(33.549232, 73.125256);
        LatLng pass = new LatLng(33.549844, 73.125849);
        LatLng qareeb = new LatLng(33.549603, 73.124201);
        double distance = distance(near.latitude, near.longitude, pass.latitude, pass.longitude);


问:
Different predictions if running in Node instead of Browser (using the same model_web - python converted model)
pretty new to ML and tensorflow!

I made an object detection model with http://cloud.annotations.ai that permits to train and convert a model in different formats, tfjs (model_web) too.
That website provides also boilerplates for running the model within a browser (react app)... just like you do - probably it is the same code, didn't spend enough time.

So I have this model running inside a browser, giving prediction about objects in a photo with pretty good results considering the amount of example I gave and the prediction score (0.89). the given bounding box is good too.

But, unfortunately, I didn't have "just one video" to analyze frame by frame inside a browser, I've got plenty of them. So I decided to switch to node.js, porting the code as is.
Guess what? TF.js relies on DOM and browser components, and almost none examples that works with Node exists. So not a big deal, just spent a morning figuring out all the missing parts.
Finally I'm able to run my model over videos that are splitted in frames, at a decent speed - although having the "Hello there, use tfjs-node to gain speed" banner when I'm already using tfjs-node - but results seems odd.
Comparing the same picture with the same model_web folder gave the same prediction but with lower score (0.80 instead of 0.89) and a different bounding box, with object not centered at all.

(TL;DR)

Does tfjs have different implementation of the libraries (tfjs and tfjs-node) that makes different use of the same model? I don't think it can be a problem of input because - after a long search and fight - i figure out two ways to give the image to tf.browser.getPixel in Node (and I'm still wondering why I have to use a "browser" method inside tfjs-node). Anyone made comparisons?

So... that's the code I used, for your reference:

model_web is being loaded with tf.loadGraphModel("file://path/to/model_web/model.json");

two different ways to convert a JPG and make it works with tf.browser.getPixel()

```<code>const inkjet = require('inkjet');
const {createCanvas, loadImage} = require('canvas');

const decodeJPGInkjet = (file) => {
    return new Promise((rs, rj) => {
        fs.readFile(file).then((buffer) => {
            inkjet.decode(buffer, (err, decoded) => {
                if (err) {
                    rj(err);
                } else {
                    rs(decoded);
                }
            });
        });
    });
};

const decodeJPGCanvas = (file) => {
    return loadImage(file).then((image) => {
        const canvas = createCanvas(image.width, image.height);
        const ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, image.width, image.height);
        const data = ctx.getImageData(0, 0, image.width, image.height);
        return {data: new Uint8Array(data.data), width: data.width, height: data.height};
    });
};
</code>```

and that's the code that use the loaded model to give predictions - same code for node and browser, found at https://github.com/cloud-annotations/javascript-sdk/blob/master/src/index.js - doesn't works on node as it is, I changed require("@tensorflow/tfjs"); with require("@tensorflow/tfjs-node"); and replaced fetch with fs.read

```<code>const runObjectDetectionPrediction = async (graph, labels, input) => {
    const batched = tf.tidy(() => {
        const img = tf.browser.fromPixels(input);
        // Reshape to a single-element batch so we can pass it to executeAsync.
        return img.expandDims(0);
    });

    const height = batched.shape[1];
    const width = batched.shape[2];

    const result = await graph.executeAsync(batched);

    const scores = result[0].dataSync();
    const boxes = result[1].dataSync();

    // clean the webgl tensors
    batched.dispose();
    tf.dispose(result);

    const [maxScores, classes] = calculateMaxScores(
        scores,
        result[0].shape[1],
        result[0].shape[2]
    );

    const prevBackend = tf.getBackend();
    // run post process in cpu
    tf.setBackend("cpu");
    const indexTensor = tf.tidy(() => {
        const boxes2 = tf.tensor2d(boxes, [result[1].shape[1], result[1].shape[3]]);
        return tf.image.nonMaxSuppression(
            boxes2,
            maxScores,
            20, // maxNumBoxes
            0.5, // iou_threshold
            0.5 // score_threshold
        );
    });
    const indexes = indexTensor.dataSync();
    indexTensor.dispose();
    // restore previous backend
    tf.setBackend(prevBackend);

    return buildDetectedObjects(
        width,
        height,
        boxes,
        maxScores,
        indexes,
        classes,
        labels
    );
};
</code>```

答:
Do different implementation of the libraries (tfjs and tfjs-node) that makes different use of the same model

If the same model is deployed both in the browser and in nodejs, the prediction will be the same thing.

If the predicted value are different, it might be related to the tensor used for the prediction. The processing from the image to the tensor might be different resulting in different tensors being used for the prediction thus causing the output to be different.

i figure out two ways to give the image to tf.browser.getPixel in Node (and I'm still wondering why I have to use a "browser" method inside tfjs-node)

The canvas package use the system graphic to create the browser like canvas environment that can be used by nodejs. This makes it possible to use tf.browser namespace especially when dealing with image conversion. However it is still possible to use directly nodejs buffer to create a tensor.

Body:
pretty new to ML and tensorflow!

I made an object detection model with http://cloud.annotations.ai that permits to train and convert a model in different formats, tfjs (model_web) too.
That website provides also boilerplates for running the model within a browser (react app)... just like you do - probably it is the same code, didn't spend enough time.

So I have this model running inside a browser, giving prediction about objects in a photo with pretty good results considering the amount of example I gave and the prediction score (0.89). the given bounding box is good too.

But, unfortunately, I didn't have "just one video" to analyze frame by frame inside a browser, I've got plenty of them. So I decided to switch to node.js, porting the code as is.
Guess what? TF.js relies on DOM and browser components, and almost none examples that works with Node exists. So not a big deal, just spent a morning figuring out all the missing parts.
Finally I'm able to run my model over videos that are splitted in frames, at a decent speed - although having the "Hello there, use tfjs-node to gain speed" banner when I'm already using tfjs-node - but results seems odd.
Comparing the same picture with the same model_web folder gave the same prediction but with lower score (0.80 instead of 0.89) and a different bounding box, with object not centered at all.

(TL;DR)

Does tfjs have different implementation of the libraries (tfjs and tfjs-node) that makes different use of the same model? I don't think it can be a problem of input because - after a long search and fight - i figure out two ways to give the image to tf.browser.getPixel in Node (and I'm still wondering why I have to use a "browser" method inside tfjs-node). Anyone made comparisons?

So... that's the code I used, for your reference:

model_web is being loaded with tf.loadGraphModel("file://path/to/model_web/model.json");

two different ways to convert a JPG and make it works with tf.browser.getPixel()

const inkjet = require('inkjet');
const {createCanvas, loadImage} = require('canvas');

const decodeJPGInkjet = (file) => {
    return new Promise((rs, rj) => {
        fs.readFile(file).then((buffer) => {
            inkjet.decode(buffer, (err, decoded) => {
                if (err) {
                    rj(err);
                } else {
                    rs(decoded);
                }
            });
        });
    });
};

const decodeJPGCanvas = (file) => {
    return loadImage(file).then((image) => {
        const canvas = createCanvas(image.width, image.height);
        const ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, image.width, image.height);
        const data = ctx.getImageData(0, 0, image.width, image.height);
        return {data: new Uint8Array(data.data), width: data.width, height: data.height};
    });
};

and that's the code that use the loaded model to give predictions - same code for node and browser, found at https://github.com/cloud-annotations/javascript-sdk/blob/master/src/index.js - doesn't works on node as it is, I changed require("@tensorflow/tfjs"); with require("@tensorflow/tfjs-node"); and replaced fetch with fs.read

const runObjectDetectionPrediction = async (graph, labels, input) => {
    const batched = tf.tidy(() => {
        const img = tf.browser.fromPixels(input);
        // Reshape to a single-element batch so we can pass it to executeAsync.
        return img.expandDims(0);
    });

    const height = batched.shape[1];
    const width = batched.shape[2];

    const result = await graph.executeAsync(batched);

    const scores = result[0].dataSync();
    const boxes = result[1].dataSync();

    // clean the webgl tensors
    batched.dispose();
    tf.dispose(result);

    const [maxScores, classes] = calculateMaxScores(
        scores,
        result[0].shape[1],
        result[0].shape[2]
    );

    const prevBackend = tf.getBackend();
    // run post process in cpu
    tf.setBackend("cpu");
    const indexTensor = tf.tidy(() => {
        const boxes2 = tf.tensor2d(boxes, [result[1].shape[1], result[1].shape[3]]);
        return tf.image.nonMaxSuppression(
            boxes2,
            maxScores,
            20, // maxNumBoxes
            0.5, // iou_threshold
            0.5 // score_threshold
        );
    });
    const indexes = indexTensor.dataSync();
    indexTensor.dispose();
    // restore previous backend
    tf.setBackend(prevBackend);

    return buildDetectedObjects(
        width,
        height,
        boxes,
        maxScores,
        indexes,
        classes,
        labels
    );
};


问:
Dynamic rowspan in angular
Number of persons and their mobiles numbers are dynamic. I need to show this in table.

Data can contain any number of pname and mobile numbers.

```<code>dataList = [
 {
  pname: "abc",
  numbers: [{mobile1: 123, mobile2: 234}]
 },
{
  pname: "mno",
  numbers: [{mobile1: 125, mobile2: 237}]
 }
]
</code>```

Template

```<code><tr *ngFor="let data of dataList">
 <td  [attr.rowspan]="data.numbers.lenght">data.pname</td>
 <td>data.numbers</td> // Here how do I show all mobile numbers of the person.
</tr>
</code>```

Expected output is of below code.

table, th, td {
    border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th>Pname</th>
    <th>Numbers</th>
  </tr>
  <tr>
    <td rowspan="2">Abc</td>
    <td>123</td>
  </tr>
  <tr>
    <td>234</td>
  </tr>
  <tr>
    <td rowspan="2">Mno</td>
    <td>125</td>
  </tr>
  <tr>
    <td>237</td>
  </tr>
</table></code>```

Problem I am facing is I need to add tr after each run of *ngFor and the number of tr will depend on length of numbers array to make row span.

答:
Simple.

You don't need index and nested ng-container.

```<code><table>
    <ng-container *ngFor="let data of dataList">
        <tr>
            <td [attr.rowspan]="data.numbers.length + 1">{{data.pname}}</td>
        </tr>
        <tr *ngFor="let number of data.numbers;">
          <td>{{number}}</td>
        </tr>
    </ng-container>
</table>
</code>```

Working example.
https://stackblitz.com/edit/angular-yrose8?file=src%2Fapp%2Fapp.component.html

Title: Dynamic rowspan in angular

Body:
Number of persons and their mobiles numbers are dynamic. I need to show this in table.

Data can contain any number of pname and mobile numbers.

dataList = [
 {
  pname: "abc",
  numbers: [{mobile1: 123, mobile2: 234}]
 },
{
  pname: "mno",
  numbers: [{mobile1: 125, mobile2: 237}]
 }
]

Template

 data.pname
 data.numbers	 // Here how do I show all mobile numbers of the person.

Expected output is of below code.

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

    Pname
    Numbers

    Abc
    123

    234

    Mno
    125

    237

Problem I am facing is I need to add tr after each run of *ngFor and the number of tr will depend on length of numbers array to make row span.

Body:
Simple.

You don't need index and nested ng-container.

<table>
    <ng-container *ngFor="let data of dataList">
        <tr>
            <td [attr.rowspan]="data.numbers.length + 1">{{data.pname}}</td>
        </tr>
        <tr *ngFor="let number of data.numbers;">
          <td>{{number}}</td>
        </tr>
    </ng-container>
</table>

Working example.
https://stackblitz.com/edit/angular-yrose8?file=src%2Fapp%2Fapp.component.html


问:
Does this observable leak memory?
I'm fairly new to observables and according to this article. The examples below leaks memory. However, I saw tonnes of tutorials online showing examples like this.

```<code>someObservable.subscribe(data => {
   // do something
});
</code>```

Does the code above leak memory? Do we always have to unsubscribe? How about http calls too?

```<code>this.http.get<Any>('someurl').subscribe(response => {
    // do something
});
</code>```

What are the general best practices for observables?

答:
HTTP calls and router events are finite, so you don't have to unsubscribe from them.

Everything else, yes you should unsubscribe from them because they generate memory leaks.

I like to subscribe and unsubscribe using the async pipe for data I am presenting in the HTML. Using the async pipe, when the component gets destroyed, the observable is automatically unsubscribed. For event subscriptions (actual .subscribe), I like to use the takeUntil operator.

The following article shows when to unsubscribe but I always unsubscribe when I need to/when component gets destroyed. Better be safe than sorry.

https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3

Title: Does this observable leak memory?

Body:
I'm fairly new to observables and according to this article. The examples below leaks memory. However, I saw tonnes of tutorials online showing examples like this.

someObservable.subscribe(data => {
   // do something
});

Does the code above leak memory? Do we always have to unsubscribe? How about http calls too?

this.http.get<Any>('someurl').subscribe(response => {
    // do something
});

What are the general best practices for observables?


问:
How to integrate aws S3 to my android app?
I am trying to figure out what is the best practice to integrate AWS S3 in my android app.

As a pre-work I have an s3 bucket which I can upload\download\delete using the python/java SDK and now I want to implement it in my android app.
I found on the web different approaches and can not get my head straight what is the recently\correct way doing it.
My research brought the following result:

mobile hub - https://grokonez.com/android/uploaddownload-files-images-amazon-s3-android
or in the amazon offical - https://docs.aws.amazon.com/aws-mobile/latest/developerguide/mobile-hub-add-aws-mobile-user-data-storage.html

user pool\cognito -https://101apps.co.za/index.php/item/195-android-and-amazon-s3-secure-file-storage-in-the-cloud

github project - https://github.com/nimran/Amazon-S3-Integration-in-Android - when i clone and try to activate it most of the aws calls are deprect.

another amazon official, this time using Android SDK - https://aws-amplify.github.io/docs/android/storage

I am looking for a guide\repo which is up to date and explain the correct way to integrate S3 in an android app.
thx

答:
Check the sample app: aws labs.
Build the app and customize it accordingly. Just change the settings in "aws configuration file".

Prerequisite:

Android Studio

S3 bucket

aws cognito (identity pool)

aws IAM role (identity pool role, having access to S3 bucket)

Hope this helps!


问:
If possible how can one embed PostgreSQL?
If it's possible, I'm interested in being able to embed a PostgreSQL database, similar to sqllite.  I've read that it's not possible.  I'm no database expert though, so I want to hear from you.

Essentially I want PostgreSQL without all the configuration and installation.  If it's possible, tell me how.

答:
You cannot embed it, nor should you try.

For embedding you should use sqlite as you mentioned or firebird rdbms.

OwnerDisplayName: Brian R. Bondy

ContentLicense: CC BY-SA 2.5


问:
Help in specify attribute of dynamic generated table in jquery
I am facing a problem to how to add the attributes of table like width, cell spacing.

```<code>var newTable = $("<table />",{id: 'myTable'+tab_counter});
newTable.appendTo('#dialog'+tab_counter);
</code>```

if i add in table tag it still doesn't do anything.

答:
If you can predefine a style, do that.

```<code>var newTable = $('<table id="myTable'+tab_counter+'" class="myTableCSS"></table>');
</code>```

If you have to do it inline, just do it at generation time:

```<code>var newTable = $('<table id="myTable'+tab_counter+'" style="width:500px;border-collapse:collapse"></table>');
</code>```

Body:
I am facing a problem to how to add the attributes of table like width, cell spacing.

var newTable = $("
",{id: 'myTable'+tab_counter});
newTable.appendTo('#dialog'+tab_counter);

if i add in table tag it still doesn't do anything.

Body:
If you can predefine a style, do that.

var newTable = $('<table id="myTable'+tab_counter+'" class="myTableCSS"></table>');

If you have to do it inline, just do it at generation time:

var newTable = $('<table id="myTable'+tab_counter+'" style="width:500px;border-collapse:collapse"></table>');


问:
Clear all sort fields VBA
I am trying to sort data through excel VBA but it is already sorted by a different header.  How would I clear all the sort fields before I set the new one? I have tried Sort.SortFields.Clear but it hasn't worked. Any help would be greatly appreciated. Here's the code I'm using:

```<code> Sheet9.Activate

Columns("J:J").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1, "J").Value = "InternalID"
Set rng2 = FindHeader("CLIENT NAME", Sheet9.Name)

Count = 1

Sheet9.Cells.Select

With Sheet9.Sort
        .SortFields.Clear
        .SortFields.Add Key:=rng2, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
</code>```

答:
```<code>ActiveSheet.Range("Your_Range_Value").AutoFilter Field:=1
</code>```

I did this for every column that has a sort field and it clears them out. Where Field:=X is the column number in your range that you want to clear.

This is what I have in my Workbook. Sheet1 is code name of sheet, and rng is string representing the range value ("B4:G1500")

```<code>' Clear all filters
Sheet1.Range(rng).AutoFilter Field:=1
Sheet1.Range(rng).AutoFilter Field:=2
Sheet1.Range(rng).AutoFilter Field:=3
Sheet1.Range(rng).AutoFilter Field:=4
Sheet1.Range(rng).AutoFilter Field:=5
Sheet1.Range(rng).AutoFilter Field:=6
</code>```

Title: Clear all sort fields VBA

Body:
I am trying to sort data through excel VBA but it is already sorted by a different header.  How would I clear all the sort fields before I set the new one? I have tried Sort.SortFields.Clear but it hasn't worked. Any help would be greatly appreciated. Here's the code I'm using:

 Sheet9.Activate

Columns("J:J").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(1, "J").Value = "InternalID"
Set rng2 = FindHeader("CLIENT NAME", Sheet9.Name)

Count = 1

Sheet9.Cells.Select

With Sheet9.Sort
        .SortFields.Clear
        .SortFields.Add Key:=rng2, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Body:
ActiveSheet.Range("Your_Range_Value").AutoFilter Field:=1

I did this for every column that has a sort field and it clears them out. Where Field:=X is the column number in your range that you want to clear.

This is what I have in my Workbook. Sheet1 is code name of sheet, and rng is string representing the range value ("B4:G1500")

' Clear all filters
Sheet1.Range(rng).AutoFilter Field:=1
Sheet1.Range(rng).AutoFilter Field:=2
Sheet1.Range(rng).AutoFilter Field:=3
Sheet1.Range(rng).AutoFilter Field:=4
Sheet1.Range(rng).AutoFilter Field:=5
Sheet1.Range(rng).AutoFilter Field:=6


问:
regular expressions to convert asp page response.writes to html
I have this...

```<code>Response.write "<table width=""700"" border=""0"">"

    Response.write "<tr><td width=""10%""> <td align=center pagetitle2strong""><br><strong>Advanced Sales Search</strong><br><br></td></tr>"

    Response.write "<tr><td width=""10%""> <td>"

    ShowSearchDisclaimer

    Response.write "<table border=0><tr><td width=""10%""> <td>"

    ShowForm

    Response.write "</td></td></tr></table>"

    Response.write "</td></tr></table>"
</code>```

Which in view source looks like this...just one big blob.

```<code><table width="700" border="0"><tr><td width="10%"> </td><td align="right" ><h1>Search Sales or Transfers</h1></td></tr><tr><td width="10%"> </td><td><table width=600 border=0><tr><td><font size=+1><b>By using this page you are agreeing to the following disclaimer.</b></font></td></tr><tr><td> </td></tr><tr><td>The information appearing on this website was extracted from the records of the office of the Sarasota County Property Appraiser. Our goal is to provide you with the most accurate information possible. The information maintained on this website should not be relied upon for any purposes except for those of the Property Appraiser and his staff. The Sarasota County Property Appraiser accepts no responsibility for the inappropriate use or the misinterpretation of data. No warranties, expressed or implied, are provided for the data herein. The property values relate to the last valuation date, or to preliminary values when noted. The data is subject to change.</td></tr><tr><td> </td></tr><tr><td>By proceeding with a property search you are stating that the notice has been read and that you understand and agree with its contents. The data contained on this site is intended for information purposes only. It is based on the best information available at the time of posting and is not warranted. The data may not reflect the most current records.</td></tr><tr><td> </td></tr><tr><td><a href="/Content/Disclaimer.asp">View Full Disclaimer Here.</a></td></tr><tr><td> </td></tr></table><table><form METHOD=POST NAME=frmPrice ACTION=/search/sales_search_results.asp><tr><td FormDisplayText"><b>Recorded Consideration<p class="teaser">Sale Price</p></b></td><td align=right><input TYPE=text SIZE=8 NAME=AmtFrom title="Minimum Price"> <input TYPE=text SIZE=8 NAME=AmtTo title="Maximum Price"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><form METHOD=POST NAME=frmDate ACTION=/search/sales_search_results.asp><tr><td FormDisplayText"><b>Transaction Date</b></td><td align=right><input TYPE=text SIZE=8 NAME=DateFrom title="Minimum Date"> <input TYPE=text SIZE=8 NAME=DateTo title="Maximum Date"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><form METHOD=POST NAME=frmInstrument ACTION=/search/sales_instrument_search_results.asp><tr><td FormDisplayText"><b>Instrument Number</b></td><td align=right><input TYPE=text SIZE=22 NAME=kw1 title="Enter Complete or Partial Instrument Number"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><form METHOD=POST NAME=frmDeedType ACTION=/search/sales_deed_type_search_results.asp><tr><td FormDisplayText"><b>Instrument Type</b></td><td align=right><input TYPE=text SIZE=22 NAME=kw1 title="Enter Exact Deed Type"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><form METHOD=POST NAME=frmGrantor ACTION=/search/sales_grantor_search_results.asp><tr><td FormDisplayText"><b>Seller/Grantor</b></td><td align=right><input TYPE=text SIZE=8 name=kw1 title="Enter part of Grantor's Name"> <input TYPE=text SIZE=8 name=kw2 title="Enter part of Grantor's Name"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><form METHOD=POST NAME=frmSubCode ACTION=/search/sales_search_results.asp?type=code><tr><td FormDisplayText"><b>Subdivision Code</b></td><td align=right><input TYPE=text SIZE=22 name=SubCode title="Enter exact Subdivision Code"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><form METHOD=POST NAME=frmSubName ACTION=/search/sales_search_results.asp?type=name><tr><td FormDisplayText"><b>Subdivision Name</b></td><td align=right><input TYPE=text SIZE=22 name=SubName title="Enter all or part of the Subdivision Name"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><form METHOD=POST NAME=frmUseCode ACTION=/search/sales_search_results.asp><tr><td FormDisplayText"><b>Land Use Code</b></td><td align=right><input TYPE=text SIZE=8 NAME=UseFrom title="Minimum LUC"> <input TYPE=text SIZE=8 NAME=UseTo title="Maximum LUC"> <input type=submit value=Submit title="Click to view search results"></td></tr></form><tr><td FormDisplayText"> </td></tr><tr><td FormDisplayText"><b>Lookup Subdivision Code</b></td><td align=right><input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/subdivision_codes.asp?type=sales'></td></tr></form><tr><td FormDisplayText"><b>Lookup Use Code</b></td><td align=right><input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/use_codes.asp?type=sales'></td></tr></form><tr><td FormDisplayText"><b>Lookup Instrument Type</b></td><td align=right><input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/deed_types.asp'></td></tr></form><tr><td FormDisplayText"><b>Lookup Transaction Qual. Codes</b></td><td align=right><input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/sales_qualification_codes.asp'></td></tr></form></table></td></tr></table>
</code>```

I want a regular expression that will allow me to quickly
change all the response.write "<some html here>" & sometimes with variables & </more html>"

TO

```<code>%>
<my html><%=somevariable%>
<%
</code>```

Also, the original code follows no form whatsoever, so rarely are attribute values correctly enclosed in quotations.

I want to do this because it is really hard to debug the "blob" plus, when I'm in the IDE, it'd be real nice to be able to see the rendered html. PLUS corret me if I'm wrong but isn't this using a lot of my server side resources? Since all of the response.write commands have to be processed server side?  Anyways.  I'd really appreciate anyone who can think of a way to quickly recode this type of a situation.

Here is a page I already did by hand...

```<code>Sub ShowCriteriaRow()

    If strPrint <> "yes" then

        %>
        <br />
        <input type="text" id="kw1" name="kw1" size="20" value="<%=Keyword1 %>"/><%

        If (PageType <> "parcel" and PageType <> "lastname"and PageType <> "situs") Then
            %>
        <input type="text" id="kw2" name="kw2" size="20" value="<%=Keyword2 %>"/><%
        End If

        If PageType = "STR" Then
            %>
        <input type="text" id="kw3" name="kw3" size="20" value="<%=Keyword3 %>"/><%
        End If

        %>
        <input type="submit" name="submit" id="submit" value="Resubmit" /><%

        ShowExportButton

    Else
        Response.Write "<b>Keywords:</b> " & Keyword1
            If Keyword2 <> "" Then Response.Write ", " & Keyword2
            If Keyword3 <> "" Then Response.Write ", " & Keyword3
        Response.Write "       "
    End If

    %>
        </td>
    </tr><%
</code>```

It's a start.  I can't change too much of the underlying structure as it's pretty spaghetti like.

答:
I don't think Regex is the answer, nor applicable here.

Personally I'd solve your issue with something more like the following to make both the script and the output HTML much more readable:

```<code>tableString  = "<table width=""700"" border=""0"">" & _
                    "<tr><td width=""10%""> <td align=center pagetitle2strong""><br><strong>Advanced Sales Search</strong><br><br></td></tr>" & _
                        "<tr>" & _
                        "<td width=""10%""> <td>" & _
                        "{SearchDisclaimer}" & _
                        "<table border=0>" & _
                            "<tr><td width=""10%""> <td>" & _
                                "{ShowForm}" & _
                            "</td></td></tr>" & _
                        "</table>" & _
                        "</td></tr>" & _
                "</table>"

tableString = replace(tableString, "{SearchDisclaimer}", ShowSearchDisclaimer())
tableString = replace(tableString, "{ShowForm}", ShowForm())

Response.write(tableString)
</code>```

Then change your Subs to functions which return HTML as a string such as this:

```<code>function ShowCriteriaRow()
    outputString = ""
    if strPrint <> "yes" then
        outputString = outputString & "<input id=""textbox"" name=""foo"" value=""bar"" />"
    end if

    ShowCriteriaRow = outputString
end function
</code>```

Body:
I have this...

Response.write "
"

    Response.write "

Advanced Sales Search

"

    Response.write "
 "

    ShowSearchDisclaimer

    Response.write "

 "

    ShowForm

    Response.write "

"

    Response.write "

"

Which in view source looks like this...just one big blob.

Search Sales or Transfers

By using this page you are agreeing to the following disclaimer.

The information appearing on this website was extracted from the records of the office of the Sarasota County Property Appraiser. Our goal is to provide you with the most accurate information possible. The information maintained on this website should not be relied upon for any purposes except for those of the Property Appraiser and his staff. The Sarasota County Property Appraiser accepts no responsibility for the inappropriate use or the misinterpretation of data. No warranties, expressed or implied, are provided for the data herein. The property values relate to the last valuation date, or to preliminary values when noted. The data is subject to change.

By proceeding with a property search you are stating that the notice has been read and that you understand and agree with its contents. The data contained on this site is intended for information purposes only. It is based on the best information available at the time of posting and is not warranted. The data may not reflect the most current records.

View Full Disclaimer Here.

<form METHOD=POST NAME=frmPrice ACTION=/search/sales_search_results.asp>
Recorded Consideration
Sale Price
	<input TYPE=text SIZE=8 NAME=AmtFrom title="Minimum Price"> <input TYPE=text SIZE=8 NAME=AmtTo title="Maximum Price"> <input type=submit value=Submit title="Click to view search results">
</form><form METHOD=POST NAME=frmDate ACTION=/search/sales_search_results.asp>
Transaction Date	<input TYPE=text SIZE=8 NAME=DateFrom title="Minimum Date"> <input TYPE=text SIZE=8 NAME=DateTo title="Maximum Date"> <input type=submit value=Submit title="Click to view search results">
</form><form METHOD=POST NAME=frmInstrument ACTION=/search/sales_instrument_search_results.asp>
Instrument Number	<input TYPE=text SIZE=22 NAME=kw1 title="Enter Complete or Partial Instrument Number"> <input type=submit value=Submit title="Click to view search results">
</form><form METHOD=POST NAME=frmDeedType ACTION=/search/sales_deed_type_search_results.asp>
Instrument Type	<input TYPE=text SIZE=22 NAME=kw1 title="Enter Exact Deed Type"> <input type=submit value=Submit title="Click to view search results">
</form><form METHOD=POST NAME=frmGrantor ACTION=/search/sales_grantor_search_results.asp>
Seller/Grantor	<input TYPE=text SIZE=8 name=kw1 title="Enter part of Grantor's Name"> <input TYPE=text SIZE=8 name=kw2 title="Enter part of Grantor's Name"> <input type=submit value=Submit title="Click to view search results">
</form><form METHOD=POST NAME=frmSubCode ACTION=/search/sales_search_results.asp?type=code>
Subdivision Code	<input TYPE=text SIZE=22 name=SubCode title="Enter exact Subdivision Code"> <input type=submit value=Submit title="Click to view search results">
</form><form METHOD=POST NAME=frmSubName ACTION=/search/sales_search_results.asp?type=name>
Subdivision Name	<input TYPE=text SIZE=22 name=SubName title="Enter all or part of the Subdivision Name"> <input type=submit value=Submit title="Click to view search results">
</form><form METHOD=POST NAME=frmUseCode ACTION=/search/sales_search_results.asp>
Land Use Code	<input TYPE=text SIZE=8 NAME=UseFrom title="Minimum LUC"> <input TYPE=text SIZE=8 NAME=UseTo title="Maximum LUC"> <input type=submit value=Submit title="Click to view search results">
</form>

Lookup Subdivision Code	<input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/subdivision_codes.asp?type=sales'>
</form>
Lookup Use Code	<input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/use_codes.asp?type=sales'>
</form>
Lookup Instrument Type	<input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/deed_types.asp'>
</form>
Lookup Transaction Qual. Codes	<input type=button value=Lookup title="Click to lookup code values" onclick=location.href='/search/sales_qualification_codes.asp'>
</form>

I want a regular expression that will allow me to quickly
change all the response.write "<some html here>" & sometimes with variables & </more html>"

TO

%>
<my html><%=somevariable%>
<%

Also, the original code follows no form whatsoever, so rarely are attribute values correctly enclosed in quotations.

I want to do this because it is really hard to debug the "blob" plus, when I'm in the IDE, it'd be real nice to be able to see the rendered html. PLUS corret me if I'm wrong but isn't this using a lot of my server side resources? Since all of the response.write commands have to be processed server side?  Anyways.  I'd really appreciate anyone who can think of a way to quickly recode this type of a situation.

Here is a page I already did by hand...

Sub ShowCriteriaRow()

    If strPrint <> "yes" then

        %>

        <input type="text" id="kw1" name="kw1" size="20" value="<%=Keyword1 %>"/><%

        If (PageType <> "parcel" and PageType <> "lastname"and PageType <> "situs") Then
            %>
        <input type="text" id="kw2" name="kw2" size="20" value="<%=Keyword2 %>"/><%
        End If

        If PageType = "STR" Then
            %>
        <input type="text" id="kw3" name="kw3" size="20" value="<%=Keyword3 %>"/><%
        End If

        %>
        <input type="submit" name="submit" id="submit" value="Resubmit" /><%

        ShowExportButton

    Else
        Response.Write "Keywords: " & Keyword1
            If Keyword2 <> "" Then Response.Write ", " & Keyword2
            If Keyword3 <> "" Then Response.Write ", " & Keyword3
        Response.Write "       "
    End If

    %>

<%

It's a start.  I can't change too much of the underlying structure as it's pretty spaghetti like.

Body:
I don't think Regex is the answer, nor applicable here.

Personally I'd solve your issue with something more like the following to make both the script and the output HTML much more readable:

tableString  = "<table width=""700"" border=""0"">" & _
                    "<tr><td width=""10%"">&nbsp;<td align=center pagetitle2strong""><br><strong>Advanced Sales Search</strong><br><br></td></tr>" & _
                        "<tr>" & _
                        "<td width=""10%"">&nbsp;<td>" & _
                        "{SearchDisclaimer}" & _
                        "<table border=0>" & _
                            "<tr><td width=""10%"">&nbsp;<td>" & _
                                "{ShowForm}" & _
                            "</td></td></tr>" & _
                        "</table>" & _
                        "</td></tr>" & _
                "</table>"

tableString = replace(tableString, "{SearchDisclaimer}", ShowSearchDisclaimer())
tableString = replace(tableString, "{ShowForm}", ShowForm())

Response.write(tableString)

Then change your Subs to functions which return HTML as a string such as this:

function ShowCriteriaRow()
    outputString = ""
    if strPrint <> "yes" then
        outputString = outputString & "<input id=""textbox"" name=""foo"" value=""bar"" />"
    end if

    ShowCriteriaRow = outputString
end function


问:
How to access generated output file in Docker
I have dockerized my python application. This application connects with Oracle database, pull out 10 rows from a table and then generate excel. I was able to build my image successfully with all dependent libraries and it's also executing fine. Now, I am not sure how to get generated excel file (batchtable.xlsx) in docker.
I am new to docker and would need your suggestion. I have checked output without storing records into excel and it's coming fine on console, so there is no code issue.

Dockerfile

```<code>FROM python:3.7.4-slim-buster

RUN apt-get update && apt-get install -y libaio1 wget unzip

WORKDIR /opt/oracle
COPY File.py /opt/oracle

RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip && \
    unzip instantclient-basiclite-linuxx64.zip && rm -f instantclient-basiclite-linuxx64.zip && \
    cd /opt/oracle/instantclient* && rm -f *jdbc* *occi* *mysql* *README *jar uidrvci genezi adrci && \
    echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf && ldconfig

RUN python -m pip install --upgrade pip
RUN python -m pip install cx_Oracle
RUN python -m pip install pandas
RUN python -m pip install openpyxl

CMD [ "python", "/opt/oracle/File.py" ]
</code>```

File.py

```<code>import cx_Oracle
import pandas as pd

#creating database connection
dsn_tns = cx_Oracle.makedsn('dev-tr01.com', '1222', service_name='ast041.com')
conn = cx_Oracle.connect(user=r'usr', password='3451', dsn=dsn_tns)
c = conn.cursor()

query ='SELECT * FROM Employee WHERE ROWNUM <10'
result = pd.read_sql(query, con=conn)
result.to_excel("batchtable.xlsx")

conn.close()
</code>```

答:
Add a -v switch to your docker run command. For instance:

```<code>docker run -v <path>:/output YOUR_IMAGE_NAME
</code>```

Replace path with a valid path on your machine, for instance c:\temp on Windows.

Change your program to write to that directory:

```<code>result.to_excel("/output/batchtable.xlsx")
</code>```

If running Docker Desktop, in the Docker Desktop settings make sure your drive is shared.

Body:
I have dockerized my python application. This application connects with Oracle database, pull out 10 rows from a table and then generate excel. I was able to build my image successfully with all dependent libraries and it's also executing fine. Now, I am not sure how to get generated excel file (batchtable.xlsx) in docker.
I am new to docker and would need your suggestion. I have checked output without storing records into excel and it's coming fine on console, so there is no code issue.

Dockerfile

FROM python:3.7.4-slim-buster

RUN apt-get update && apt-get install -y libaio1 wget unzip

WORKDIR /opt/oracle
COPY File.py /opt/oracle

RUN wget https://download.oracle.com/otn_software/linux/instantclient/instantclient-basiclite-linuxx64.zip && \
    unzip instantclient-basiclite-linuxx64.zip && rm -f instantclient-basiclite-linuxx64.zip && \
    cd /opt/oracle/instantclient* && rm -f *jdbc* *occi* *mysql* *README *jar uidrvci genezi adrci && \
    echo /opt/oracle/instantclient* > /etc/ld.so.conf.d/oracle-instantclient.conf && ldconfig

RUN python -m pip install --upgrade pip
RUN python -m pip install cx_Oracle
RUN python -m pip install pandas
RUN python -m pip install openpyxl

CMD [ "python", "/opt/oracle/File.py" ]

File.py

import cx_Oracle
import pandas as pd

#creating database connection
dsn_tns = cx_Oracle.makedsn('dev-tr01.com', '1222', service_name='ast041.com')
conn = cx_Oracle.connect(user=r'usr', password='3451', dsn=dsn_tns)
c = conn.cursor()

query ='SELECT * FROM Employee WHERE ROWNUM <10'
result = pd.read_sql(query, con=conn)
result.to_excel("batchtable.xlsx")

conn.close()

Body:
Add a -v switch to your docker run command. For instance:

docker run -v <path>:/output YOUR_IMAGE_NAME

Replace path with a valid path on your machine, for instance c:\temp on Windows.

Change your program to write to that directory:

result.to_excel("/output/batchtable.xlsx")

If running Docker Desktop, in the Docker Desktop settings make sure your drive is shared.


问:
I have added "Previous Quarter" in jquery datatable but i am not getting the expected result

If todays date is 19/Feb/2020 then i want the Previous Quarter to be set as 1/Oct/2019 to 31/Dec/2019 what should be in code to make it possible i tried

var quarter = moment().quarter();
dateRange['Previous Quarter'] = [moment().quarter(quarter).endOf('quarter')];

Here "Previous Quarter"  represents "the quarter before the current quarter" .

答:
//Selects the quarter before the current quarter.

dateRange['Previous Quarter'] = [moment().subtract(1, 'quarter').startOf('quarter'), moment().subtract(1, 'quarter').endOf('quarter')];

it works!!


问:
How do I use foreach within a while loop
I have a script that displays all the values in a db table.  I'd like to be able to update the price value of each row individually on clicking the update button but as it's in a while loop it's only updating the final value successfully.  I realise this probably requires foreach but I can't figure where to code it within the loop to send the data from each row to the processing script on the next page.  Can anyone help?  Thank you!

Display script

```<code><h2>Boiler Prices</h2>
<?php
$sql = "SELECT * FROM emb_prices_boilers ORDER BY id ASC";
$result = $connection->query($sql);

if ($result->num_rows > 0) {

  /* Start Form and Table ---------------------------------------------------------*/

  echo "<form action='../admin/actions/set-boiler-price.php' method='post'>";
  echo "<table id='boiler-prices'>
  <tr>
    <th>ID</th>
    <th>Type</th>
    <th>Boiler</th>
    <th>Ref</th>
    <th>Price</th>
  </tr>";

  /* Start Loop and Variables --------------------------------------------*/

  while($row = $result->fetch_assoc()) {

  $id = $row["id"];
  $type = $row["type"];
  $manufacturer = $row["manufacturer"];
  $model = $row["model"];
  $boilerref = $row["boilerref"];
  $price = $row["price"];

  // output data of each row
  echo "
  <tr>
    <td>" .$id. "</td>
    <td>" .$type. "</td>
    <td>" .$manufacturer. " " .$model. "</td>
    <td>" .$boilerref. "</td>
    <td>£<input type='text' name='price' value='" .$price. "' /><input type='hidden' name='boilerref' value='" .$boilerref. "' /><input type='submit' value='update' /></td>
  </tr>";

  }
/* End Loop -------------------------------------------------------*/

echo "</table>";
echo "</form>";
/* End Table and Form -------------------------------------------------------*/

}

else {

echo "0 results";

}

?>
</code>```

Processing script

```<code><?php

$boilerref = $_POST['boilerref'];
$price = $_POST['price'];

if ($setboilerprice = mysqli_prepare($connection, "UPDATE  emb_prices_boilers SET price = ? WHERE boilerref = ?")
) {

/* bind parameters for markers */
mysqli_stmt_bind_param($setboilerprice, "ds", $price, $boilerref );

/* execute query */
mysqli_stmt_execute($setboilerprice);

/* close statement */
mysqli_stmt_close($setboilerprice);

}
else {
    echo "error: Failed to write to db";
}

?>
</code>```

答:
What you need is to create a separate form for each record. Remove <form>/</form> tags from the beginning and the end of
 and use this code in your last td:

```<code>echo "
    ...
    <td>
        <form action='../admin/actions/set-boiler-price.php' method='post'>
            £<input type='text' name='price' value='" .$price. "' />
            <input type='hidden' name='boilerref' value='" .$boilerref. "' />
            <input type='submit' value='update' />
        </form>
    </td>
</tr>";
</code>```

With such mark up each form will send it's own data to your set-boiler-price.php and updating will work as you expect.

Body:
I have a script that displays all the values in a db table.  I'd like to be able to update the price value of each row individually on clicking the update button but as it's in a while loop it's only updating the final value successfully.  I realise this probably requires foreach but I can't figure where to code it within the loop to send the data from each row to the processing script on the next page.  Can anyone help?  Thank you!

Display script

Boiler Prices

<?php
$sql = "SELECT * FROM emb_prices_boilers ORDER BY id ASC";
$result = $connection->query($sql);

if ($result->num_rows > 0) {

  /* Start Form and Table ---------------------------------------------------------*/

  echo "<form action='../admin/actions/set-boiler-price.php' method='post'>";
  echo "

    ID
    Type
    Boiler
    Ref
    Price

";

  /* Start Loop and Variables --------------------------------------------*/

  while($row = $result->fetch_assoc()) {

  $id = $row["id"];
  $type = $row["type"];
  $manufacturer = $row["manufacturer"];
  $model = $row["model"];
  $boilerref = $row["boilerref"];
  $price = $row["price"];

  // output data of each row
  echo "

    " .$id. "
    " .$type. "
    " .$manufacturer. " " .$model. "
    " .$boilerref. "
    £<input type='text' name='price' value='" .$price. "' /><input type='hidden' name='boilerref' value='" .$boilerref. "' /><input type='submit' value='update' />

";

  }
/* End Loop -------------------------------------------------------*/

echo "
";
echo "</form>";
/* End Table and Form -------------------------------------------------------*/

}

else {

echo "0 results";

}

?>

Processing script

<?php

$boilerref = $_POST['boilerref'];
$price = $_POST['price'];

if ($setboilerprice = mysqli_prepare($connection, "UPDATE  emb_prices_boilers SET price = ? WHERE boilerref = ?")
) {

/* bind parameters for markers */
mysqli_stmt_bind_param($setboilerprice, "ds", $price, $boilerref );

/* execute query */
mysqli_stmt_execute($setboilerprice);

/* close statement */
mysqli_stmt_close($setboilerprice);

}
else {
    echo "error: Failed to write to db";
}

?>

Body:
What you need is to create a separate form for each record. Remove <form>/</form> tags from the beginning and the end of <table> and use this code in your last td:

echo "
    ...
    <td>
        <form action='../admin/actions/set-boiler-price.php' method='post'>
            &pound;<input type='text' name='price' value='" .$price. "' />
            <input type='hidden' name='boilerref' value='" .$boilerref. "' />
            <input type='submit' value='update' />
        </form>
    </td>
</tr>";

With such mark up each form will send it's own data to your set-boiler-price.php and updating will work as you expect.


问:
Mysql error when try to update a table from another table
I need to update a field in TableA from the same field on TableB

```<code>UPDATE TableA
SET TableA.categories = (
    SELECT TableB.categories
    FROM TableB
    WHERE TableB.title = TableA.title
);
</code>```

I get this error :

Error in query (1242): Subquery returns more than 1 row

答:
If you are updating more than one row then subquery will not work, try using JOIN UPDATE</p>

```<code>UPDATE TableA
JOIN TableB ON TableB.title = TableA.title AND TableB.uid = TableA.uid
SET TableA.categories = TableB.categories;
</code>```

Body:
I need to update a field in TableA from the same field on TableB

UPDATE TableA
SET TableA.categories = (
    SELECT TableB.categories
    FROM TableB
    WHERE TableB.title = TableA.title
);

I get this error :

Error in query (1242): Subquery returns more than 1 row

Body:
If you are updating more than one row then subquery will not work, try using JOIN UPDATE

UPDATE TableA
JOIN TableB ON TableB.title = TableA.title AND TableB.uid = TableA.uid
SET TableA.categories = TableB.categories;


问:
Can a C# program be cross-platform?
I'm a newbie to programming, and I'm considering using C# to write a VERY simple program that simply edits a text file.

Will it work on Macs and Linux? What will work?

I want to know what makes a program cross-platform?

答: C# is cross-platform thanks to .NET Core, but without a cross-platform User Interface library you can only make very basic console programs with it. In order to make cross-platform apps for Windows, Mac and Linux you need a cross-platform User Interface library like Nevron Open Vision </p>

Title: Can a C# program be cross-platform?


问:
MySql Table Insert if not exist otherwise update
```<code>UPDATE AggregatedData SET datenum="734152.979166667",
Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667";
</code>```

It works if the datenum exists, but  I want to insert this data as a new row if the datenum does not exist.

UPDATE

the datenum is unique but that's not the primary key

答:
Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

Body:
UPDATE AggregatedData SET datenum="734152.979166667",
Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667";

It works if the datenum exists, but  I want to insert this data as a new row if the datenum does not exist.

UPDATE

the datenum is unique but that's not the primary key


问:
How to fix "Call to a member function xy on array" without using foreach?
I have an object inside an array stored in the variable $image

```<code>array(1) { [250]=> object(Magento\Framework\DataObject)#11025 (1) { ["_data":protected]=> array(26) { ["value_id"]=> string(3) "250" ["file"]=> string(58) "/i/n/insetktenschutz-doppeltuer-im-zargenrahmen_37_1_3.jpg"  ... } } }
</code>```

If I try to return a value, e.g. file like this:

```<code>echo $image->getFile();
</code>```

Then of course I get Fatal error: Uncaught Error: Call to a member function getFile() on array

So I tried to call it like this:

```<code>$image = $image[0];
echo $image->getFile();
</code>```

But I get Exception #0 (Exception): Notice: Undefined offset: 0

So I tried to cast it to an object:

```<code>$image = (object) $image;
echo $image->getFile();
</code>```

Now I get Fatal error: Uncaught Error: Call to undefined method stdClass::getFile()

Then I used a foreach:

```<code>foreach($image as $i) {
    echo $image->getFile();  // alternative: $image->getData('file')
}
</code>```

and it works! Why does it work with foreach and how can I make it work without?

答:
You can try with reset array function of PHP to get first element of array

```<code>$imageData = reset($image);
echo $imageData->getData("file");
</code>```

Body:
I have an object inside an array stored in the variable $image

array(1) { [250]=> object(Magento\Framework\DataObject)#11025 (1) { ["_data":protected]=> array(26) { ["value_id"]=> string(3) "250" ["file"]=> string(58) "/i/n/insetktenschutz-doppeltuer-im-zargenrahmen_37_1_3.jpg"  ... } } }

If I try to return a value, e.g. file like this:

echo $image->getFile();

Then of course I get Fatal error: Uncaught Error: Call to a member function getFile() on array

So I tried to call it like this:

$image = $image[0];
echo $image->getFile();

But I get Exception #0 (Exception): Notice: Undefined offset: 0

So I tried to cast it to an object:

$image = (object) $image;
echo $image->getFile();

Now I get Fatal error: Uncaught Error: Call to undefined method stdClass::getFile()

Then I used a foreach:

foreach($image as $i) {
    echo $image->getFile();  // alternative: $image->getData('file')
}

and it works! Why does it work with foreach and how can I make it work without?

Body:
You can try with reset array function of PHP to get first element of array

$imageData = reset($image);
echo $imageData->getData("file");


问:
How to kill all processes with a given partial name?
I want to kill all processes that I get by:

```<code>ps aux | grep my_pattern
</code>```

How to do it?

This does not work:

```<code>pkill my_pattern
</code>```

答:
This is the way:

```<code>kill -9 $(pgrep -d' ' -f chrome)
</code>```

The pgrep searches for all processes related to chrome and returns them in a list separated by spaces.

This is passed to the kill application that can safely kill all the related chrome processes.

This is still dangerous, be careful.

Body:
I want to kill all processes that I get by:

ps aux | grep my_pattern

How to do it?

This does not work:

pkill my_pattern

Body:
This is the way:

kill -9 $(pgrep -d' ' -f chrome)

The pgrep searches for all processes related to chrome and returns them in a list separated by spaces.

This is passed to the kill application that can safely kill all the related chrome processes.

This is still dangerous, be careful.


问:
What does (*(int *)&(w)) mean in c programming?
I'm learning processes and in the following code snippet:

```<code>/*
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
void fork10()
{
    pid_t pid[N];
    int i, child_status;

    for (i = 0; i < N; i++)
    if ((pid[i] = fork()) == 0) {
        exit(100+i); /* Child */
    }
    for (i = 0; i < N; i++) { /* Parent */
        pid_t wpid = wait(&child_status);
        if (WIFEXITED(child_status))
            printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
        else
            printf("Child %d terminate abnormally\n", wpid);
    }
}
</code>```

when I trace WIFEXITED function definition this is what I've got:

```<code>#define WIFEXITED(x)    (_WSTATUS(x) == 0)
#define _WSTATUS(x) (_W_INT(x) & 0177)
#define _W_INT(w)   (*(int *)&(w))  /* convert union wait to int */
</code>```

I have two questions:

Why use mask 0177 instead of 0b1111111, I've seen it many times, what's the benefits of using octal number over other formats? Personally I find binary more intuitive.

What's the meaning of (*(int *)&(w))?

Thanks!

答:
It has the advantage of not requiring any extra symbols as digits (the hexadecimal system is base-16 and therefore needs six additional symbols beyond 0–9). It is also used for digital displays.

You are trying to convert it to integer pointer and referencing the value from it.

Body:
I'm learning processes and in the following code snippet:

/*
 * fork10 - Synchronizing with multiple children (wait)
 * Reaps children in arbitrary order
 * WIFEXITED and WEXITSTATUS to get info about terminated children
 */
void fork10()
{
    pid_t pid[N];
    int i, child_status;

    for (i = 0; i < N; i++)
    if ((pid[i] = fork()) == 0) {
        exit(100+i); /* Child */
    }
    for (i = 0; i < N; i++) { /* Parent */
        pid_t wpid = wait(&child_status);
        if (WIFEXITED(child_status))
            printf("Child %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
        else
            printf("Child %d terminate abnormally\n", wpid);
    }
}

when I trace WIFEXITED function definition this is what I've got:

#define WIFEXITED(x)    (_WSTATUS(x) == 0)
#define _WSTATUS(x) (_W_INT(x) & 0177)
#define _W_INT(w)   (*(int *)&(w))  /* convert union wait to int */

I have two questions:

Why use mask 0177 instead of 0b1111111, I've seen it many times, what's the benefits of using octal number over other formats? Personally I find binary more intuitive.

What's the meaning of (*(int *)&(w))?

Thanks!


问:
React Native: Command `run-ios` unrecognized
I have two different ReactNative-Projects:

a) a project from januar 2016

b) a complete new react-native project
from now (march 20th 2016)

Within the new project the cli tool of react-native contains the command "run-ios" next two "run-android", but not on the older project from januar 2016. On the older one there is not "run-ios" command available:

```<code>$ react-native run-ios
Command `run-ios` unrecognized
Usage: react-native <command>
</code>```

I already ran "react-native upgrade" without any issues.

How can i get the command "run-ios" also in older projects?

答:
Delete the node-modules. Its because the packages are not installed.

rm -rf node_modules
 npm install

then run your project

react-native run-ios

Body:
I have two different ReactNative-Projects:

a) a project from januar 2016

b) a complete new react-native project
from now (march 20th 2016)

Within the new project the cli tool of react-native contains the command "run-ios" next two "run-android", but not on the older project from januar 2016. On the older one there is not "run-ios" command available:

$ react-native run-ios
Command `run-ios` unrecognized
Usage: react-native <command>

I already ran "react-native upgrade" without any issues.

How can i get the command "run-ios" also in older projects?


问:
Program that reads other .py
I am coding a Python program to be able to read another .py file and make a report of its content.
The data that I need is related to the libraries, functions and variables used in that .py.
I tried to use inspect library but this requires to import that .py and I can't see all its globals.

Is there a library to perform in a better way this task?

答:
Have you tried to treat this .py file as a simple text file and open it with Python's open built-in function?

Then use the regular expression module to search patterns in the string inside the .py file?

Title: Program that reads other .py


问:
How to optimize the query to update a table column with a column in another table in oracle
I have 2 tables. One table is cr_archive which has around 9000000 records. It has a column called v_sales_person which does not have values. I have another table called table_2 which has the same column called v_sales_person in which there are values. Both tables have columns called product_label,account_num. I want to select data from table _2 which has the same product_labels and account_num as in cr_archive and update the column v_sales_person in cr_archive with the values in table_2 which fulfill the above conditions(using oracle). I tried the following query.

```<code>update cr_archive a
set a.v_sales_person = (select distinct b.v_sales_person from table_2 b where a.account_num = b.account_num and A.PRODUCT_LABEL=b.PRODUCT_LABEL )
/
commit
/
</code>```

But the query is taking more than 6 hours to process and don't know whether it gives the output. I have 2 questions.
1. Is the above query correct?
2. Is there any method to optimize the above query.

答:
Don't use select distinct in the subquery.  It suggests that it could return more than one row.  Instead, use rownum = 1.  So, start with:

```<code>update cr_archive a
    set a.v_sales_person = (select b.v_sales_person
                            from table_2 b
                            where a.account_num = b.account_num and
                                  A.PRODUCT_LABEL = b.PRODUCT_LABEL and
                                  rownum = 1
                           );
</code>```

You want to optimize this with an index on table_2(account_num, PRODUCT_LABEL, v_sales_person).  The index is important for performance.

Next, this is updating all rows.  If that is not necessary, it is expensive.  So:

```<code>update cr_archive a
    set a.v_sales_person = (select b.v_sales_person
                            from table_2 b
                            where a.account_num = b.account_num and
                                  A.PRODUCT_LABEL = b.PRODUCT_LABEL and
                                  rownum = 1
                           )
    where a.v_sales_person is null or
          a.v_sales_person <> (select b.v_sales_person
                               from table_2 b
                               where a.account_num = b.account_num and
                                     A.PRODUCT_LABEL = b.PRODUCT_LABEL and
                                     rownum = 1
                              );
</code>```

Finally, if you do need to update all rows, then it is going to be quite expensive.  You might find one of the following a viable alternative:

Reconstruct the table.  Massive inserts are faster than massive updates.

Forget it.  Just JOIN when you query the table to get the name.

Add a new table with the same primary key.

Body:
I have 2 tables. One table is cr_archive which has around 9000000 records. It has a column called v_sales_person which does not have values. I have another table called table_2 which has the same column called v_sales_person in which there are values. Both tables have columns called product_label,account_num. I want to select data from table _2 which has the same product_labels and account_num as in cr_archive and update the column v_sales_person in cr_archive with the values in table_2 which fulfill the above conditions(using oracle). I tried the following query.

update cr_archive a
set a.v_sales_person = (select distinct b.v_sales_person from table_2 b where a.account_num = b.account_num and A.PRODUCT_LABEL=b.PRODUCT_LABEL )
/
commit
/

But the query is taking more than 6 hours to process and don't know whether it gives the output. I have 2 questions.
1. Is the above query correct?
2. Is there any method to optimize the above query.

Body:
Don't use select distinct in the subquery.  It suggests that it could return more than one row.  Instead, use rownum = 1.  So, start with:

update cr_archive a
    set a.v_sales_person = (select b.v_sales_person
                            from table_2 b
                            where a.account_num = b.account_num and
                                  A.PRODUCT_LABEL = b.PRODUCT_LABEL and
                                  rownum = 1
                           );

You want to optimize this with an index on table_2(account_num, PRODUCT_LABEL, v_sales_person).  The index is important for performance.

Next, this is updating all rows.  If that is not necessary, it is expensive.  So:

update cr_archive a
    set a.v_sales_person = (select b.v_sales_person
                            from table_2 b
                            where a.account_num = b.account_num and
                                  A.PRODUCT_LABEL = b.PRODUCT_LABEL and
                                  rownum = 1
                           )
    where a.v_sales_person is null or
          a.v_sales_person <> (select b.v_sales_person
                               from table_2 b
                               where a.account_num = b.account_num and
                                     A.PRODUCT_LABEL = b.PRODUCT_LABEL and
                                     rownum = 1
                              );

Finally, if you do need to update all rows, then it is going to be quite expensive.  You might find one of the following a viable alternative:

Reconstruct the table.  Massive inserts are faster than massive updates.

Forget it.  Just JOIN when you query the table to get the name.

Add a new table with the same primary key.


问:
When to use if (document.all&&document.getElementById) condition
Would like to know when to use, This applies for what browser ?</p>

```<code>if (document.all&&document.getElementById) {
// Some code block
}
</code>```

答:
document.all was a feature implemented by old versions of IE (IE3 and higher). It was also implemented by Opera, in an attempt to be compatible with IE-only sites.

However document.all is no longer recommended for use in any situation -- it is entirely obsolete. IE and Opera have kept support for it because there may be some old code that still uses it, but there is no place for it in modern code.

There are some script libraries which implement a version of document.all in Javascript, to allow old code to be run on modern browsers. For this reason, it isn't even worth using document.all as a browser test (as you've shown it in the question). In fact, all I have to do to break your test is write document.all = true;.

document.getElememtById was first implemented by IE in v5.0, so the condition you've given in the question would have been written in the days of IE5, and would have been a primitive browser-detection code for IE5.0 and higher, since that was (at the time) the only browser that supported both methods. But as already discussed, it is pretty much useless now, and is more likely to cause you problems than make anything work.

Body:
Would like to know when to use, This applies for what browser ?

if (document.all&&document.getElementById) {
// Some code block
}


问:
General replacing of NULL values in SQL Views
We have a fairly recent version of a SQL Server that we're using to extract data into a SAP BW Datawarehouse. We're using views to access data in tables on the SQL server. Some of the fields in these tables contain NULL values. These are transferred into SAP as String Value ('NULL') instead of empty, which causes us a major headache.

I understand that we can use COALESCE() in views to replace NULL values with a desired default value ('', 0, '1900-01-01', etc.), however, doing this for each NULL field that we encounter doesn't appear to be very smart.

Is there a better way of addressing this issue short of changing tables to not allow NULL values? Is it possible to include a custom global function that gets automatically applied to all fields fetched in a view without us having to call this function for each field individually?

答:
@Jeroen Mostert's answer in the comments answers my question.

There is no global toggle, flag or setting that will magically
  eliminate NULLs for you. The closest thing is that COALESCE(,
  '') will "work" (for some values of "work") for almost every type
  (including DATETIME), with the notable exception of DECIMAL. You
  cannot write a function to do this, as functions in T-SQL cannot
  return different types based on their input. By far the best "fix" is
  indeed to fix the processing step, if only because ending up with
  1900-01-01 dates in your database is typically quite undesirable.

Therefore, the only options are

go through each field that can potentially hold a NULL value and
cleanse it within the view

handle NULL values on the receiving
end (e.g. SAP BW); this could be done through a generic function to
be placed in the entry layer's start routine or it could be done
manually.

Disallowing NULL values on table level in the source system is in this case not feasible as we cannot change the application that writes to the tables (third party vendor ERP).