问:
Export Google Doc without comments
I am using the google drive api v3 files.export method to get the text/html version of a google doc. I noticed that all the currently open comments in the doc also show up in the content as footnotes. I was wondering if there is any way to export the content of the doc without exporting the open comments. I can’t seem to find any options for files.export that would disable comments. Thanks in advance for any help.

答:
Unfortunately, when Google Docs are exported, there are no methods for directly removing comments. So how about this workaround?

Retrieve all comment IDs from the Google Doc using drive.comments.list.

Remove all comments on the Google Doc using drive.comments.delete.

Export the Google Doc as HTML using drive.files.export.

Note :

If you want to continue to use the Google Doc which included comments, at first, please copy the Google Doc.

References :

drive.comments.list

drive.comments.delete

drive.files.export

If I misunderstand your question, I'm sorry.

Edit :

When you will modify HTML using regex, how about a following regex?

```<code><sup><a href="#cmnt\w.+?<\/a><\/sup>|<div style=\"border:1px solid black;margin:5px\">[\w\W]+<\/div>
</code>```

<\/sup> is the reference numbers at the upper right.

[\w\W]+<\/div> is the comments at the lower part.

When above regex is used for the exported Google Doc, the result is as follows.

From :

To :

href="https://i.stack.imgur.com/UMDuX.png" rel="nofollow noreferrer">

If this was not useful for you, I'm sorry.

Title: Export Google Doc without comments

Body:
Unfortunately, when Google Docs are exported, there are no methods for directly removing comments. So how about this workaround?

Retrieve all comment IDs from the Google Doc using drive.comments.list.

Remove all comments on the Google Doc using drive.comments.delete.

Export the Google Doc as HTML using drive.files.export.

Note :

If you want to continue to use the Google Doc which included comments, at first, please copy the Google Doc.

References :

drive.comments.list

drive.comments.delete

drive.files.export

If I misunderstand your question, I'm sorry.

Edit :

When you will modify HTML using regex, how about a following regex?

<sup><a href="#cmnt\w.+?<\/a><\/sup>|<div style=\"border:1px solid black;margin:5px\">[\w\W]+<\/div>

<sup><a href="#cmnt\w.+?<\/a><\/sup> is the reference numbers at the upper right.

<div style=\"border:1px solid black;margin:5px\">[\w\W]+<\/div> is the comments at the lower part.

When above regex is used for the exported Google Doc, the result is as follows.

From :

To :

If this was not useful for you, I'm sorry.


来源: stackexchange

问:
How can I go about creating distinct variables in Idris?
I am trying to reconstruct the axioms for Hilbert's geometry in Idris. I came up with the following code to represent his axioms:

```<code>interface (Eq point) => Plane line point where
  colinear : point -> point -> point -> Bool
  contains : line -> point -> point -> Bool
  axiom1a : (a,b : point) -> (a /= b) = True -> (l : line ** (contains l a b = True))
  axiom1b : contains l a b = True -> contains m a b = True -> l = m
  axiom2 : (a : point ** (colinear a b c = False) && (a /= b) = True && (b /= c) = True && (a /= c) = True)
  axiom3 : (l : line) -> (a ** (contains l a b = True))
</code>```

axiom2 should read "There exists 3 distinct non-colinear points." I get the following error:

```<code>When checking type of Main.axiom2:
When checking argument P to type constructor Builtins.DPair:
        Type mismatch between
                Bool (Type of _ && _)
        and
                Type (Expected type)
</code>```

If I remove && (a /= b) = True && (b /= c) = True && (a /= c) = True the code runs but then the qualification of "distinct" in the axiom is lost. Any help would be appreciated.

答:
colinear a b c = False is a Type, not a Bool.  Likewise for (a /= b) = True, (b /= c) = True, and (a /= c) = True.

Instead of using &&, you must use a "type-level &&", i.e. a tuple.

```<code>axiom2 : (a : point ** (colinear a b c = False, (a /= b) = True, (b /= c) = True, (a /= c) = True))
</code>```

However, that would read "There exists a point a that is not colinear with any two other distinct points", which is not always the case.  You could instead write this:

```<code>axiom2 : (a : point ** (b : point ** (c : point ** (colinear a b c = False, (a /= b) = True, (b /= c) = True, (a /= c) = True))))
</code>```

That would read "There exist three distinct points that are not colinear".  I'm not sure if it's possible to make that any nicer to look at, like (a, b, c : point ** ....

ContentLicense: CC BY-SA 3.0

Body:
I am trying to reconstruct the axioms for Hilbert's geometry in Idris. I came up with the following code to represent his axioms:

interface (Eq point) => Plane line point where
  colinear : point -> point -> point -> Bool
  contains : line -> point -> point -> Bool
  axiom1a : (a,b : point) -> (a /= b) = True -> (l : line ** (contains l a b = True))
  axiom1b : contains l a b = True -> contains m a b = True -> l = m
  axiom2 : (a : point ** (colinear a b c = False) && (a /= b) = True && (b /= c) = True && (a /= c) = True)
  axiom3 : (l : line) -> (a ** (contains l a b = True))

axiom2 should read "There exists 3 distinct non-colinear points." I get the following error:

When checking type of Main.axiom2:
When checking argument P to type constructor Builtins.DPair:
        Type mismatch between
                Bool (Type of _ && _)
        and
                Type (Expected type)

If I remove && (a /= b) = True && (b /= c) = True && (a /= c) = True the code runs but then the qualification of "distinct" in the axiom is lost. Any help would be appreciated.

Body:
colinear a b c = False is a Type, not a Bool.  Likewise for (a /= b) = True, (b /= c) = True, and (a /= c) = True.

Instead of using &&, you must use a "type-level &&", i.e. a tuple.

axiom2 : (a : point ** (colinear a b c = False, (a /= b) = True, (b /= c) = True, (a /= c) = True))

However, that would read "There exists a point a that is not colinear with any two other distinct points", which is not always the case.  You could instead write this:

axiom2 : (a : point ** (b : point ** (c : point ** (colinear a b c = False, (a /= b) = True, (b /= c) = True, (a /= c) = True))))

That would read "There exist three distinct points that are not colinear".  I'm not sure if it's possible to make that any nicer to look at, like (a, b, c : point ** ....


问:
Concatenate Julia DataFrames adding a categorical column
Say I have the following

```<code>a = DataFrame(x = [1,2,3,4], y = [10,20,30,40])
b = DataFrame(x = [1,2,3,4], y = [50,60,70,80])
</code>```

is there a way of getting [a;b] with an additional categorical column to obtain something like the following?

```<code>8×3 DataFrames.DataFrame
│ Row │ x │ y  │ c │
├─────┼───┼────┼───┤
│ 1   │ 1 │ 10 │ 1 │
│ 2   │ 2 │ 20 │ 1 │
│ 3   │ 3 │ 30 │ 1 │
│ 4   │ 4 │ 40 │ 1 │
│ 5   │ 1 │ 50 │ 2 │
│ 6   │ 2 │ 60 │ 2 │
│ 7   │ 3 │ 70 │ 2 │
│ 8   │ 4 │ 80 │ 2 │
</code>```

For two dataframes, something like

```<code>using DataFramesMeta
[@transform(a, c = 1); @transform(b, c = 2)]
</code>```

works, but what if I have more than a few DataFrames?

答:
You could use enumerate if you like to create result from array of DataFrames. For example:

```<code>l = [a,b]
vcat([transform(x,c=i) for (i,x) in enumerate(l)])
</code>```

Body:
Say I have the following

a = DataFrame(x = [1,2,3,4], y = [10,20,30,40])
b = DataFrame(x = [1,2,3,4], y = [50,60,70,80])

is there a way of getting [a;b] with an additional categorical column to obtain something like the following?

8×3 DataFrames.DataFrame
│ Row │ x │ y  │ c │
├─────┼───┼────┼───┤
│ 1   │ 1 │ 10 │ 1 │
│ 2   │ 2 │ 20 │ 1 │
│ 3   │ 3 │ 30 │ 1 │
│ 4   │ 4 │ 40 │ 1 │
│ 5   │ 1 │ 50 │ 2 │
│ 6   │ 2 │ 60 │ 2 │
│ 7   │ 3 │ 70 │ 2 │
│ 8   │ 4 │ 80 │ 2 │

For two dataframes, something like

using DataFramesMeta
[@transform(a, c = 1); @transform(b, c = 2)]

works, but what if I have more than a few DataFrames?

Body:
You could use enumerate if you like to create result from array of DataFrames. For example:

l = [a,b]
vcat([transform(x,c=i) for (i,x) in enumerate(l)])


问:
flip order of passed arguments
Is there a idiomatic / built-in way to flip the argument order that is passed to a function in Clojure?

As I do here with the definition of a helper function:

```<code>(defn flip [f & xs]
   (apply f (reverse xs)))

(vector 1 2)       ; [1 2]
(flip vector 1 2)  ; [2 1]
</code>```

答:
You can also use anonymous inline function to re-define the order of arguments.</p>

```<code>(vector "a" "b")          ; ["a" "b"]
(#(vector %2 %1) "a" "b") ; ["b" "a"]
</code>```

Title: flip order of passed arguments

Body:
Is there a idiomatic / built-in way to flip the argument order that is passed to a function in Clojure?

As I do here with the definition of a helper function:

(defn flip [f & xs]
   (apply f (reverse xs)))

(vector 1 2)       ; [1 2]
(flip vector 1 2)  ; [2 1]

Body:
You can also use anonymous inline function to re-define the order of arguments.

(vector "a" "b")          ; ["a" "b"]
(#(vector %2 %1) "a" "b") ; ["b" "a"]


问:
How to get SQL Server login mappings & role membership for a user
I technically need this from a code in C#, but SQL would work as well. Say, I have a SQL Server 2008 or later login or a user account. Let's call it c_user002.

How do I get databases mapped to this user?

How do I get role membership (or permissions) for this user?

Both concepts can be best illustrated via a screenshot from the SQL Server Management Studio:

答:
Here's a partial answer. You can find out which users have which permissions on which objects using this query:

```<code>SELECT
         dp.name AS DBUser,
         dp.type_desc AS UserType,
         OBJECT_NAME(p.major_id) AS ObjectName,
         p.permission_name AS Permission,
         p.state_desc AS PermissionStatus,
         dp.is_fixed_role AS BuiltInRole
FROM
         sys.database_permissions AS p
LEFT OUTER JOIN
    sys.database_principals AS dp
    ON
    dp.principal_id = p.grantee_principal_id
 WHERE (p.class = 1); -- Limit to Object or Column;
</code>```

Note that this only applies to the current database. You can always loop through to get them all though.

Body:
Here's a partial answer. You can find out which users have which permissions on which objects using this query:

SELECT
         dp.name AS DBUser,
         dp.type_desc AS UserType,
         OBJECT_NAME(p.major_id) AS ObjectName,
         p.permission_name AS Permission,
         p.state_desc AS PermissionStatus,
         dp.is_fixed_role AS BuiltInRole
FROM
         sys.database_permissions AS p
LEFT OUTER JOIN
    sys.database_principals AS dp
    ON
    dp.principal_id = p.grantee_principal_id
 WHERE (p.class = 1); -- Limit to Object or Column;

Note that this only applies to the current database. You can always loop through to get them all though.


问:
Trying to get the host and port out of a url in php
Hi all hope this makes sense.

I am wondering if there is a way to split the following with php

so

```<code>$url = "http://50.7.71.219:7183/listen.mp3";
</code>```

I then need to split it into 2 more strings so i should get a result of :

```<code>$ip = "http://50.7.71.219";
$port = "7183";
</code>```

Thanks,
Jamie

Body:
Hi all hope this makes sense.

I am wondering if there is a way to split the following with php

so

$url = "http://50.7.71.219:7183/listen.mp3";

I then need to split it into 2 more strings so i should get a result of :

$ip = "http://50.7.71.219";
$port = "7183";

Thanks,
Jamie

Body:
$s1=explode($url,":");
$s2=explode($s1[2],"/");
$ip=$s1[0].':'.$s1[1];
$port=$s2[0];

This should do the trick.


问:
How to keep Tesseract from inserting extra whitespace in words?
I asked about this on the Tesseract forum already

Via Tesseract (and ImageMagick), I'm trying to find out the text of this
PDF file

This is the section of the PDF that I'm working on, it's line #7 of the
PDF:

In this section, Tesseract is running into problems when trying to identify
the string CONSTRUCTORA.

It sees CO NSTRUCTO RA

It should see CONSTRUCTORA

Can anyone suggest any possible fixes for this?

This is the commandline sequence:

```<code>convert -density 600 my_pdf.pdf tmp.tif
tesseract -l spa tmp.tif stdout > tmp.txt
</code>```

These are the software versions:

```<code>~% tesseract --version
tesseract 3.05.01
leptonica-1.74.4
  libgif 4.1.6(?) : libjpeg 8d (libjpeg-turbo 1.3.0) : libpng 1.2.50 :
libtiff 4.0.3 : zlib 1.2.8
~% convert --version
Version: ImageMagick 6.7.7-10 2014-08-28 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2012 ImageMagick Studio LLC
Features: OpenMP
</code>```

答:
For dealing with the irregular kerning of the PDF file, Will suggested tweaking the parameters around tosp_min_sane_kn_sp of the docs https://github.com/naptha/tesseract.js/blob/master/docs/tesseract_parameters.md

Setting tosp_min_sane_kn_sp=2.8 solved the issue that was described in the question.

The new Tesseract invocation is the following:

```<code>tesseract -c tosp_min_sane_kn_sp=2.8 -l spa tmp.tif stdout > tmp.txt
</code>```

The default value for tosp_min_sane_kn_sp seems to be 1.5. So far, I have only tested with values larger than 1.5.

Body:
I asked about this on the Tesseract forum already

Via Tesseract (and ImageMagick), I'm trying to find out the text of this
PDF file

This is the section of the PDF that I'm working on, it's line #7 of the
PDF:

In this section, Tesseract is running into problems when trying to identify
the string CONSTRUCTORA.

It sees CO NSTRUCTO RA

It should see CONSTRUCTORA

Can anyone suggest any possible fixes for this?

This is the commandline sequence:

convert -density 600 my_pdf.pdf tmp.tif
tesseract -l spa tmp.tif stdout > tmp.txt

These are the software versions:

~% tesseract --version
tesseract 3.05.01
leptonica-1.74.4
  libgif 4.1.6(?) : libjpeg 8d (libjpeg-turbo 1.3.0) : libpng 1.2.50 :
libtiff 4.0.3 : zlib 1.2.8
~% convert --version
Version: ImageMagick 6.7.7-10 2014-08-28 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2012 ImageMagick Studio LLC
Features: OpenMP

Body:
For dealing with the irregular kerning of the PDF file, Will suggested tweaking the parameters around tosp_min_sane_kn_sp of the docs https://github.com/naptha/tesseract.js/blob/master/docs/tesseract_parameters.md

Setting tosp_min_sane_kn_sp=2.8 solved the issue that was described in the question.

The new Tesseract invocation is the following:

tesseract -c tosp_min_sane_kn_sp=2.8 -l spa tmp.tif stdout > tmp.txt

The default value for tosp_min_sane_kn_sp seems to be 1.5. So far, I have only tested with values larger than 1.5.


问:
Qt how to open a file in current dir ? or what's wrong with this?
I'm trying to open an xml file in the current location of the executable

```<code>        QString path = QDir::currentPath();
        path.append("/acc.xml");
        QFile file(path);

        if(!file.open(QIODevice::ReadOnly))
        {
            insertItem("IO ERR");
        }
</code>```

When I run it from Qt creator, everything works. currentPath() returns the path to the executable's folder

When I go to project-build-desktop/ folder and try to run it manually currentPath() returns /home/user/Documents

EDIT

also tried with same results:

```<code>Qt::current().path();
Qt::current().absolutePath();
</code>```

答:
Check the returned value of QDir::currentPath(). I think when you run from Qt Creator, it returns the path where the project file (*.pro) is located. When you run from outside, you get path of the binary.

Edit

I never worked with Linux. However, you can try other functions/combinations from QDir:

QDir::current().path()

QDir::current().absolutePath()

etc.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to open an xml file in the current location of the executable

        QString path = QDir::currentPath();
        path.append("/acc.xml");
        QFile file(path);

        if(!file.open(QIODevice::ReadOnly))
        {
            insertItem("IO ERR");
        }

When I run it from Qt creator, everything works. currentPath() returns the path to the executable's folder

When I go to project-build-desktop/ folder and try to run it manually currentPath() returns /home/user/Documents

EDIT

also tried with same results:

Qt::current().path();
Qt::current().absolutePath();


问:
Error response from daemon: oci runtime error: container_linux.go:262 :
I have just started to use docker. I have installed alpine image for testing docker workflow but after running

```<code>docker run alpine ls -l
</code>```

I am getting this following error

Error response from daemon: oci runtime error: container_linux.go:262:
  starting container process caused "exec: \"ls-l\": executable file not
  found in $PATH".

I have installed Docker Desktop for Windows in Windows 10.

答:
The last argument to docker run must be the name of an executable. ls is a command implemented by the shell, but not an executable in itself, hence the error you see. You have to tell docker to run ls in the context of a particular shell. E.g.

```<code>$ docker run alpine sh -c 'ls -l'
total 52
drwxr-xr-x    2 root     root          4096 Oct 25 22:05 bin
drwxr-xr-x    5 root     root           340 Nov 15 22:45 dev
drwxr-xr-x   14 root     root          4096 Nov 15 22:45 etc
...
</code>```

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
I have just started to use docker. I have installed alpine image for testing docker workflow but after running

docker run alpine ls -l

I am getting this following error

Error response from daemon: oci runtime error: container_linux.go:262:
  starting container process caused "exec: \"ls-l\": executable file not
  found in $PATH".

I have installed Docker Desktop for Windows in Windows 10.

Body:
The last argument to docker run must be the name of an executable. ls is a command implemented by the shell, but not an executable in itself, hence the error you see. You have to tell docker to run ls in the context of a particular shell. E.g.

$ docker run alpine sh -c 'ls -l'
total 52
drwxr-xr-x    2 root     root          4096 Oct 25 22:05 bin
drwxr-xr-x    5 root     root           340 Nov 15 22:45 dev
drwxr-xr-x   14 root     root          4096 Nov 15 22:45 etc
...

Hope this helps.


问:
How to Center Button in Bootstrap 3.0.2
I'm trying to get a button centered on a page. I've tried probably over 50 ways and nothing has worked.
Here's my code:

```<code><div class="container">
<div class="row" style="margin-top: 25px; align:center;">
  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
    <p style="text-align:center; margin-bottom: 25px; font-size: 135%;">Sample text.</p>
      <p style="text-align:center; padding-left: 40%; padding-right:40%;"><div class="button"><a href="www.exampleURL.com" target="_blank"><strong>Donate</strong></a></div> </p>
      <p> </p>
  </div>
</div>
</code>```

Any ideas? I've tried adding text-center, align:center--almost every variation you could think of--to every different tag and nothing works.

答:
One of the ways is to make use of class text-center on
 in which <button> is wrapped , Below is the working code:

```<code><div class="container">
  <div class=row>
    <div class="col-md-4 text-center">
      <button id="centerbutton" name="centerbutton" class="btn btn-primary"> Button in Center</button>
    </div>
  </div>
</div>
</code>```

And here is the Working JSFIDDLE in Bootstrap 3.0.2

Title: How to Center Button in Bootstrap 3.0.2

Body:
I'm trying to get a button centered on a page. I've tried probably over 50 ways and nothing has worked.
Here's my code:

Sample text.

Donate

Any ideas? I've tried adding text-center, align:center--almost every variation you could think of--to every different tag and nothing works.

Body:
One of the ways is to make use of class text-center on <div> in which <button> is wrapped , Below is the working code:

<div class="container">
  <div class=row>
    <div class="col-md-4 text-center">
      <button id="centerbutton" name="centerbutton" class="btn btn-primary"> Button in Center</button>
    </div>
  </div>
</div>

And here is the Working JSFIDDLE in Bootstrap 3.0.2


问:
Did anyone try using "Call Virtual User Generator Script" from toolbox for API testing?
For testing one my functionality I want to call VUGEN script in my APItest in UFT. I added the "Call Virtual User Generator Script" from toolbox to my test. But I am unable to give the script path. In the screenshot attached calling vugen script from UFT error, when I am trying to locate the error to give the path of my vugen script I am not even getting the popup to select the path. Did anyone try this option or is there any known issue with UFT for calling vugen script.

Thanks in advance for any help or suggestions.

答:
I do NOT have VUGen installed on my system. But in order to update the script path, you need to update in Properties section of that activity.

To view the Property section, click:

```<code>View -> Properties
</code>```

Now from here click on the highlighted button and it will give you the script selection window.

Body:
I do NOT have VUGen installed on my system. But in order to update the script path, you need to update in Properties section of that activity.

To view the Property section, click:

View -> Properties

Now from here click on the highlighted button and it will give you the script selection window.


问:
What mean `(value, value)` in JS obfluscated code
I try to understand how JS code works, but to the end I'm not sure what to look for. I have:

```<code>m = ((146.8E1, 67.60E1) > (71., 4.80E1) ? (0x5C, 'n') : (40., 83.))
</code>```

The full expression is if(), but I don't know how to understand (arg1, arg2).

My browsers (ff, chrome, edge) always returns 2 "arguments".
It's just a method of onfluscate or syntax I don't know?

答:
The comma operator separates expressions. (a, b) simply evaluates to b.

```<code>(a, b) > (c, d) ? (e, f) : (g, h)
</code>```

is equivalent to

```<code>b > d ? f : g
</code>```

Body:
I try to understand how JS code works, but to the end I'm not sure what to look for. I have:

m = ((146.8E1, 67.60E1) > (71., 4.80E1) ? (0x5C, 'n') : (40., 83.))

The full expression is if(), but I don't know how to understand (arg1, arg2).

My browsers (ff, chrome, edge) always returns 2 "arguments".
It's just a method of onfluscate or syntax I don't know?

Body:
The comma operator separates expressions. (a, b) simply evaluates to b.

(a, b) > (c, d) ? (e, f) : (g, h)

is equivalent to

b > d ? f : g


问:
Find UNC path of a network drive?
I need to be able determine the path of the network Q drive at work for a WEBMethods project. The code that I have before is in my configuration file. I placed single character leters inside of the directories just for security reasons. I am not sure what the semi-colon is for, but I think that the double slashes are were the drive name comes to play.

Question: Is there an easy way on a Windows 7 machine to find out what the full path of the UNC is for any specific drive location?

Code:

```<code>allowedWritePaths=Q:/A/B/C/D/E/
allowedReadPaths=C:/A/B;//itpr99999/c$/A/FileName.txt
allowedDeletePaths=
</code>```

答:
This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:

https://pathcopycopy.github.io/

Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:

Title: Find UNC path of a network drive?

Body:
I need to be able determine the path of the network Q drive at work for a WEBMethods project. The code that I have before is in my configuration file. I placed single character leters inside of the directories just for security reasons. I am not sure what the semi-colon is for, but I think that the double slashes are were the drive name comes to play.

Question: Is there an easy way on a Windows 7 machine to find out what the full path of the UNC is for any specific drive location?

Code:

allowedWritePaths=Q:/A/B/C/D/E/
allowedReadPaths=C:/A/B;//itpr99999/c$/A/FileName.txt
allowedDeletePaths=


问:
Firebase retrieves my Double as a String in Swift iOS?
So I'm saving a dictionary to my firebase. The dictionary is located in a custom class I made called FoodItem. Here's the lines where I save the dictionary:

```<code>let favRef = self.ref.childByAppendingPath("urlhidden")
favRef.setValue(foodItem.toAnyObject())
</code>```

foodItem is a FoodItem object, here's the part of my FoodItem class that implements .toAnyObject()

```<code>var key: String
var ref: Firebase?
var name: String
var description: String
var minCal: Int
var maxCal: Int
var containsNuts: Bool
var vegetarian: Bool
var price: Double //**NOTE THAT PRICE IS A DOUBLE**

func toAnyObject()->[String:AnyObject]{
    return ["name":self.name,
            "price":self.price,
            "description":self.description,
            "minCal":self.minCal,
            "maxCal":self.maxCal,
            "containsNuts":self.containsNuts,
            "vegetarian":self.vegetarian]
    }
</code>```

So those bits of code combined saves my data to my firebase. Works as it should. But when I retrieve the data, my price variable is a string? I'll explain...

Here's where I retrieve the data:

```<code>func getCurrentOrder(){
    let uid = ref.authData.uid
    ref = Firebase(url: "urlhidden")
    ref.observeEventType(.Value, withBlock: { snapshot in

        var newItems = [FoodItem]()

        for item in snapshot.children {

            let foodItem = FoodItem(snapshot: item as! FDataSnapshot)
            newItems.append(foodItem)
        }

        self.order = newItems
        self.tableView.reloadData()
    })
}
</code>```

That FoodItem constructor you see with the snapshot takes the data from my firebase and assigns my FoodItem variables to those values in my firebase. Here's that code:

```<code>init(snapshot: FDataSnapshot) {
    key = snapshot.key
    name = snapshot.value["name"] as! String
    price = snapshot.value["price"] as! Double //**NOTE STILL A DOUBLE**
    description = snapshot.value["description"] as! String
    minCal = snapshot.value["minCal"] as! Int
    maxCal = snapshot.value["maxCal"] as! Int
    containsNuts = snapshot.value["containsNuts"] as! Bool
    vegetarian = snapshot.value["vegetarian"] as! Bool

    ref = snapshot.ref
}
</code>```

However when I run my code, I see that it prints the double as a String

As you can see, there are clearly quotes around the Double variable "price".
And I get this error:

Could not cast value of type '__NSCFString' (0xff0ee0) to 'NSNumber' (0x13ff81c).

With this line of code highlighted in red:

```<code>price = snapshot.value["price"] as! Double
</code>```

Which is located inside the FoodItem constructor with the snapshot as I posted above.

Any Ideas???

*EDIT: It does the same thing for my int variables. Same error message

答:
2017 example

It may save someone some typing, here's some completely typical code to observe a simple number value. Let's say it's a fraction called SomeFraction.

As always, Firebase rocks  :)

```<code>override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)
    dev_listenForLiveFraction()
}

var r1: DatabaseReference? = nil
func dev_listenForLiveFraction() {

    let p1 = "something/someFractionForExample"

    r1 = Database.database().reference(withPath: p1)
    r1!.observe(.value) { (snapshot) in

        let sf: NSNumber = snapshot.value as? NSNumber ?? 0.666
        self.example_handleSomeFraction(sf)
    }
}

func example_handleSomeFraction(_ sf: NSNumber) {

    print("the fraction is now \(sf)")
}

override func viewDidDisappear(_ animated: Bool) {

    super.viewDidDisappear(animated)
    clearObservations()
}

private func clearObservations() {

    if r1 != nil {

        r1?.removeAllObservers()
        r1 = nil
    }
}
</code>```

Body:
So I'm saving a dictionary to my firebase. The dictionary is located in a custom class I made called FoodItem. Here's the lines where I save the dictionary:

let favRef = self.ref.childByAppendingPath("urlhidden")
favRef.setValue(foodItem.toAnyObject())

foodItem is a FoodItem object, here's the part of my FoodItem class that implements .toAnyObject()

var key: String
var ref: Firebase?
var name: String
var description: String
var minCal: Int
var maxCal: Int
var containsNuts: Bool
var vegetarian: Bool
var price: Double //**NOTE THAT PRICE IS A DOUBLE**

func toAnyObject()->[String:AnyObject]{
    return ["name":self.name,
            "price":self.price,
            "description":self.description,
            "minCal":self.minCal,
            "maxCal":self.maxCal,
            "containsNuts":self.containsNuts,
            "vegetarian":self.vegetarian]
    }

So those bits of code combined saves my data to my firebase. Works as it should. But when I retrieve the data, my price variable is a string? I'll explain...

Here's where I retrieve the data:

func getCurrentOrder(){
    let uid = ref.authData.uid
    ref = Firebase(url: "urlhidden")
    ref.observeEventType(.Value, withBlock: { snapshot in

        var newItems = [FoodItem]()

        for item in snapshot.children {

            let foodItem = FoodItem(snapshot: item as! FDataSnapshot)
            newItems.append(foodItem)
        }

        self.order = newItems
        self.tableView.reloadData()
    })
}

That FoodItem constructor you see with the snapshot takes the data from my firebase and assigns my FoodItem variables to those values in my firebase. Here's that code:

init(snapshot: FDataSnapshot) {
    key = snapshot.key
    name = snapshot.value["name"] as! String
    price = snapshot.value["price"] as! Double //**NOTE STILL A DOUBLE**
    description = snapshot.value["description"] as! String
    minCal = snapshot.value["minCal"] as! Int
    maxCal = snapshot.value["maxCal"] as! Int
    containsNuts = snapshot.value["containsNuts"] as! Bool
    vegetarian = snapshot.value["vegetarian"] as! Bool

    ref = snapshot.ref
}

However when I run my code, I see that it prints the double as a String

As you can see, there are clearly quotes around the Double variable "price".
And I get this error:

Could not cast value of type '__NSCFString' (0xff0ee0) to 'NSNumber' (0x13ff81c).

With this line of code highlighted in red:

price = snapshot.value["price"] as! Double

Which is located inside the FoodItem constructor with the snapshot as I posted above.

Any Ideas???

*EDIT: It does the same thing for my int variables. Same error message

Body:
2017 example

It may save someone some typing, here's some completely typical code to observe a simple number value. Let's say it's a fraction called SomeFraction.

As always, Firebase rocks  :)

override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)
    dev_listenForLiveFraction()
}

var r1: DatabaseReference? = nil
func dev_listenForLiveFraction() {

    let p1 = "something/someFractionForExample"

    r1 = Database.database().reference(withPath: p1)
    r1!.observe(.value) { (snapshot) in

        let sf: NSNumber = snapshot.value as? NSNumber ?? 0.666
        self.example_handleSomeFraction(sf)
    }
}

func example_handleSomeFraction(_ sf: NSNumber) {

    print("the fraction is now \(sf)")
}

override func viewDidDisappear(_ animated: Bool) {

    super.viewDidDisappear(animated)
    clearObservations()
}

private func clearObservations() {

    if r1 != nil {

        r1?.removeAllObservers()
        r1 = nil
    }
}


问:
Can I use a subclass to change the background image?
How do I specify a subclass to swap in background images?

Here's my css:

```<code>.background-image-post{
    background-image:url('../images/posts/background-post.jpg');
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;

}
</code>```

I want to change the image dependant on the post either with a subclass post1, etc or ideally override it in the HTML but It's not working.

any thoughts?

答:
Subclass is the wrong verbiage here.  All you need is an 'additional' class, which creates a higher level of specificity.

As an example: All divs with the class background-image-post get the placehold background.  However divs with both background-image-post and phil classes, will get the fillmurray background because it's more specific.

.background-image-post{
    display: inline-block;
    margin: 3px;
    background-image:url('//placehold.it/200x200');
    width: 200px;
    height: 200px;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

.background-image-post.phil {
    background-image:url('//fillmurray.com/200/200');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="background-image-post"></div>
<div class="background-image-post phil"></div></code>```

Body:
How do I specify a subclass to swap in background images?

Here's my css:

.background-image-post{
    background-image:url('../images/posts/background-post.jpg');
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;

}

I want to change the image dependant on the post either with a subclass post1, etc or ideally override it in the HTML but It's not working.

any thoughts?

Body:
Subclass is the wrong verbiage here.  All you need is an 'additional' class, which creates a higher level of specificity.

As an example: All divs with the class background-image-post get the placehold background.  However divs with both background-image-post and phil classes, will get the fillmurray background because it's more specific.

.background-image-post{
    display: inline-block;
    margin: 3px;
    background-image:url('//placehold.it/200x200');
    width: 200px;
    height: 200px;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

.background-image-post.phil {
    background-image:url('//fillmurray.com/200/200');
}

<div class="background-image-post"></div>
<div class="background-image-post phil"></div>


问:
How to Download a file in App with webview component?
I have a App with WebView, and i'm trying to download a file.
I just want to download files, don't need be inside WebView App, just making the download. I search in the web some codes but i don't found much about this.

This is my WebView (the webview is a fragment):

```<code>public class Example extends Fragment {

public WebView myWebView;

private ProgressBar prg;

SwipeRefreshLayout mySwipeRefreshLayout;

public static Example newInstance() {
    Example fragment = new Example();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.pagina_principal_layout, container, false);
    myWebView = (WebView) rootView.findViewById(R.id.paginaPrincipalWebView);
    myWebView.loadUrl("http://example.com/");
    prg = (ProgressBar)rootView.findViewById(R.id.progressBar2);
    mySwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipelayout);

    //Esconder barra deslizante lateral de navegação Web.
    myWebView.setVerticalScrollBarEnabled(false);

    //*Ativar JavaScript
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    //*Forçar links para abrir no WebView ao invés do navegador
    myWebView.setWebViewClient(new WebViewClient());

    //Forçar links para abrir no WebView ao invés do navegador.
    mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            myWebView.reload();
            mySwipeRefreshLayout.setRefreshing(false);
        }
    });

    //*Voltar histórico ao pressionar botão "voltar"
    myWebView.setOnKeyListener(new View.OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if(event.getAction() == KeyEvent.ACTION_DOWN)
            {
                WebView webView = (WebView) v;

                switch(keyCode)
                {
                    case KeyEvent.KEYCODE_BACK:
                        if(webView.canGoBack())
                        {
                            webView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });

    return rootView;

}
</code>```

I tried this code:

```<code>mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
            String contentDisposition, String mimetype,
            long contentLength) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}
});
</code>```

This code will open browser and make the download from it. The problem in this code is that the download start, but after that the download failed.

答:
As I said, if you want to download the file inside your webview, you should try this:

```<code>myWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
                                String contentDisposition, String mimetype,
                                long contentLength) {
        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse(url));

        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name of your file");
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(request);
       //you could show a message here

    }
});
</code>```

Don't forget to add this permission on your manifest:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

And if you are using Android > 5 , you have to ask for permissions :)

Link: https://developer.android.com/training/permissions/requesting.html

Body:
I have a App with WebView, and i'm trying to download a file.
I just want to download files, don't need be inside WebView App, just making the download. I search in the web some codes but i don't found much about this.

This is my WebView (the webview is a fragment):

public class Example extends Fragment {

public WebView myWebView;

private ProgressBar prg;

SwipeRefreshLayout mySwipeRefreshLayout;

public static Example newInstance() {
    Example fragment = new Example();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.pagina_principal_layout, container, false);
    myWebView = (WebView) rootView.findViewById(R.id.paginaPrincipalWebView);
    myWebView.loadUrl("http://example.com/");
    prg = (ProgressBar)rootView.findViewById(R.id.progressBar2);
    mySwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipelayout);

    //Esconder barra deslizante lateral de navegação Web.
    myWebView.setVerticalScrollBarEnabled(false);

    //*Ativar JavaScript
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    //*Forçar links para abrir no WebView ao invés do navegador
    myWebView.setWebViewClient(new WebViewClient());

    //Forçar links para abrir no WebView ao invés do navegador.
    mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            myWebView.reload();
            mySwipeRefreshLayout.setRefreshing(false);
        }
    });

    //*Voltar histórico ao pressionar botão "voltar"
    myWebView.setOnKeyListener(new View.OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if(event.getAction() == KeyEvent.ACTION_DOWN)
            {
                WebView webView = (WebView) v;

                switch(keyCode)
                {
                    case KeyEvent.KEYCODE_BACK:
                        if(webView.canGoBack())
                        {
                            webView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });

    return rootView;

}

I tried this code:

mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
            String contentDisposition, String mimetype,
            long contentLength) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}
});

This code will open browser and make the download from it. The problem in this code is that the download start, but after that the download failed.

Body:
As I said, if you want to download the file inside your webview, you should try this:

myWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
                                String contentDisposition, String mimetype,
                                long contentLength) {
        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse(url));

        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name of your file");
        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(request);
       //you could show a message here

    }
});

Don't forget to add this permission on your manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And if you are using Android > 5 , you have to ask for permissions :)

Link: https://developer.android.com/training/permissions/requesting.html


问:
Google App Engine is not creating table (python)
I have this model

```<code>class SiteUser(db.Model):
    site_user = db.UserProperty()
    total_votes = db.IntegerProperty(default=1)
    liked_items = db.StringProperty()

class Item(db.Model):
    user_who_liked_this_item = db.UserProperty()
    title = db.StringProperty()
    url = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    points = db.IntegerProperty(default=1)
</code>```

Item table is created but SiteUser table is not created. Can anyone help me understand what I am doing wrong?

Thanks?

答:
When you use this the first time it will "create a table"</p>

```<code>new_user = SiteUser()
new_user.liked_items = str(42)
new_user.put()
</code>```

Body:
I have this model

class SiteUser(db.Model):
    site_user = db.UserProperty()
    total_votes = db.IntegerProperty(default=1)
    liked_items = db.StringProperty()

class Item(db.Model):
    user_who_liked_this_item = db.UserProperty()
    title = db.StringProperty()
    url = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    points = db.IntegerProperty(default=1)

Item table is created but SiteUser table is not created. Can anyone help me understand what I am doing wrong?

Thanks?

Body:
When you use this the first time it will "create a table"

new_user = SiteUser()
new_user.liked_items = str(42)
new_user.put()


问:
Access Methods form django apps within the same project = Django
I am have a django project that I am creating. Within the django project I have two apps which as user and common. I want to use a method that validates if a user is logged in from the common apps views.py file within the user views.py file. How can I can the LoggedIn method from the common view.py in a method from he user views.py Home method....

User -> views.py file:

```<code># checks if someone is logged in
def Home(request):
    # check if there is a user logged in
    currentUser = LoggedIn(request)
    # no user logged in
    if currentUser == None:
        # send user to the main sign in and log in form
        return redirect('Signup')
    # a user logged in
    else:
        # users home page content will be down below
        parameters = 'parameters'
</code>```

Common -> views.py file:

```<code>def LoggedIn(request):
    if 'username' not in request.session:
        return None
    else:
        user = request.session['username']
        currentUser = User.objects.get(username=username)
        return curentUser
</code>```

I cant seem to get how to call one method from a different app. I don't want to have to redirect the user but rather just call the method and return a value to the Home method in the user app views.py file. Couldn't find any documentation on this matter.

答:
You are trying to reinvent the wheel there. Django has built-in authentication support which does what you are trying to do properly. I'd do a bit more reading before trying to code something, start here: https://docs.djangoproject.com/en/1.11/topics/auth/default/

Specifically, you seem to be looking for login_required decorator.

If your question was conceptual, you are looking for a way to import a function from another file, in that case check this question.

Also, Python has a style guide for coding, called PEP. For example, function names are suggested to be lowercase and words separated with underscores. I suggest you check that, too: https://www.python.org/dev/peps/pep-0008/#function-names

Body:
I am have a django project that I am creating. Within the django project I have two apps which as user and common. I want to use a method that validates if a user is logged in from the common apps views.py file within the user views.py file. How can I can the LoggedIn method from the common view.py in a method from he user views.py Home method....

User -> views.py file:

# checks if someone is logged in
def Home(request):
    # check if there is a user logged in
    currentUser = LoggedIn(request)
    # no user logged in
    if currentUser == None:
        # send user to the main sign in and log in form
        return redirect('Signup')
    # a user logged in
    else:
        # users home page content will be down below
        parameters = 'parameters'

Common -> views.py file:

def LoggedIn(request):
    if 'username' not in request.session:
        return None
    else:
        user = request.session['username']
        currentUser = User.objects.get(username=username)
        return curentUser

I cant seem to get how to call one method from a different app. I don't want to have to redirect the user but rather just call the method and return a value to the Home method in the user app views.py file. Couldn't find any documentation on this matter.


问:
C# viewmodel : Mapping unnamed string array from JSON
I'm trying to create a C# viewmodel to map the follwing JSON :

```<code>"choices": {
        "5": {
            "Id": 16,
            "Name": "Sterk",
            "FoodPropertyId": 5
        },
        "6": {
            "Id": 17,
            "Name": "Pommes Frites",
            "FoodPropertyId": 6
        }
    },
</code>```

As you might notice.. "5" and "6" are just values, and are not valuable at all in my viewmodel. Problem is.. the array-data inside is what i need.

Can someone tell me how to map this into a viewmodel ?

答:
You can use a dictionary for the choices .The key will be a numeric type and value will be the class representing each item with those 3 properties.

```<code>public class RootData
{
    public Dictionary<int, FoodItem> Choices { set; get; }
}
public class FoodItem
{
    public int Id { get; set; }
    public int FoodPropertyId { get; set; }
    public string Name { get; set; }
}
</code>```

This should work for the below JSON

```<code>{
    "choices": {
        "5": {
            "Id": 16,
            "Name": "Sterk",
            "FoodPropertyId": 5
        },
        "6": {
            "Id": 17,
            "Name": "Pommes Frites",
            "FoodPropertyId": 6
        }
    }
}
</code>```

Edit : As per the comment, adding the code to access this.

You can loop through the Choices dictionary and read each key and the value(a FoodItem object)

Here is a sample using the RootData class as the parameter of a wep api 2 controller action method.

```<code>public IHttpActionResult Post(RootData value)
{
    if (value != null && value.Choices != null)
    {
        foreach (var valueChoice in value.Choices)
        {
            int theNumber = valueChoice.Key;
            FoodItem foodItem = valueChoice.Value;

            var name = foodItem.Name;
            var id   = foodItem.Id;
        }
    }
    return Ok("All good");
}
</code>```

Body:
I'm trying to create a C# viewmodel to map the follwing JSON :

"choices": {
        "5": {
            "Id": 16,
            "Name": "Sterk",
            "FoodPropertyId": 5
        },
        "6": {
            "Id": 17,
            "Name": "Pommes Frites",
            "FoodPropertyId": 6
        }
    },

As you might notice.. "5" and "6" are just values, and are not valuable at all in my viewmodel. Problem is.. the array-data inside is what i need.

Can someone tell me how to map this into a viewmodel ?

Body:
You can use a dictionary for the choices .The key will be a numeric type and value will be the class representing each item with those 3 properties.

public class RootData
{
    public Dictionary<int, FoodItem> Choices { set; get; }
}
public class FoodItem
{
    public int Id { get; set; }
    public int FoodPropertyId { get; set; }
    public string Name { get; set; }
}

This should work for the below JSON

{
    "choices": {
        "5": {
            "Id": 16,
            "Name": "Sterk",
            "FoodPropertyId": 5
        },
        "6": {
            "Id": 17,
            "Name": "Pommes Frites",
            "FoodPropertyId": 6
        }
    }
}

Edit : As per the comment, adding the code to access this.

You can loop through the Choices dictionary and read each key and the value(a FoodItem object)

Here is a sample using the RootData class as the parameter of a wep api 2 controller action method.

public IHttpActionResult Post(RootData value)
{
    if (value != null && value.Choices != null)
    {
        foreach (var valueChoice in value.Choices)
        {
            int theNumber = valueChoice.Key;
            FoodItem foodItem = valueChoice.Value;

            var name = foodItem.Name;
            var id   = foodItem.Id;
        }
    }
    return Ok("All good");
}


问:
R: how to check how many cores/CPU usage available
R is single-threaded.

Using R, how to check how many cores/threads are running R in Windows and Linux? (Or how many Rs are running)

Using R, how to check the usage of each core that is running R in Windows and Linux? (Or the percentage of CPU each R is using)

For example, if I have two R opened running projects. I would expect that there are 2 threads running R with some % of CPU for each thread. Then I open another R. How to use the third R to check the number of threads (2 in this case) and percentage of CPU being used by R?

答:
On Linux you can send ps command to the system: it gives you the average cpu usage and the memory usage of the program called rsession:

```<code>splitted <- strsplit(system("ps -C rsession -o %cpu,%mem,pid,cmd", intern = TRUE), " ")
df <- do.call(rbind, lapply(splitted[-1],
                            function(x) data.frame(
                                cpu = as.numeric(x[2]),
                                mem = as.numeric(x[4]),
                                pid = as.numeric(x[5]),
                                cmd = paste(x[-c(1:5)], collapse = " "))))
df
#  cpu mem   pid   cmd
#1 0.8 0.7 11001  /usr/lib/rstudio/bin/rsession
#2 0.0 0.2 12397  /usr/lib/rstudio/bin/rsession
#3 0.1 0.7 14960  /usr/lib/rstudio/bin/rsession
#4 0.4 0.2 26122  /usr/lib/rstudio-server/bin/rsession
#5 0.3 8.3 35782  /usr/lib/rstudio/bin/rsession
</code>```

You can probably improve it to get the parent id and the instantaneous CPU usage with other options passed to ps or top and deduce the number of cores used by each session.

On Windows you can try this:

```<code>a <- system("wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime", intern = TRUE)
df <- do.call(rbind, lapply(strsplit(a, " "), function(x) {x <- x[x != ""];data.frame(process = x[1], cpu = x[2])}))
df[grepl("Rgui|rstudio", df$process),]
#     process cpu
# 105    Rgui   0
# 108 rstudio   0
</code>```

Body:
On Linux you can send ps command to the system: it gives you the average cpu usage and the memory usage of the program called rsession:

splitted <- strsplit(system("ps -C rsession -o %cpu,%mem,pid,cmd", intern = TRUE), " ")
df <- do.call(rbind, lapply(splitted[-1],
                            function(x) data.frame(
                                cpu = as.numeric(x[2]),
                                mem = as.numeric(x[4]),
                                pid = as.numeric(x[5]),
                                cmd = paste(x[-c(1:5)], collapse = " "))))
df
#  cpu mem   pid   cmd
#1 0.8 0.7 11001  /usr/lib/rstudio/bin/rsession
#2 0.0 0.2 12397  /usr/lib/rstudio/bin/rsession
#3 0.1 0.7 14960  /usr/lib/rstudio/bin/rsession
#4 0.4 0.2 26122  /usr/lib/rstudio-server/bin/rsession
#5 0.3 8.3 35782  /usr/lib/rstudio/bin/rsession

You can probably improve it to get the parent id and the instantaneous CPU usage with other options passed to ps or top and deduce the number of cores used by each session.

On Windows you can try this:

a <- system("wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime", intern = TRUE)
df <- do.call(rbind, lapply(strsplit(a, " "), function(x) {x <- x[x != ""];data.frame(process = x[1], cpu = x[2])}))
df[grepl("Rgui|rstudio", df$process),]
#     process cpu
# 105    Rgui   0
# 108 rstudio   0


问:
PHP - self destruct message telegram bot
I am building a telegram bot to send ads to my channels and I want them to be deleted after a certain period of time

But I need to get message id to delete it, when I run code like this

```<code>$update = json_decode(file_get_contents("php://input"));
$command = $update->message->text;
function message($mchat_id, $mtext)
{
    global $token;
    $ret=json_decode(file_get_contents('https://api.telegram.org/bot' .$token.'/sendMessage?chat_id='.$mchat_id.'&text='.$mtext.'&parse_mode=HTML'));
    return $ret;
}
function delete($dchat_id, $dmsgid)
{
    global $token;
    file_get_contents('https://api.telegram.org/bot'.$token.'/deleteMessage?chat_id='.$dchat_id.'&message_id='.$dmsgid);
}
if($command == "/start")
{
    $ret = message("$chat_id" , "$text");
    $msgid = $ret->result->message_id;
    $chatid = $ret->result->chat->id;
    sleep(3600);
    delete($chaid , $msgid);
}
</code>```

It sends the text again and again every ~2 minutes forever and deletes each sent message after an hour.

答: You used existing function called delete(), just rename that.</p>

Body:
I am building a telegram bot to send ads to my channels and I want them to be deleted after a certain period of time

But I need to get message id to delete it, when I run code like this

$update = json_decode(file_get_contents("php://input"));
$command = $update->message->text;
function message($mchat_id, $mtext)
{
    global $token;
    $ret=json_decode(file_get_contents('https://api.telegram.org/bot' .$token.'/sendMessage?chat_id='.$mchat_id.'&text='.$mtext.'&parse_mode=HTML'));
    return $ret;
}
function delete($dchat_id, $dmsgid)
{
    global $token;
    file_get_contents('https://api.telegram.org/bot'.$token.'/deleteMessage?chat_id='.$dchat_id.'&message_id='.$dmsgid);
}
if($command == "/start")
{
    $ret = message("$chat_id" , "$text");
    $msgid = $ret->result->message_id;
    $chatid = $ret->result->chat->id;
    sleep(3600);
    delete($chaid , $msgid);
}

It sends the text again and again every ~2 minutes forever and deletes each sent message after an hour.


问:
Check if PCollection is empty - Apache Beam
Is there any way to check if a PCollection is empty?

I haven't found anything relevant in the documentation of Dataflow and Apache Beam.

答:
There is no way to check size of the PCollection without applying a PTransform on it (such as Count.globally() or Combine.combineFn()) because PCollection is not like a typical Collection in Java SDK or so.

It is an abstraction of bounded or unbounded collection of data where data is fed into the collection for an operation being applied on it (e.g. PTransform). Also it is parallelized (as the P at the beginning of the class suggest).

Therefore you need a mechanism to get counts of elements from each worker/node and combine them to get a value. Whether it is 0 or n can not be known until the end of that transformation.


问:
Redirect seo-friendly URLs (htaccess)
I have a script that generates seo-friendly URLs like:

```<code>mydomain.com/song_here-is-the-song-title_3bhbex.html
or
mydomain.com/song_this-is-one-more-song_4mb6mb.html
</code>```

So it is generate like this scheme:
song_TITLE-OF-SONG_RANDOMID.html

How can I get this random-ID to foward it via htaccess?
Right now I have

```<code>RewriteRule ^song_([0-9]+)\.html$ /song-text.php?id=$1 [L]
</code>```

I need to change this rule, cause now I also have the songtitle as a slug and the ID is now also letters (not only digits).

How do I have to change my htaccess?

Thank you!

答:
This will work.

RewriteRule ^song_([a-zA-Z0-9_]+).html$ /song-text.php?id=$1

Title: Redirect seo-friendly URLs (htaccess)

Body:
I have a script that generates seo-friendly URLs like:

mydomain.com/song_here-is-the-song-title_3bhbex.html
or
mydomain.com/song_this-is-one-more-song_4mb6mb.html

So it is generate like this scheme:
song_TITLE-OF-SONG_RANDOMID.html

How can I get this random-ID to foward it via htaccess?
Right now I have

RewriteRule ^song_([0-9]+)\.html$ /song-text.php?id=$1 [L]

I need to change this rule, cause now I also have the songtitle as a slug and the ID is now also letters (not only digits).

How do I have to change my htaccess?

Thank you!


答:
```<code>myList.reduce((acc, val, idx) => (idx !== 0 && val.length && val[0]) ? acc.concat(val) : acc, []);
</code>```

this is standard list flattening with a filter, which is inherently a reduce operation.  A reduce takes a list and reduces it into a single value, in this case a flattened list since it's taking a list of lists.

you seem new to js so to walk you through this... im starting with myList, which is your array, and im running the array operation "reduce" on it, which does what I explained above.  the first argument to reduce is a function, called a reducer, to run on each item in the original array, the function takes several arguments, the first argument to the reducer is the "accumulated value" named acc in this case, this is the final value reduce will give you, the second named "val" is the current item in the list I'm operating on, and the 3rd in this case is the current index since we need it for our filter.

All i do in my reducer is 1st check that the index isn't 0, then than the current item has a length (0 counts as not having a length) and then that the value of the first item in the current item is "truthy" (empty strings are falsey).  If all of those are true, i concatenate the current item to my accumulated value, concat just makes 1 list out of 2.  if any are false, i just skip that item.  The final argument to reduce is the starting value, in this case an empty array.

edit: edited to filter out items that are lists with a single blank entry.

Title: Create new list

Body:
Suppose I have the following list :

[["Accounts"],["Budget Propane"],[""],[""],[""],["Laser AMP"],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""]]

With a general function, how could I parse that list in such a way new list will become [account1, account2]?

So I need the remove all the subempty lists and the element [Accounts].

function isBlank(line) {
  return line[0].trim() === '';
}

function parseData(data) {

  const output = [];

  data.forEach(function(line, index) {
    if (isBlank(line) || index === 0) {
      return;
    }

    output.push(line[0])
  });

  return output;
}

console.log(parseData([["Accounts"],["Budget Propane"],[""],[""],[""],["Laser AMP"],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""]]));

Body:
myList.reduce((acc, val, idx) => (idx !== 0 && val.length && val[0]) ? acc.concat(val) : acc, []);

this is standard list flattening with a filter, which is inherently a reduce operation.  A reduce takes a list and reduces it into a single value, in this case a flattened list since it's taking a list of lists.

you seem new to js so to walk you through this... im starting with myList, which is your array, and im running the array operation "reduce" on it, which does what I explained above.  the first argument to reduce is a function, called a reducer, to run on each item in the original array, the function takes several arguments, the first argument to the reducer is the "accumulated value" named acc in this case, this is the final value reduce will give you, the second named "val" is the current item in the list I'm operating on, and the 3rd in this case is the current index since we need it for our filter.

All i do in my reducer is 1st check that the index isn't 0, then than the current item has a length (0 counts as not having a length) and then that the value of the first item in the current item is "truthy" (empty strings are falsey).  If all of those are true, i concatenate the current item to my accumulated value, concat just makes 1 list out of 2.  if any are false, i just skip that item.  The final argument to reduce is the starting value, in this case an empty array.

edit: edited to filter out items that are lists with a single blank entry.


问:
Error when inserting datetime into SQL
I am having a problem inserting a datetime into SQL. my statement is...

```<code>INSERT INTO `booking.com`.`last_sign_in` (`personID`, `browser`,
`deviceType`, `deviceOS`, `location`, `time`) VALUES ('1', 'chrome
61', 'desktop', 'windows 10', 'Belfast', '20171114 10:34:09 AM');
</code>```

When I try to run this insert statement I get the error...

all help appreciated!!

答:
Try this

```<code>INSERT INTO `booking.com`.`last_sign_in` (`personID`, `browser`, `deviceType`, `deviceOS`, `location`, `time`)
VALUES (1, 'chrome 61', 'desktop', 'windows 10', 'Belfast', '2017-11-14 10:34:09');
</code>```

The dates have been changed to the correct format (dashes added and the AM removed) also, it looks like you're trying to add the string value '1' into the PersonID column which I am assuming is int so I have changed that to an int value based on that assumption

Title: Error when inserting datetime into SQL

Body:
I am having a problem inserting a datetime into SQL. my statement is...

INSERT INTO `booking.com`.`last_sign_in` (`personID`, `browser`,
`deviceType`, `deviceOS`, `location`, `time`) VALUES ('1', 'chrome
61', 'desktop', 'windows 10', 'Belfast', '20171114 10:34:09 AM');

When I try to run this insert statement I get the error...

all help appreciated!!

Body:
Try this

INSERT INTO `booking.com`.`last_sign_in` (`personID`, `browser`, `deviceType`, `deviceOS`, `location`, `time`)
VALUES (1, 'chrome 61', 'desktop', 'windows 10', 'Belfast', '2017-11-14 10:34:09');

The dates have been changed to the correct format (dashes added and the AM removed) also, it looks like you're trying to add the string value '1' into the PersonID column which I am assuming is int so I have changed that to an int value based on that assumption


问:
Sort Points Using C++
I have an array of std::vector<cv::Point> that looks like-

```<code>[49, 500]
[49, 129]
[441, 501]
[49, 374]
[440, 374]
[440, 259]
[440, 128]
[49, 260]
</code>```

Let consider array elements as [x, y]. Now I need to get 4 elements from the array having-

lowest x with highest y

lowest x with lowest y

highest x with lowest y

highest x with highest y

currently, I am using functions to sort based on conditions and then fetch a point.

```<code>bool SortForMinXMaxY(const Point & a, const Point &b)
{
    return (a.x < b.x || a.y > b.y) ;
}
</code>```

What should be the standard approach with C++ and OpenCV to achieve the goal?

答:
Your problem (finding lowest x value and highest y value) is ILL-POSED, since the lowest x value may be another point than the highest y value. You must not ask for both at the same point, but be clearer what you actually want. There are a number of possibilities:

The highest y amongst the points with lowest x

```<code>[](Point const&a, Point const&b)
{ return a.x==b.x? a.y<b.y : a.x>b.x; }
</code>```

the lowest x amongst the points with highest y

```<code>[](Point const&a, Point const&b)
{ return a.y==b.y? a.x>b.x : a.y<b.y; }
</code>```

the point with maximum difference y-x

```<code>[](Point const&a, Point const&b)
{ return a.y-a.x < b.y-b.x; }
</code>```

From your example, I guess it's the last one of these that you actually want, as [48,498] has neither the lowest x nor the highest y, but the largest difference.

Finally, for merely finding the maximum of (some function of) some values, you don't need to sort them, but merely do a single pass:

```<code> auto extremum = std::max_element(Points.begin(), Points.end(),
                                  [](Point const&a, Point const&b)
                                  { return a.y-a.x < b.y-b.x; });
</code>```

Title: Sort Points Using C++

Body:
I have an array of std::vector<cv::Point> that looks like-

[49, 500]
[49, 129]
[441, 501]
[49, 374]
[440, 374]
[440, 259]
[440, 128]
[49, 260]

Let consider array elements as [x, y]. Now I need to get 4 elements from the array having-

lowest x with highest y

lowest x with lowest y

highest x with lowest y

highest x with highest y

currently, I am using functions to sort based on conditions and then fetch a point.

bool SortForMinXMaxY(const Point & a, const Point &b)
{
    return (a.x  b.y) ;
}

What should be the standard approach with C++ and OpenCV to achieve the goal?

Body:
Your problem (finding lowest x value and highest y value) is ILL-POSED, since the lowest x value may be another point than the highest y value. You must not ask for both at the same point, but be clearer what you actually want. There are a number of possibilities:

The highest y amongst the points with lowest x

[](Point const&a, Point const&b)
{ return a.x==b.x? a.y<b.y : a.x>b.x; }

the lowest x amongst the points with highest y

[](Point const&a, Point const&b)
{ return a.y==b.y? a.x>b.x : a.y<b.y; }

the point with maximum difference y-x

[](Point const&a, Point const&b)
{ return a.y-a.x < b.y-b.x; }

From your example, I guess it's the last one of these that you actually want, as [48,498] has neither the lowest x nor the highest y, but the largest difference.

Finally, for merely finding the maximum of (some function of) some values, you don't need to sort them, but merely do a single pass:

 auto extremum = std::max_element(Points.begin(), Points.end(),
                                  [](Point const&a, Point const&b)
                                  { return a.y-a.x < b.y-b.x; });


问:
Creating Web Application in Android
How to create an offline web application in Android using android.webkit package?</p>

答: Using Phonegap framework should meet your purpose http://www.phonegap.com/</p>

Title: Creating Web Application in Android


问:
Skip Condtion if value is null
This should be really simple; however, I cannot wrap my head around it using the CASE statement.

```<code>DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
WHERE Quality = 1 AND Ready = @Test
</code>```

I would like to accomplish something similar to this:

```<code>DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
CASE @Test IS NOT NULL
  WHERE Quality = 1 AND Ready = @Test
ELSE
  WHERE Quality = 1
</code>```

UPDATE

I created a schema sample for quickly testing provided answers

```<code>--create a temporary table
CREATE TABLE #ImagesTable(
Quality BIT,
Ready BIT)

-- insert into the temporary table
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
</code>```

Declaring @Test as null should return all

Declaring @Test as 1 or 0 should return half records

答:
I think you want</p>

```<code>SELECT *
FROM #ImagesTable
WHERE Quality IS NULL
OR    (
        Quality = 1   AND
        Ready = @Test
      )
</code>```

Title: Skip Condtion if value is null

Body:
This should be really simple; however, I cannot wrap my head around it using the CASE statement.

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
WHERE Quality = 1 AND Ready = @Test

I would like to accomplish something similar to this:

DECLARE @Test INT = NULL
SELECT *
FROM StoreImages
CASE @Test IS NOT NULL
  WHERE Quality = 1 AND Ready = @Test
ELSE
  WHERE Quality = 1

UPDATE

I created a schema sample for quickly testing provided answers

--create a temporary table
CREATE TABLE #ImagesTable(
Quality BIT,
Ready BIT)

-- insert into the temporary table
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 1);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);
INSERT INTO #ImagesTable(Quality,Ready)
VALUES (1, 0);

Declaring @Test as null should return all

Declaring @Test as 1 or 0 should return half records

Body:
I think you want

SELECT *
FROM #ImagesTable
WHERE Quality IS NULL
OR    (
        Quality = 1   AND
        Ready = @Test
      )


问:
Powershell output - Row to column conversion
I found the following PowerShell VMware script that exports several pieces of information from the environment.

```<code>&{foreach($vm in (Get-VM)) {
$vm.ExtensionData.Guest.Net | select -Property @{N='VM';E={$vm.Name}},
@{N='Host';E={$vm.VMHost.Name}},
@{N='OS';E={$vm.Guest.OSFullName}},
@{N='Tools';E={$vm.ExtensionData.Guest.ToolsRunningStatus}},
@{N='NicType';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty Type))}},
@{N='VLAN';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty NetworkName))}},
@{N='IP';E={[string]::Join(',',($vm.Guest.IPAddress | Where {($_.Split(".")).length -eq 4}))}},
@{N='Gateway';E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | %{if($_.Gateway.IpAddress){$_.Gateway.IpAddress}}))}},
@{N='Subnet Mask';E={
            $dec = [Convert]::ToUInt32($(('1' * $_.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
            $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                    $Remainder = $dec % [Math]::Pow(256, $i)
                    (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                    $dec = $Remainder
                } )
            [String]::Join('.', $DottedIP)
        }},
@{N="DNS";E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))}},
@{N='MAC';E={[string]::Join(',',$_.MacAddress)}}}}
</code>```

The output of it, is in a following style: (several hundred of those "blocks", one per VM, showing two of them)

```<code>VM          : VMname1
Host        : ESXi1.domain.com
OS          : Red Hat Enterprise Linux 6 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 123-DMZ-VMnet
IP          : 10.10.10.40
Gateway     : 10.10.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13
MAC         : 01:50:56:9a:98:62

VM          : VMname2
Host        : ESXi2.domain.com
OS          : Microsoft Windows Server 2012 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 20-VMnet
IP          : 10.55.10.14
Gateway     : 10.55.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13,10.20.10.11,10.10.231.13
MAC         : 12:50:32:22:68:9c
</code>```

I have tried to find a correct approach to convert the output to the CSV format:
VM,HOST,OS,Tools,NicType,VLAN,IP,Gateway, Subnet Mask, DNS, MAC
VMname1,ESXi1.domain.com, etc
VMname1,ESXi2.domain.com, etc

With the "conversion script", also found on the internet, which I tried to adjust to meet my needs, I tried to convert the information however it doesn't seems to work.

```<code>$list = Get-Content C:\temp\IPs\results.txt
$i = 0
Do
{
$VM1 = $list[$i].value
$Host1 =$list[$i+1].value
$OS1 =$list[$i+2].value
$Tools1 =$list[$i+3].value
$NicType1 =$list[$i+4].value
$VLAN1 =$list[$i+5].value
$IP1 =$list[$i+6].value
$Gateway1 =$list[$i+7].value
$SubnetMask1 =$list[$i+8].value
$DNS1 =$list[$i+9].value
$MAC1 =$list[$i+10].value
[array]$converter += $VM1 + "," + $Host1 + "," + $OS1 + "," + $Tools1 + ","
+ $NicType1 + "," + $VLAN1 + "," + $IP1 + "," + $Gateway1 + "," +
$SubnetMask1 + "," + $DNS1 + "," + $MAC1
$i = $i + 11
} while ($i -le $list.count)
$converter = $converter|convertfrom-csv -header VM1, Host1, OS1, Tools1,
NicType1, VLAN1, IP1, Gateway1, SubnetMask1, DNS1, MAC1
$converter|export-csv C:\temp\IPs\results.csv -notypeinformation
</code>```

Please note, for some entries such as DNS or IP address, there might be multiple values.

How would I go and convert the rows to columns to capture all the available info?

Thank you.

答:
Edit: In hindsight, I have no idea why the original author is piping .Net to Select-Object when there is nothing done with that value.  I've updated my answer with a better representation

Putting it all together (with formatting):

```<code>#Requires -Version 3

$Collection = ForEach ($VM in (Get-VM))
{
    $Out = Select-Object -InputObject $VM -Property @(
        @{ N = 'VM'
           E = {$PSItem.Name}
         },
        @{ N = 'Host'
           E = {$PSItem.VMHost.Name}
         },
        @{ N = 'OS'
           E = {$PSItem.Guest.OSFullName}
         },
        @{ N = 'Tools'
           E = {$PSItem.ExtensionData.Guest.ToolsRunningStatus}
         },
        @{ N = 'NicType'
           E = {(Get-NetworkAdapter -Vm $PSItem).Type -join ','}
         },
        @{ N = 'VLAN'
           E = {(Get-NetworkAdapter -Vm $PSItem).NetworkName -join ','}
         },
        @{ N = 'IP'
           E = {($PSItem.Guest.IPAddress | Where-Object { ($PSItem -split '.').Count -eq 4}) -join ','}
         },
        @{ N = 'Gateway'
           E = {($PSItem.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | Where-Object { $PSItem.Gateway.IpAddress }) -join ','}
         },
        @{ N = 'Subnet Mask'
           E={
                $dec = [Convert]::ToUInt32($(('1' * $PSItem.ExtensionData.Guest.Net.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
                $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                        $Remainder = $dec % [Math]::Pow(256, $i)
                        (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                        $dec = $Remainder
                    } )
                [String]::Join('.', $DottedIP)
            }
         },
        @{ N = 'DNS'
           E = {$PSItem.ExtensionData.Guest.IpStack.DnsConfig.IpAddress -join ','}
         },
        @{ N = 'MAC'
           E = {$PSItem.MacAddress -join ','}
         }
    )

    $Out | Export-Csv -Path $Path -NoTypeInformation -Append -Force -Encoding 'UTF8'
    $Out
}
</code>```

If all you care about is the resulting CSV:

```<code>#Requires -Version 3

Get-VM |
    Select-Object -Property @(
        @{ N = 'VM'
           E = {$PSItem.Name}
         },
        @{ N = 'Host'
           E = {$PSItem.VMHost.Name}
         },
        @{ N = 'OS'
           E = {$PSItem.Guest.OSFullName}
         },
        @{ N = 'Tools'
           E = {$PSItem.ExtensionData.Guest.ToolsRunningStatus}
         },
        @{ N = 'NicType'
           E = {(Get-NetworkAdapter -Vm $PSItem).Type -join ','}
         },
        @{ N = 'VLAN'
           E = {(Get-NetworkAdapter -Vm $PSItem).NetworkName -join ','}
         },
        @{ N = 'IP'
           E = {($PSItem.Guest.IPAddress | Where-Object { ($PSItem -split '.').Count -eq 4}) -join ','}
         },
        @{ N = 'Gateway'
           E = {($PSItem.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | Where-Object { $PSItem.Gateway.IpAddress }) -join ','}
         },
        @{ N = 'Subnet Mask'
           E={
                $dec = [Convert]::ToUInt32($(('1' * $PSItem.ExtensionData.Guest.Net.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
                $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                        $Remainder = $dec % [Math]::Pow(256, $i)
                        (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                        $dec = $Remainder
                    } )
                [String]::Join('.', $DottedIP)
            }
         },
        @{ N = 'DNS'
           E = {$PSItem.ExtensionData.Guest.IpStack.DnsConfig.IpAddress -join ','}
         },
        @{ N = 'MAC'
           E = {$PSItem.MacAddress -join ','}
         }
    ) |
    Export-Csv -Path $Path -NoTypeInformation -Force -Encoding 'UTF8'
</code>```

Body:
I found the following PowerShell VMware script that exports several pieces of information from the environment.

&{foreach($vm in (Get-VM)) {
$vm.ExtensionData.Guest.Net | select -Property @{N='VM';E={$vm.Name}},
@{N='Host';E={$vm.VMHost.Name}},
@{N='OS';E={$vm.Guest.OSFullName}},
@{N='Tools';E={$vm.ExtensionData.Guest.ToolsRunningStatus}},
@{N='NicType';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty Type))}},
@{N='VLAN';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty NetworkName))}},
@{N='IP';E={[string]::Join(',',($vm.Guest.IPAddress | Where {($_.Split(".")).length -eq 4}))}},
@{N='Gateway';E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | %{if($_.Gateway.IpAddress){$_.Gateway.IpAddress}}))}},
@{N='Subnet Mask';E={
            $dec = [Convert]::ToUInt32($(('1' * $_.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
            $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                    $Remainder = $dec % [Math]::Pow(256, $i)
                    (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                    $dec = $Remainder
                } )
            [String]::Join('.', $DottedIP)
        }},
@{N="DNS";E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))}},
@{N='MAC';E={[string]::Join(',',$_.MacAddress)}}}}

The output of it, is in a following style: (several hundred of those "blocks", one per VM, showing two of them)

VM          : VMname1
Host        : ESXi1.domain.com
OS          : Red Hat Enterprise Linux 6 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 123-DMZ-VMnet
IP          : 10.10.10.40
Gateway     : 10.10.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13
MAC         : 01:50:56:9a:98:62

VM          : VMname2
Host        : ESXi2.domain.com
OS          : Microsoft Windows Server 2012 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 20-VMnet
IP          : 10.55.10.14
Gateway     : 10.55.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13,10.20.10.11,10.10.231.13
MAC         : 12:50:32:22:68:9c

I have tried to find a correct approach to convert the output to the CSV format:
VM,HOST,OS,Tools,NicType,VLAN,IP,Gateway, Subnet Mask, DNS, MAC
VMname1,ESXi1.domain.com, etc
VMname1,ESXi2.domain.com, etc

With the "conversion script", also found on the internet, which I tried to adjust to meet my needs, I tried to convert the information however it doesn't seems to work.

$list = Get-Content C:\temp\IPs\results.txt
$i = 0
Do
{
$VM1 = $list[$i].value
$Host1 =$list[$i+1].value
$OS1 =$list[$i+2].value
$Tools1 =$list[$i+3].value
$NicType1 =$list[$i+4].value
$VLAN1 =$list[$i+5].value
$IP1 =$list[$i+6].value
$Gateway1 =$list[$i+7].value
$SubnetMask1 =$list[$i+8].value
$DNS1 =$list[$i+9].value
$MAC1 =$list[$i+10].value
[array]$converter += $VM1 + "," + $Host1 + "," + $OS1 + "," + $Tools1 + ","
+ $NicType1 + "," + $VLAN1 + "," + $IP1 + "," + $Gateway1 + "," +
$SubnetMask1 + "," + $DNS1 + "," + $MAC1
$i = $i + 11
} while ($i -le $list.count)
$converter = $converter|convertfrom-csv -header VM1, Host1, OS1, Tools1,
NicType1, VLAN1, IP1, Gateway1, SubnetMask1, DNS1, MAC1
$converter|export-csv C:\temp\IPs\results.csv -notypeinformation

Please note, for some entries such as DNS or IP address, there might be multiple values.

How would I go and convert the rows to columns to capture all the available info?

Thank you.

Body:
Edit: In hindsight, I have no idea why the original author is piping .Net to Select-Object when there is nothing done with that value.  I've updated my answer with a better representation

Putting it all together (with formatting):

#Requires -Version 3

$Collection = ForEach ($VM in (Get-VM))
{
    $Out = Select-Object -InputObject $VM -Property @(
        @{ N = 'VM'
           E = {$PSItem.Name}
         },
        @{ N = 'Host'
           E = {$PSItem.VMHost.Name}
         },
        @{ N = 'OS'
           E = {$PSItem.Guest.OSFullName}
         },
        @{ N = 'Tools'
           E = {$PSItem.ExtensionData.Guest.ToolsRunningStatus}
         },
        @{ N = 'NicType'
           E = {(Get-NetworkAdapter -Vm $PSItem).Type -join ','}
         },
        @{ N = 'VLAN'
           E = {(Get-NetworkAdapter -Vm $PSItem).NetworkName -join ','}
         },
        @{ N = 'IP'
           E = {($PSItem.Guest.IPAddress | Where-Object { ($PSItem -split '.').Count -eq 4}) -join ','}
         },
        @{ N = 'Gateway'
           E = {($PSItem.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | Where-Object { $PSItem.Gateway.IpAddress }) -join ','}
         },
        @{ N = 'Subnet Mask'
           E={
                $dec = [Convert]::ToUInt32($(('1' * $PSItem.ExtensionData.Guest.Net.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
                $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                        $Remainder = $dec % [Math]::Pow(256, $i)
                        (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                        $dec = $Remainder
                    } )
                [String]::Join('.', $DottedIP)
            }
         },
        @{ N = 'DNS'
           E = {$PSItem.ExtensionData.Guest.IpStack.DnsConfig.IpAddress -join ','}
         },
        @{ N = 'MAC'
           E = {$PSItem.MacAddress -join ','}
         }
    )

    $Out | Export-Csv -Path $Path -NoTypeInformation -Append -Force -Encoding 'UTF8'
    $Out
}

If all you care about is the resulting CSV:

#Requires -Version 3

Get-VM |
    Select-Object -Property @(
        @{ N = 'VM'
           E = {$PSItem.Name}
         },
        @{ N = 'Host'
           E = {$PSItem.VMHost.Name}
         },
        @{ N = 'OS'
           E = {$PSItem.Guest.OSFullName}
         },
        @{ N = 'Tools'
           E = {$PSItem.ExtensionData.Guest.ToolsRunningStatus}
         },
        @{ N = 'NicType'
           E = {(Get-NetworkAdapter -Vm $PSItem).Type -join ','}
         },
        @{ N = 'VLAN'
           E = {(Get-NetworkAdapter -Vm $PSItem).NetworkName -join ','}
         },
        @{ N = 'IP'
           E = {($PSItem.Guest.IPAddress | Where-Object { ($PSItem -split '.').Count -eq 4}) -join ','}
         },
        @{ N = 'Gateway'
           E = {($PSItem.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | Where-Object { $PSItem.Gateway.IpAddress }) -join ','}
         },
        @{ N = 'Subnet Mask'
           E={
                $dec = [Convert]::ToUInt32($(('1' * $PSItem.ExtensionData.Guest.Net.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
                $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                        $Remainder = $dec % [Math]::Pow(256, $i)
                        (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                        $dec = $Remainder
                    } )
                [String]::Join('.', $DottedIP)
            }
         },
        @{ N = 'DNS'
           E = {$PSItem.ExtensionData.Guest.IpStack.DnsConfig.IpAddress -join ','}
         },
        @{ N = 'MAC'
           E = {$PSItem.MacAddress -join ','}
         }
    ) |
    Export-Csv -Path $Path -NoTypeInformation -Force -Encoding 'UTF8'