问:
Google Script - onEdit(e) not triggering
I have a google sheet with some script running behind it.  I've had to separate some of the tabs out to individual workbooks, and have been updating the script accordingly.  One of the functions I had was an onEdit(e) trigger, that was no longer running in the new workbook.  As part of my testing, I've simplified it to just:

```<code>function onEdit(e) {
  Logger.log("TEST");
}
</code>```

No matter the changes I make in the sheet this is attached to, the Logger.log never writes.

I've done some research, especially into the simple trigger restrictions, and one of those relates to openByURL, which I am using elsewhere in the script.

```<code>var otherBook = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/etcetc/edit');
</code>```

Even though the onEdit(e) doesn't directly relate, is the presence of the openByUrl within the script what is preventing the onEdit(e) from running?  If so, are there ways to get around that, so that I can trigger actions based on an edit, but also be able to pull data from an alternate workbook?

答:
I inserted the following into a new script and the onEdit(e) worked without an issue. To call functions from onEdit that are restricted for simple triggers, install the trigger instead and set it to fire on spreadsheet edit.

function onEdit(e) {
  Logger.log("TEST2");
}

function test() {
  var otherBook = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/etcetc/edit');
}```

Body:
I have a google sheet with some script running behind it.  I've had to separate some of the tabs out to individual workbooks, and have been updating the script accordingly.  One of the functions I had was an onEdit(e) trigger, that was no longer running in the new workbook.  As part of my testing, I've simplified it to just:

function onEdit(e) {
  Logger.log("TEST");
}

No matter the changes I make in the sheet this is attached to, the Logger.log never writes.

I've done some research, especially into the simple trigger restrictions, and one of those relates to openByURL, which I am using elsewhere in the script.

var otherBook = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/etcetc/edit');

Even though the onEdit(e) doesn't directly relate, is the presence of the openByUrl within the script what is preventing the onEdit(e) from running?  If so, are there ways to get around that, so that I can trigger actions based on an edit, but also be able to pull data from an alternate workbook?


来源: stackexchange

问:
Elm: Html embedded in Svg bug
In Elm I'm trying to embed a Html textarea in Svg, but the textarea won't load correctly. Can someone help me?

```<code>svgTextarea : Model -> Html Msg
svgTextarea model =
    let
        textspace =
            textarea [ onInput ChangeSvgText ] []

        ( w, h ) =
            ( 200, 200 )
    in
    svg
      [ width w
      , height h
      , viewBox <| "0 0 " ++ toString w ++ " " ++ toString h
      ]
      [ textspace ]
</code>```

Thanks in advance!

Example repo: https://github.com/gitLabor8/Elm-Html-embedded-in-Svg-bug

答:
A textarea on its own is not valid SVG. You need to wrap it in a foreignObject tag.

svgTextarea model =
    let
        textspace =
            Svg.foreignObject []
                [ textarea [ onInput ChangeSvgText ] [] ]
    ...
```

Note that foreignObject tags are not supported by all browsers.

ContentLicense: CC BY-SA 3.0

Title: Elm: Html embedded in Svg bug

Body:
In Elm I'm trying to embed a Html textarea in Svg, but the textarea won't load correctly. Can someone help me?

svgTextarea : Model -> Html Msg
svgTextarea model =
    let
        textspace =
            textarea [ onInput ChangeSvgText ] []

        ( w, h ) =
            ( 200, 200 )
    in
    svg
      [ width w
      , height h
      , viewBox <| "0 0 " ++ toString w ++ " " ++ toString h
      ]
      [ textspace ]

Thanks in advance!

Example repo: https://github.com/gitLabor8/Elm-Html-embedded-in-Svg-bug

Body:
A textarea on its own is not valid SVG. You need to wrap it in a foreignObject tag.

svgTextarea model =
    let
        textspace =
            Svg.foreignObject []
                [ textarea [ onInput ChangeSvgText ] [] ]
    ...

Note that foreignObject tags are not supported by all browsers.


问:
6-byte little-endian sequence from 32-bit timestamp multiplied by 1000
Take y = 1510751840.  Suppose you want the 6-byte little-endian sequence of bytes of the number y*1000.  You're using Lua 5.1.  How can you get it?  There is no integer datatype, only double, which is Lua's default.  How can that be done?

For example, if y = 1510743753, the 6-byte sequence should be: 01 5f bf 58 41 28.

Thank you!

Why do I ask?  I must produce a little-endian sequence for the number of miliseconds since the UNIX epoch using a Lua embedded system.  I have only the number of seconds and so I can produce a little-endian 4-byte sequence of this number.  But I must produce a 6-byte, 48-bit byte sequence.  So my idea is to multiply the 32-bit timestamp by 1000, but I can't seem to be able to multiply that number in my Lua 5.1 embeddable system.  So I'm hoping for a hack that allows me to get the 6-byte sequence corresponding to the timestamp * 1000.

答:
An alternate approach:</p>

```<code>function byte_n(val,byte_num)
  val = val * 1000
  for i = 1, byte_num-1 do
    val = ('%.0f'):format((val - val % 256) / 256)
  end
  return ('%02x'):format(val % 256)
end

y = 1510743753      --> 01 5f bf 58 41 28

print(byte_n(y,6))  --MSB
print(byte_n(y,5))
print(byte_n(y,4))
print(byte_n(y,3))
print(byte_n(y,2))
print(byte_n(y,1))  --LSB
</code>```

Body:
An alternate approach:

function byte_n(val,byte_num)
  val = val * 1000
  for i = 1, byte_num-1 do
    val = ('%.0f'):format((val - val % 256) / 256)
  end
  return ('%02x'):format(val % 256)
end

y = 1510743753      --> 01 5f bf 58 41 28

print(byte_n(y,6))  --MSB
print(byte_n(y,5))
print(byte_n(y,4))
print(byte_n(y,3))
print(byte_n(y,2))
print(byte_n(y,1))  --LSB


问:
How to retrieve a response when the request is sent by ajax (XMLHtttpRequest)
```<code>/* the following **frontend** function is invoked to
   send a new post (in json) to the node server */

addPost(postData) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(postData));
}

/* the following **server** code picks up the request
   from the function above */

app.post('/posts', bodyParser.json(), (request, response) => {
    new Promise(resolve => {
            // code to add request.body to database will be here
            resolve(request.body);
        })
        .then(data => response.send(data)); // *** How do I retrieve
    }                                       // *** this "data" in
);                                          // *** my frontend code?
</code>```

Hi all,

The top part of my code (frontend) is an ajax that sends a request in json format.

The bottom part of my code (node/express server) does the following:
   1) receives the request
   2) inserts "request.body" in a database
   3) sends a response back to the frontend.

This response is a Promise containing the request.body. How do I retrieve this response in my frontend code? It seems that ajax helps me send requests, but doesn't do anything about retrieving the response that comes back.

Thanks!

P.S. Since this data was originally sent from the frontend, one might say the frontend already has this data. However, I just want to know, in general, how to retrieve a response when the request is sent by ajax.

答:
```<code>const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        console.log(xhr.responseText);
    }
}
</code>```

xhr has an event handler onreadystatechange ,
you can say that the request has been successful when xhr.readyState == XMLHttpRequest.DONE.

more detailed doc on this can be availed @ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

you can also get the status code of the http  request from xhr.status

XMLHttpRequest is pretty Useful API, but it is too low level, it is now being superseded by FETCH API, which is awesome, it also supports promise interface, that means you can use .then and .catch , or the newer async/await.

you can read it up here @ https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

and an example @ https://googlechrome.github.io/samples/fetch-api/fetch-post.html

Body:
/* the following **frontend** function is invoked to
   send a new post (in json) to the node server */

addPost(postData) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(postData));
}

/* the following **server** code picks up the request
   from the function above */

app.post('/posts', bodyParser.json(), (request, response) => {
    new Promise(resolve => {
            // code to add request.body to database will be here
            resolve(request.body);
        })
        .then(data => response.send(data)); // *** How do I retrieve
    }                                       // *** this "data" in
);                                          // *** my frontend code?

Hi all,

The top part of my code (frontend) is an ajax that sends a request in json format.

The bottom part of my code (node/express server) does the following:
   1) receives the request
   2) inserts "request.body" in a database
   3) sends a response back to the frontend.

This response is a Promise containing the request.body. How do I retrieve this response in my frontend code? It seems that ajax helps me send requests, but doesn't do anything about retrieving the response that comes back.

Thanks!

P.S. Since this data was originally sent from the frontend, one might say the frontend already has this data. However, I just want to know, in general, how to retrieve a response when the request is sent by ajax.

Body:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        console.log(xhr.responseText);
    }
}

xhr has an event handler onreadystatechange ,
you can say that the request has been successful when xhr.readyState == XMLHttpRequest.DONE.

more detailed doc on this can be availed @ https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

you can also get the status code of the http  request from xhr.status

XMLHttpRequest is pretty Useful API, but it is too low level, it is now being superseded by FETCH API, which is awesome, it also supports promise interface, that means you can use .then and .catch , or the newer async/await.

you can read it up here @ https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

and an example @ https://googlechrome.github.io/samples/fetch-api/fetch-post.html


问:
How to update value in HashMap if Key field is an instance of a class?
Suppose I have a code snippet:

```<code>package practice;
import java.util.*;

public class Practice {
    public static void main(String[] args) {
        Map<Temp,Integer> m = new HashMap<>();
        m.put(new Temp(1,2), 5);
        m.put(new Temp(1,2), 6);
        System.out.println(m.size());
    }
}

class Temp {
    int x, y;
    public Temp(int a, int b) {
        this.x = a;
        this.y = b;
    }
}
</code>```

Output: 2

I am trying to update the value corresponding to the object new Temp(1,2) but it is inserting instead of replacing it. This is why the size is 2. How to replace the old value?

答:
Java compares the references by default, unless you implement equals and hashCode methods:

```<code>class Temp {
    // ...

    public boolean equals(Object obj) {
        Temp temp = (Temp)obj;
        return temp.x == this.x && temp.y == this.y;
    }

    public int hashCode() {
        return Objects.hash(this.x, this.y);
    }
}
</code>```

Then:

```<code>System.out.println(m.size()); // 1
</code>```

Body:
Suppose I have a code snippet:

package practice;
import java.util.*;

public class Practice {
    public static void main(String[] args) {
        Map<Temp,Integer> m = new HashMap<>();
        m.put(new Temp(1,2), 5);
        m.put(new Temp(1,2), 6);
        System.out.println(m.size());
    }
}

class Temp {
    int x, y;
    public Temp(int a, int b) {
        this.x = a;
        this.y = b;
    }
}

Output: 2

I am trying to update the value corresponding to the object new Temp(1,2) but it is inserting instead of replacing it. This is why the size is 2. How to replace the old value?

Body:
Java compares the references by default, unless you implement equals and hashCode methods:

class Temp {
    // ...

    public boolean equals(Object obj) {
        Temp temp = (Temp)obj;
        return temp.x == this.x && temp.y == this.y;
    }

    public int hashCode() {
        return Objects.hash(this.x, this.y);
    }
}

Then:

System.out.println(m.size()); // 1


问:
how to use SheetJS (js-xlsx) in angular 2
I'm learning angular2 and i wanted to use js-xlsx library in my project.

I installed xlsx npm install xlsx  and jszip npm install jszip and added them in my index.html

and added the typescript defitions tsd install xlsx

and I'm using webpack

but when I used it in

```<code>import * as xlsx from 'xlsx';
</code>```

but i get error
module build failed: error: cannot resolve module 'xlsx'

答:
For making xlsx work for angular 2+, you don't need any typings to be installed. Because the xlsx library contains the required typings in the package itself.

Step 1: Install xlsx using npm

```<code>npm install xlsx
</code>```

Step 2: Import xlsx in your service/component.

const XLSX = require('xlsx');

```<code>OR
</code>```

import * as XLSX from 'xlsx'; -- (This did not work for me)

Step 3: You can use the XLSX as below.

```<code>XLSX.utils.json_to_sheet(json);
</code>```

Body:
I'm learning angular2 and i wanted to use js-xlsx library in my project.

I installed xlsx npm install xlsx  and jszip npm install jszip and added them in my index.html

and added the typescript defitions tsd install xlsx

and I'm using webpack

but when I used it in

import * as xlsx from 'xlsx';

but i get error
module build failed: error: cannot resolve module 'xlsx'

Body:
For making xlsx work for angular 2+, you don't need any typings to be installed. Because the xlsx library contains the required typings in the package itself.

Step 1: Install xlsx using npm

npm install xlsx

Step 2: Import xlsx in your service/component.

const XLSX = require('xlsx');

OR

import * as XLSX from 'xlsx'; -- (This did not work for me)

Step 3: You can use the XLSX as below.

XLSX.utils.json_to_sheet(json);


问:
Concatenate ByteArrayOutputStream
```<code>public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
</code>```

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

```<code>public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
</code>```

答:
try the following to place the recordid first.</p>

```<code>ByteArrayOutputStream objectStream = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(objectStream);
dout.writeUTF(recordid);
dout.write(dataObject.toByteArrayOutputStream().toByteArray());
</code>```

ContentLicense: CC BY-SA 2.5

Title: Concatenate ByteArrayOutputStream

Body:
public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

Body:
try the following to place the recordid first.

ByteArrayOutputStream objectStream = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(objectStream);
dout.writeUTF(recordid);
dout.write(dataObject.toByteArrayOutputStream().toByteArray());


问:
Locating a valid NGINX template for nginx-ingress-controller? (Kubernetes)
I am trying to follow this tutorial on configuring nginx-ingress-controller for a Kubernetes cluster I deployed to AWS using kops.

https://daemonza.github.io/2017/02/13/kubernetes-nginx-ingress-controller/

When I run kubectl create -f ./nginx-ingress-controller.yml, the pods are created but error out. From what I can tell, the problem lies with the following portion of nginx-ingress-controller.yml:

volumes:
        - name: tls-dhparam-vol
          secret:
            secretName: tls-dhparam
        - name: nginx-template-volume
          configMap:
            name: nginx-template
            items:
            - key: nginx.tmpl
              path: nginx.tmpl```
</div>
</div>
</p>

<p>Error shown on the pods:</p>

<p>MountVolume.SetUp failed for volume "nginx-template-volume" : configmaps "nginx-template" not found</p>

<p>This makes sense, because the tutorial does not have the reader create this configmap before creating the controller. I know that I need to create the configmap using:</p>

<p><strong>kubectl create configmap nginx-template --from-file=nginx.tmpl=nginx.tmpl</strong></p>

<p>I've done this using <strong>nginx.tmpl</strong> files found from sources like this, but they don't seem to work (always fail with invalid NGINX template errors). Log example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>I1117 16:29:49.344882       1 main.go:94] Using build: https://github.com/bprashanth/contrib.git - git-92b2bac
I1117 16:29:49.402732       1 main.go:123] Validated default/default-http-backend as the default backend
I1117 16:29:49.402901       1 main.go:80] mkdir /etc/nginx-ssl: file exists already exists
I1117 16:29:49.402951       1 ssl.go:127] using file '/etc/nginx-ssl/dhparam/dhparam.pem' for parameter ssl_dhparam
F1117 16:29:49.403962       1 main.go:71] invalid NGINX template: template: nginx.tmpl:1: function "where" not defined</code>```

The image version used is quite old, but I've tried newer versions with no luck.

 containers:
        - name: nginx-ingress-controller
          image: gcr.io/google_containers/nginx-ingress-controller:0.8.3```

This thread is similar to my issue, but I don't quite understand the proposed solution. Where would I use docker cp to extract a usable template from? Seems like the templates I'm using use a language/syntax incompatible with Docker...?

答:
To copy the nginx template file from the ingress controller pod to your local machine, you can first grab the name of the pod with kubectl get pods then run kubectl exec [POD_NAME] -it -- cat /etc/nginx/template/nginx.tmpl > nginx.tmpl.

This will leave you with the nginx.tmpl file you can then edit and push back up as a configmap. I would recommend though keeping custom changes to the template to a minimum as it can make it hard for you to update the controller in the future.

Hope this helps!

Body:
I am trying to follow this tutorial on configuring nginx-ingress-controller for a Kubernetes cluster I deployed to AWS using kops.

https://daemonza.github.io/2017/02/13/kubernetes-nginx-ingress-controller/

When I run kubectl create -f ./nginx-ingress-controller.yml, the pods are created but error out. From what I can tell, the problem lies with the following portion of nginx-ingress-controller.yml:

volumes:
        - name: tls-dhparam-vol
          secret:
            secretName: tls-dhparam
        - name: nginx-template-volume
          configMap:
            name: nginx-template
            items:
            - key: nginx.tmpl
              path: nginx.tmpl

Error shown on the pods:

MountVolume.SetUp failed for volume "nginx-template-volume" : configmaps "nginx-template" not found

This makes sense, because the tutorial does not have the reader create this configmap before creating the controller. I know that I need to create the configmap using:

kubectl create configmap nginx-template --from-file=nginx.tmpl=nginx.tmpl

I've done this using nginx.tmpl files found from sources like this, but they don't seem to work (always fail with invalid NGINX template errors). Log example:

I1117 16:29:49.344882       1 main.go:94] Using build: https://github.com/bprashanth/contrib.git - git-92b2bac
I1117 16:29:49.402732       1 main.go:123] Validated default/default-http-backend as the default backend
I1117 16:29:49.402901       1 main.go:80] mkdir /etc/nginx-ssl: file exists already exists
I1117 16:29:49.402951       1 ssl.go:127] using file '/etc/nginx-ssl/dhparam/dhparam.pem' for parameter ssl_dhparam
F1117 16:29:49.403962       1 main.go:71] invalid NGINX template: template: nginx.tmpl:1: function "where" not defined

The image version used is quite old, but I've tried newer versions with no luck.

 containers:
        - name: nginx-ingress-controller
          image: gcr.io/google_containers/nginx-ingress-controller:0.8.3

This thread is similar to my issue, but I don't quite understand the proposed solution. Where would I use docker cp to extract a usable template from? Seems like the templates I'm using use a language/syntax incompatible with Docker...?


问:
How to query Azure Data Lake?
Coming from the database world, when we have something related to Data we use a ui tool to query data. Be it big or small.

Is there anything like SSMS, SQL WorkBench (For Big Data Redshift), Athena (Query Big Data S3) for Azure Data Lake?

I see Data Lake Analytics just queries the data and store it in file. Is there is anyway to query the data on Azure Data Lake via a UI Tool or WebBased Tool?

答:
No there is not (yet). Sure, you can run a query using the portal or using Visual Studio (docs) or Visual Studio  Code (docs) but all those tools will provide access to the generated file (which can be easily obtained or previewed)

Main reason is that u-sql / data lake analytics is geared toward long running jobs (that can take up from a few minutes to hours) to process the vast amount of data. Keeping that in mind you can hopefully better understand why these kind of direct query tooling is not (yet?) available.

EDIT: try upvoting this on the feedback site. What you are asking is a highly requested feature.

Title: How to query Azure Data Lake?


问:
How do I generate and open an Outlook email with Python (but do not send)
I have a script that automatically creates and sends emails sends emails using the simple function below:

```<code>def Emailer(text, subject, recipient):
    import win32com.client as win32

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    mail.send
</code>```

But how do I open this email in an Outlook window so that it can be manually edited and sent?

Ideally, I'd like something like this:

```<code>def __Emailer(text, subject, recipient, auto=True):
    import win32com.client as win32

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    if auto:
        mail.send
    else:
        mail.open # or whatever the correct code is
</code>```

答:
tldr: Use mail.Display(False) instead of mail.Display(True)

mail.Display(False) will still display the window.
If you use mail.Display(True) the scripts stops until the window is closed. So use mail.Display(False) this will open the window and your python script will move on to the next command. It is also useful to know that you can use mail.save() to save as draft in the draft folder.

Visit https://msdn.microsoft.com/en-us/VBA/Outlook-VBA/articles/mailitem-display-method-outlook to read more on this

ContentLicense: CC BY-SA 4.0

Body:
I have a script that automatically creates and sends emails sends emails using the simple function below:

def Emailer(text, subject, recipient):
    import win32com.client as win32

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    mail.send

But how do I open this email in an Outlook window so that it can be manually edited and sent?

Ideally, I'd like something like this:

def __Emailer(text, subject, recipient, auto=True):
    import win32com.client as win32

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    if auto:
        mail.send
    else:
        mail.open # or whatever the correct code is


问:
AppiumLibrary: Element Should Not Be Visible Keyword?
In AppiumLibrary, as of version 1.4.5, a very handy keyword called Element Should Be Visible has been introduced. But I am looking for the opposite version of that keyword too, which would be something like Element Should Not Be Visible. Since AppiumLibrary doesn't have that yet, is there any way we could achieve this?

答:
There's always the possibility of expanding the library's python code, this shouldn't be very difficult. You basically just need to clone the Element Should Be Visible keyword definition and change the condition to do the opposite.

But, if that's not a possibility for you, perhaps you could use the keyword Run Keyword And Expect Error, in combination with the keyword you mentioned, Element Should Be Visible. Using this keyword on an element that isn't visible would throw an error, which in this particular case would be the desired outcome.

Still, that's a fishy workaround which will not help the readability of your test, and you should consider first looking into expanding the library itself.


问:
Azure Traffic Manager with multiple web apps
I have two web apps, let's say API1 and WWW1 deployed on Azure.
these apps are deployed in the same azure region.

I would like to use high availability configured as active/passive with hot standby.

To achieve this I have replicated the apps in the paired region (API2 and WWW2) and I am creating a Traffic manager profile working in priority routing mode, and configure endpoints. More specifically I would like to configure that API1 is the primary endpoint and the API2 is the secondary. The same I would like to do with WWW1 and WWW2.

However I get an error because both the app (API1 and WWW1) are on the same azure region.

Do I need to configure two different Traffic manager profiles?

答:
Yes, you would create multiple Traffic Manager profiles and then nest them.

https://learn.microsoft.com/en-us/azure/traffic-manager/traffic-manager-routing-methods#a-name--performanceaperformance-traffic-routing-method

"If your profile contains multiple endpoints in the same Azure region,
  then Traffic Manager distributes traffic evenly across the available
  endpoints in that region. If you prefer a different traffic
  distribution within a region, you can use nested Traffic Manager
  profiles."

How to set up nested profiles.


问:
Change the background color of a div using Javascript and a json file
I am trying to dynamically create and color divs based on a .json file i have created. I have been able to create each individual div but adding the colors from the file is what I can't seem to do, i have been able to print out the color names but being able to change each div is giving me issues any assistance would be greatly appreciated.

My code is below.

index.html

```<code> <!DOCTYPE html>
<meta charset="utf-8">
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link rel="stylesheet" type="css/text" href="">
   <title>Json and Ajax</title>
</head>
<style>

    h1
    {
        margin-bottom: 60px;
    }

    .boxvalue
    {
        width:150px;
        height: 150px;
        border: 2px solid rgb(199, 91, 91);
        display: inline-block;
        margin: 20px;
    }

    .Colorname
    {
        font-size: 18px;
        font-weight: 600;
        margin: 20px;
        display: inline-block;
        text-align: center;
    }
</style>
<body>
<div class="container-fluid">
    <header>
      <h1>Colors</h1>
    </header>
   <div id="ColorArea">

   </div>
</div>
    <script src="colorequest.js"></script>
 </body>
</code>```

js File

```<code>var ColorContainer = document.getElementById('ColorArea');

var NewRequest = new XMLHttpRequest();
NewRequest.open('GET', 'colors.json', true);

NewRequest.onload = function()
{
    var ColorData = JSON.parse(NewRequest.responseText);
    renderHTML(ColorData);
};
NewRequest.send();

/* Function used to render the Color Data */
function renderHTML(data){
 var ColorInfo = " ";
 var Colordiv

 for (i = 0; i<data.length; i++)
    {
        ColorInfo += data[i].code.hex + " " + data[i].color + "<br>";
        Colordiv = document.createElement('div');
        Colordiv.classList.add('boxvalue');
        ColorContainer.appendChild(Colordiv);
    }

}
</code>```

json File

```<code>[
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]
</code>```

答:
You're really only missing an assignment to your divs' style property, which you can access using element.style.cssPropertyInCamelCase. You can access any inline CSS declaration this way, just convert the property name from kebab-case to camelCase in your JavaScript.

And since your colors JSON is going to be parsed as an array, you can also simplify the loop to a forEach call:

var colors = [{
    "color": "black",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [255, 255, 255, 1],
      "hex": "#000"
    }
  },
  {
    "color": "white",
    "category": "value",
    "code": {
      "rgba": [0, 0, 0, 1],
      "hex": "#FFF"
    }
  },
  {
    "color": "red",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [255, 0, 0, 1],
      "hex": "#F00"
    }
  },
  {
    "color": "blue",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [0, 0, 255, 1],
      "hex": "#00F"
    }
  },
  {
    "color": "yellow",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [255, 255, 0, 1],
      "hex": "#FF0"
    }
  },
  {
    "color": "green",
    "category": "hue",
    "type": "secondary",
    "code": {
      "rgba": [0, 255, 0, 1],
      "hex": "#0F0"
    }
  }
]

colors.forEach(function(color) {
  var colorDiv = document.createElement('div');
  colorDiv.textContent = color.color + ' ' + color.code.hex;
  colorDiv.style.backgroundColor = color.code.hex;
  document.getElementById('ColorArea').appendChild(colorDiv);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ColorArea {
  color: #ccc;
}</code>```

```

Body:
I am trying to dynamically create and color divs based on a .json file i have created. I have been able to create each individual div but adding the colors from the file is what I can't seem to do, i have been able to print out the color names but being able to change each div is giving me issues any assistance would be greatly appreciated.

My code is below.

index.html

 <!DOCTYPE html>
<meta charset="utf-8">

   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link rel="stylesheet" type="css/text" href="">
   <title>Json and Ajax</title>

Colors

js File

var ColorContainer = document.getElementById('ColorArea');

var NewRequest = new XMLHttpRequest();
NewRequest.open('GET', 'colors.json', true);

NewRequest.onload = function()
{
    var ColorData = JSON.parse(NewRequest.responseText);
    renderHTML(ColorData);
};
NewRequest.send();

/* Function used to render the Color Data */
function renderHTML(data){
 var ColorInfo = " ";
 var Colordiv

 for (i = 0; i<data.length; i++)
    {
        ColorInfo += data[i].code.hex + " " + data[i].color + "
";
        Colordiv = document.createElement('div');
        Colordiv.classList.add('boxvalue');
        ColorContainer.appendChild(Colordiv);
    }

}

json File

[
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]

Body:
You're really only missing an assignment to your divs' style property, which you can access using element.style.cssPropertyInCamelCase. You can access any inline CSS declaration this way, just convert the property name from kebab-case to camelCase in your JavaScript.

And since your colors JSON is going to be parsed as an array, you can also simplify the loop to a forEach call:

var colors = [{
    "color": "black",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [255, 255, 255, 1],
      "hex": "#000"
    }
  },
  {
    "color": "white",
    "category": "value",
    "code": {
      "rgba": [0, 0, 0, 1],
      "hex": "#FFF"
    }
  },
  {
    "color": "red",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [255, 0, 0, 1],
      "hex": "#F00"
    }
  },
  {
    "color": "blue",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [0, 0, 255, 1],
      "hex": "#00F"
    }
  },
  {
    "color": "yellow",
    "category": "hue",
    "type": "primary",
    "code": {
      "rgba": [255, 255, 0, 1],
      "hex": "#FF0"
    }
  },
  {
    "color": "green",
    "category": "hue",
    "type": "secondary",
    "code": {
      "rgba": [0, 255, 0, 1],
      "hex": "#0F0"
    }
  }
]

colors.forEach(function(color) {
  var colorDiv = document.createElement('div');
  colorDiv.textContent = color.color + ' ' + color.code.hex;
  colorDiv.style.backgroundColor = color.code.hex;
  document.getElementById('ColorArea').appendChild(colorDiv);
});

#ColorArea {
  color: #ccc;
}

<div id="ColorArea">
</div>


问:
Set font family in TVML
In my TVML app I am able to set font style properties such as font-size and font-weight using tv-text-style:none, however I am not able to set the font-family property, which seems to be ignored:

```<code>var Template = function() { return `<?xml version="1.0"    encoding="UTF-8" ?>
<document>
    <head>
        <style>
            .customText {
                tv-text-style: none;
                tv-position: center;
                color: white;
                font-size: 40px;
                font-weight: bold;
                font-family: Courier;
            }
        </style>
    </head>
    <paradeTemplate>
...
                <listItemLockup>
                    <title>Title</title>
                    <relatedContent>
                         <divTemplate>
                             <title class="customText">abcABC</title>
                         </divTemplate>
                    </relatedContent>
                </listItemLockup>
...
</code>```

Can I set a font-family different from the system font family?

Thanks for your help,

Luca

答:
font-family is now available in TVML. No need to use TVInterfaceFactory for custom font support anymore.

Example:

```<code>tv-text-style: 'none'
font-family: 'Times New Roman'
</code>```

Apple TV Markup Language Reference: font-family

Title: Set font family in TVML

Body:
In my TVML app I am able to set font style properties such as font-size and font-weight using tv-text-style:none, however I am not able to set the font-family property, which seems to be ignored:

var Template = function() { return `<?xml version="1.0"    encoding="UTF-8" ?>
<document>

    <paradeTemplate>
...
                <listItemLockup>
                    <title>Title</title>
                    <relatedContent>
                         <divTemplate>
                             <title class="customText">abcABC</title>
                         </divTemplate>
                    </relatedContent>
                </listItemLockup>
...

Can I set a font-family different from the system font family?

Thanks for your help,

Luca

Body:
font-family is now available in TVML. No need to use TVInterfaceFactory for custom font support anymore.

Example:

tv-text-style: 'none'
font-family: 'Times New Roman'

Apple TV Markup Language Reference: font-family


问:
Powershell: Encapsulate numbers in quotes if not already encapsulated
The system i'm working on stores SSNs in a database using varchar(10), I am not allowed to change that.
I have an automated script that runs, reading a submitted ticket, and using the query in the ticket, carries out the required task. Frequently we have queries being submitted with SSNs not in quotations, when stored as varchar this fails.
I want to have a regex that checks the query for any SSNs and if not encapsulated, does so with single quotations.
I'd been trying to use this but it's replacing the first and last characters in each numeric string. so 123456789 results in '2345678'.
Any help greatly appreciated.

```<code>$String = "SELECT firstname, lastname FROM table WHERE ssn in (123456786,876543217,'321654784',345676873)"
$String -replace "(?<!'|\d)\d","'" -replace "\d(?!'|\d)","'"
</code>```

Results in

```<code>SELECT firstname, lastname FROM table WHERE ssn in ('2345678','7654321','321654784','4567687')
</code>```

答:
Use lookarounds to avoid consuming the digits:

```<code>$String -replace "(?<!['\d])\d+(?!['\d])", "'`$&'"
</code>```

See the regex demo.

Details

(?<!['\d]) - a location that is not immediately preceded with a digit or single quote

\d+ - 1+ digits

(?!['\d]) - a location that is not immediately followed with a digit or single quote.

The "'`$&'" replacement replaced with the whole match ($&) enclosed with single quotes.

Body:
The system i'm working on stores SSNs in a database using varchar(10), I am not allowed to change that.
I have an automated script that runs, reading a submitted ticket, and using the query in the ticket, carries out the required task. Frequently we have queries being submitted with SSNs not in quotations, when stored as varchar this fails.
I want to have a regex that checks the query for any SSNs and if not encapsulated, does so with single quotations.
I'd been trying to use this but it's replacing the first and last characters in each numeric string. so 123456789 results in '2345678'.
Any help greatly appreciated.

$String = "SELECT firstname, lastname FROM table WHERE ssn in (123456786,876543217,'321654784',345676873)"
$String -replace "(?<!'|\d)\d","'" -replace "\d(?!'|\d)","'"

Results in

SELECT firstname, lastname FROM table WHERE ssn in ('2345678','7654321','321654784','4567687')

Body:
Use lookarounds to avoid consuming the digits:

$String -replace "(?<!['\d])\d+(?!['\d])", "'`$&'"

See the regex demo.

Details

(?<!['\d]) - a location that is not immediately preceded with a digit or single quote

\d+ - 1+ digits

(?!['\d]) - a location that is not immediately followed with a digit or single quote.

The "'`$&'" replacement replaced with the whole match ($&) enclosed with single quotes.


问:
How to create tables from column data instead of row data in HTML?
According to this article at W3 Schools, one can create a basic table in HTML like this:

```<code><table border="1">
    <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
    </tr>
    <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
    </tr>
</table>
</code>```

From above, it appears that one enters data by rows.

I have a situation where I need to enter all of the data by columns. Is something like this possible?

```<code><table border="1">
    <tc>
        <td>row 1, cell 1</td>
        <td>row 2, cell 1</td>
    </tc>
    <tc>
        <td>row 1, cell 2</td>
        <td>row 2, cell 2</td>
    </tc>
</table>
</code>```

答:
Just did this by using a bunch of uls filled with lis, seemed a lot cleaner than anything I could find. You'll have to do something like adding a class to all the uls and setting its style to display: inline-table.

```<code>@* pseudo html/razor *@
@foreach(var col in columns){
    <ul class='tableColumn'>
        foreach(var data in col){
            <li>data</li>
        }
    </ul>
}
</code>```

and some styling

```<code>.tableColumn {
    border: 1px solid;
    display: inline-table;
}
</code>```

Body:
According to this article at W3 Schools, one can create a basic table in HTML like this:

        row 1, cell 1
        row 1, cell 2

        row 2, cell 1
        row 2, cell 2

From above, it appears that one enters data by rows.

I have a situation where I need to enter all of the data by columns. Is something like this possible?

    <tc>
        row 1, cell 1
        row 2, cell 1
    </tc>
    <tc>
        row 1, cell 2
        row 2, cell 2
    </tc>

Body:
Just did this by using a bunch of uls filled with lis, seemed a lot cleaner than anything I could find. You'll have to do something like adding a class to all the uls and setting its style to display: inline-table.

@* pseudo html/razor *@
@foreach(var col in columns){
    <ul class='tableColumn'>
        foreach(var data in col){
            <li>data</li>
        }
    </ul>
}

and some styling

.tableColumn {
    border: 1px solid;
    display: inline-table;
}


问:
Splitting a list of twitter data
I have a file full of hundreds of un-separated tweets all formatted like so:

```<code>{"text": "Just posted a photo @ Navarre Conference Center", "created_at": "Sun  Nov 13 01:52:03 +0000 2016", "coordinates": [-86.8586,  30.40299]}
</code>```

I am trying to split them up so I can assign each part to a variable.

The text

The timestamp

The location coordinates

I was able to split the tweets up using .split('{}') but I don't really know how to split the rest into the three things that I want.

My basic idea that didn't work:

```<code>file = open('tweets_with_time.json' , 'r')
line = file.readline()

    for line in file:

        line = line.split(',')

        message = (line[0])
        timestamp = (line[1])
        position = (line[2])

        #just to test if it's working
        print(position)
</code>```

Thanks!

答:
It looks like well-formatted JSON data. Try the following:

```<code>import json
from pprint import pprint

file_ptr = open('tweets_with_time.json' , 'r')
data = json.load(file_ptr)
pprint(data)
</code>```

It should parse your data into a nice Python dictionary. You can access the elements by their names like:

```<code># Return the first 'coordinates' data point as a list of floats
data[0]["coordinates"]

# Return the 5th 'text' data point as a string
data[4]["text"]
</code>```

Title: Splitting a list of twitter data

Body:
I have a file full of hundreds of un-separated tweets all formatted like so:

{"text": "Just posted a photo @ Navarre Conference Center", "created_at": "Sun  Nov 13 01:52:03 +0000 2016", "coordinates": [-86.8586,  30.40299]}

I am trying to split them up so I can assign each part to a variable.

The text

The timestamp

The location coordinates

I was able to split the tweets up using .split('{}') but I don't really know how to split the rest into the three things that I want.

My basic idea that didn't work:

file = open('tweets_with_time.json' , 'r')
line = file.readline()

    for line in file:

        line = line.split(',')

        message = (line[0])
        timestamp = (line[1])
        position = (line[2])

        #just to test if it's working
        print(position)

Thanks!

Body:
It looks like well-formatted JSON data. Try the following:

import json
from pprint import pprint

file_ptr = open('tweets_with_time.json' , 'r')
data = json.load(file_ptr)
pprint(data)

It should parse your data into a nice Python dictionary. You can access the elements by their names like:

# Return the first 'coordinates' data point as a list of floats
data[0]["coordinates"]

# Return the 5th 'text' data point as a string
data[4]["text"]


问:
Passing DbContext reference to another method from within a using statement bad practice?
I have a method that uses an EF 6 data model and is wrapped within a using statement.  There are some additional and common steps that need to be done where Id rather not include them all in one method.  The code below, while not the exact code Im using, seems to work.  However, Im wondering if there is any "gotchyas" Im setting up related to EF-specific issues dealing with the DbContext itself.  Especially in how everything must be translated to SQL?

The main goal is to do several operations on several entities before calling SaveChanges so that the implicit transactions covers all the changes rather than calling SaveChanges more than once leaving the option open for orphaned changes.

```<code>AppendFlagToOrder(ref DbContext tx, ref CustOrder o) {
    var oSettings = (from a in tx.OrderSettings where a.Type == o.OrderType select a).FirstOrDefault();
    if(!oSettings == null) {
        o.IsFlagged = oSettings.Flagged
    }
}

CheckOrderFlag(int OrderId) {

     using (var ctx = new StoreDbCtx()) {
        CustOrder co = (from a in ctx.Orders where a.Id == OrderId select a).FirstOrDefault();
        AppendFlagToOrder(ctx,co);

        //-- continue with other operations
    }
}
</code>```

答: You normally don't want to pass DbContext around like that as anyone would have the ability to call SaveChanges() on you at any point.  The easiest thing to do would be to create an IStoreDbCtx interface that only has the DbSets on it you want exposed.  Then you send that type through to the sub methods so they can't access SaveChanges() on you.</p>

Body:
I have a method that uses an EF 6 data model and is wrapped within a using statement.  There are some additional and common steps that need to be done where Id rather not include them all in one method.  The code below, while not the exact code Im using, seems to work.  However, Im wondering if there is any "gotchyas" Im setting up related to EF-specific issues dealing with the DbContext itself.  Especially in how everything must be translated to SQL?

The main goal is to do several operations on several entities before calling SaveChanges so that the implicit transactions covers all the changes rather than calling SaveChanges more than once leaving the option open for orphaned changes.

AppendFlagToOrder(ref DbContext tx, ref CustOrder o) {
    var oSettings = (from a in tx.OrderSettings where a.Type == o.OrderType select a).FirstOrDefault();
    if(!oSettings == null) {
        o.IsFlagged = oSettings.Flagged
    }
}

CheckOrderFlag(int OrderId) {

     using (var ctx = new StoreDbCtx()) {
        CustOrder co = (from a in ctx.Orders where a.Id == OrderId select a).FirstOrDefault();
        AppendFlagToOrder(ctx,co);

        //-- continue with other operations
    }
}


问:
add several values into one cell of prettyTable
I have list like:

```<code>[1, 2, ['a', 'b', 'c',], 3]
</code>```

How can I add a line in a table to insert values of sublist

```<code>['a', 'b', 'c',]
</code>```

in one cell of table. The values have to be under each other

Is there any other libs to handle this use case if prettyTable is not available?

for now  i have following code:

```<code>table = PrettyTable(headers)
for line in lines:
        table.add_row(line)
print table
</code>```

but sublist is displayed as list in the cell. I haven't found any information in prettyTable documentation about adding several items into one cell

答:
Maybe it will be hellpufull for someone:

list

```<code>['a', 'b', 'c',]
</code>```

should be converted in such format

```<code>"\n".join(['a', 'b', 'c',]).
</code>```

And than new string has to replace sublist so final result has to be

```<code>[1, 2, 'a\nb\nc', 3].
</code>```

In such way 3-rd element of the list will be displayed as three elements one under another while using prettyTable

Body:
I have list like:

[1, 2, ['a', 'b', 'c',], 3]

How can I add a line in a table to insert values of sublist

['a', 'b', 'c',]

in one cell of table. The values have to be under each other

Is there any other libs to handle this use case if prettyTable is not available?

for now  i have following code:

table = PrettyTable(headers)
for line in lines:
        table.add_row(line)
print table

but sublist is displayed as list in the cell. I haven't found any information in prettyTable documentation about adding several items into one cell

Body:
Maybe it will be hellpufull for someone:

list

['a', 'b', 'c',]

should be converted in such format

"\n".join(['a', 'b', 'c',]).

And than new string has to replace sublist so final result has to be

[1, 2, 'a\nb\nc', 3].

In such way 3-rd element of the list will be displayed as three elements one under another while using prettyTable


问:
Is there a way to assert that a route has not been called in Cypress?
I am trying to assert that a route has not been called in Cypress. I thoroughly looked through the documentation and have found nothing.

I am trying to do something like this:

```<code>cy.get('@myRouteAlias').should('have.not.been.called');
</code>```

I am currently working around this by asserting that the successful request toast message is not being displayed but it is a flimsy solution.

Any ideas?

答:
It is very difficult to test a situation where an action has not occured. With this type of assertion, you can really only say:

"The XHR request was not made within the 400ms that Cypress looked for this XHR request to have been made (or whatever you set your timeout to be)"

This doesn't really confirm that the XHR request was never called.

That being said, Cypress offers a way to retrieve all XHR requests made using the undocumented cy.state('requests'). You could check the length of that, filter them by alias, etc to probably determine what you want.

Body:
I am trying to assert that a route has not been called in Cypress. I thoroughly looked through the documentation and have found nothing.

I am trying to do something like this:

cy.get('@myRouteAlias').should('have.not.been.called');

I am currently working around this by asserting that the successful request toast message is not being displayed but it is a flimsy solution.

Any ideas?


问:
How do I pass command line arguments to Python from VS in Debug mode?
I am working with Python Tools for Visual Studio.  (Note, not IronPython.)

I need to work with arguments passed to the module from the command line.  I see how to start the module in Debug by right-clicking in the code window and selecting "Start with Debugging".  But this approach never prompts me for command line arguments, and len(sys.argv) always == 1.

How do I start my module in debug mode and also pass arguments to it so sys.argv has more than 1 member?

答:
I have solved this by putting a breakpoint on the first line of my script and opening the Immediate window in VS (where you can execute commands in the context of your script). Then I run</p>

```<code>import sys
sys.argv += 'arg1 arg2 --arg3'.split()
</code>```

Body:
I have solved this by putting a breakpoint on the first line of my script and opening the Immediate window in VS (where you can execute commands in the context of your script). Then I run

import sys
sys.argv += 'arg1 arg2 --arg3'.split()


问:
SQL Server Connection refused and jTDS driver not working
I'm trying to connect to my local SQL Server Database. The database name is MDB and those are the credentials I use. Tried with user="User" as well and it didn't work.

I have the following jar into my library: jtds-1.3.1.jar

The version of SQL server I use is 2012.

```<code>String url = "jdbc:jtds:sqlserver://localhost:1344/MDB;instance=sqlserver;useNTLMv2=true;";
String user = "User-PC\\User";
String pass = "";
</code>```

I also tried with localhost:1099 and no success.

```<code>try
{
    Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch (ClassNotFoundException e){
    e.printStackTrace();
    System.out.println("1st error");
}
try
{
    Connection con = DriverManager.getConnection( dbUrl, dbUser, dbPwd );
    System.out.println("Worked");
} catch (SQLException e){
    e.printStackTrace();
    System.out.println("Driver error");
}
</code>```

I have the JTDS jar into my external libraries.
The error I get is the following:

java.sql.SQLException: Network error IOException: Connection refused:
  connect   at
  net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:436)
    at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)    at
  java.sql.DriverManager.getConnection(DriverManager.java:571)  at
  java.sql.DriverManager.getConnection(DriverManager.java:215)  at
  Main.main(Main.java:33)   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
  com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
  Caused by: java.net.ConnectException: Connection refused: connect     at
  java.net.DualStackPlainSocketImpl.connect0(Native Method)     at
  java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at
  java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at
  java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at
  java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)   at
  java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)    at
  java.net.Socket.connect(Socket.java:579)  at
  net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:288)
    at
  net.sourceforge.jtds.jdbc.SharedSocket.(SharedSocket.java:251)
    at
  net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:331)
    ... 9 more

Info from SQL:
Login name:User-PC\User
Server name: USER-PC

答: You need to make sure TCP/IP ports are enabled in SQL server configuration and the SQL Server Browser service is also running.</p>

Body:
I'm trying to connect to my local SQL Server Database. The database name is MDB and those are the credentials I use. Tried with user="User" as well and it didn't work.

I have the following jar into my library: jtds-1.3.1.jar

The version of SQL server I use is 2012.

String url = "jdbc:jtds:sqlserver://localhost:1344/MDB;instance=sqlserver;useNTLMv2=true;";
String user = "User-PC\\User";
String pass = "";

I also tried with localhost:1099 and no success.

try
{
    Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch (ClassNotFoundException e){
    e.printStackTrace();
    System.out.println("1st error");
}
try
{
    Connection con = DriverManager.getConnection( dbUrl, dbUser, dbPwd );
    System.out.println("Worked");
} catch (SQLException e){
    e.printStackTrace();
    System.out.println("Driver error");
}

I have the JTDS jar into my external libraries.
The error I get is the following:

java.sql.SQLException: Network error IOException: Connection refused:
  connect   at
  net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:436)
    at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)    at
  java.sql.DriverManager.getConnection(DriverManager.java:571)  at
  java.sql.DriverManager.getConnection(DriverManager.java:215)  at
  Main.main(Main.java:33)   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)     at
  com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
  Caused by: java.net.ConnectException: Connection refused: connect     at
  java.net.DualStackPlainSocketImpl.connect0(Native Method)     at
  java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at
  java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at
  java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at
  java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)   at
  java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)    at
  java.net.Socket.connect(Socket.java:579)  at
  net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:288)
    at
  net.sourceforge.jtds.jdbc.SharedSocket.(SharedSocket.java:251)
    at
  net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:331)
    ... 9 more

Info from SQL:
Login name:User-PC\User
Server name: USER-PC


问:
c++ Linux TickCount
Is there a similar function like GetTickCount() for Linux?

I´ve tried out some other sutff, but they didn´t work at all.

So it should return the exact time in milliseconds since startup.

答:
```<code>/// Returns the number of ticks since an undefined time (usually system startup).
static uint64_t GetTickCountMs()
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);

    return (uint64_t)(ts.tv_nsec / 1000000) + ((uint64_t)ts.tv_sec * 1000ull);
}
</code>```

Also useful...

```<code>/// Computes the elapsed time, in milliseconds, between two 'timespec'.
inline uint32_t TimeElapsedMs(const struct timespec& tStartTime, const struct timespec& tEndTime)
{
   return 1000*(tEndTime.tv_sec - tStartTime.tv_sec) +
          (tEndTime.tv_nsec - tStartTime.tv_nsec)/1000000;
}
</code>```

Title: c++ Linux TickCount

Body:
/// Returns the number of ticks since an undefined time (usually system startup).
static uint64_t GetTickCountMs()
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);

    return (uint64_t)(ts.tv_nsec / 1000000) + ((uint64_t)ts.tv_sec * 1000ull);
}

Also useful...

/// Computes the elapsed time, in milliseconds, between two 'timespec'.
inline uint32_t TimeElapsedMs(const struct timespec& tStartTime, const struct timespec& tEndTime)
{
   return 1000*(tEndTime.tv_sec - tStartTime.tv_sec) +
          (tEndTime.tv_nsec - tStartTime.tv_nsec)/1000000;
}


问:
Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia
I opened a webcam by using the following JavaScript code:

const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
```

Is there any JavaScript code to stop or close the webcam?

答:
Don't use stream.stop(), it's deprecated

MediaStream Deprecations

Use stream.getTracks().forEach(track => track.stop())

Body:
I opened a webcam by using the following JavaScript code:

const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });

Is there any JavaScript code to stop or close the webcam?


问:
templatetag: QuerySet' object has no attribute 'getlist'
I'm greeted with the following error when attempting to follow a books example of templatetags with modification:

```<code>QuerySet' object has no attribute 'getlist'report_id=88&report_id=89 HTTP/1.1" 500 180158
</code>```

I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such:

```<code>Security

        accounts

           templatetags

                app_filters.py

                __init__.py
</code>```

My app_filter.py is defined as such:

```<code>from django import template
register = template.Library()

@register.filter
def get_list(querydict, itemToGet ):

    return querydict.getlist(itemToGet)
</code>```

My settings.py includes the following:

```<code>INSTALLED_APPS = [
    'django_python3_ldap',
    'django_extensions',
    'django_filters',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
]
</code>```

My view is passing the array correctly:

```<code>checked = request.GET.get('report_id')
checkedlist = request.GET.getlist('report_id')

reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)

print (checked)
print (checkedlist)

args = {'retreivecheckbox': reportlist}

return render(request,'accounts/requestaccess.html', args)
</code>```

I see the array in my console, when doing a print checkedlist:

```<code>['75', '76', '77']
</code>```

My template is the following:

```<code>{% load app_filters %}
{% for reports in retreivecheckbox %}

        {{ retreivecheckbox|get_list:'report_id' }}
    </div>
{% endfor %}
</code>```

答:
You're calling @register.filter with a path. I think you mean to call it with @register.filter('get_list')

Take a look at the docs: these are the two use examples:

```<code>@register.filter(name='cut')
def cut(value, arg):
    return value.replace(arg, '')

@register.filter
def lower(value):
    return value.lower()
</code>```

Those would create two filters, lower and cut.

Alternatively, you can call @register.filter and pass the name as the first parameter, as in these cases:

```<code>register.filter('cut', cut)
register.filter('lower', lower)
</code>```

Body:
I'm greeted with the following error when attempting to follow a books example of templatetags with modification:

QuerySet' object has no attribute 'getlist'report_id=88&report_id=89 HTTP/1.1" 500 180158

I'm following the instructions of adding templatetags to my app directory and included the init.py and the app_filter.py i'd like to filter on, as such:

Security

        accounts

           templatetags

                app_filters.py

                __init__.py

My app_filter.py is defined as such:

from django import template
register = template.Library()

@register.filter
def get_list(querydict, itemToGet ):

    return querydict.getlist(itemToGet)

My settings.py includes the following:

INSTALLED_APPS = [
    'django_python3_ldap',
    'django_extensions',
    'django_filters',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
]

My view is passing the array correctly:

checked = request.GET.get('report_id')
checkedlist = request.GET.getlist('report_id')

reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)

print (checked)
print (checkedlist)

args = {'retreivecheckbox': reportlist}

return render(request,'accounts/requestaccess.html', args)

I see the array in my console, when doing a print checkedlist:

['75', '76', '77']

My template is the following:

{% load app_filters %}
{% for reports in retreivecheckbox %}

        {{ retreivecheckbox|get_list:'report_id' }}

{% endfor %}

Body:
You're calling @register.filter with a path. I think you mean to call it with @register.filter('get_list')

Take a look at the docs: these are the two use examples:

@register.filter(name='cut')
def cut(value, arg):
    return value.replace(arg, '')

@register.filter
def lower(value):
    return value.lower()

Those would create two filters, lower and cut.

Alternatively, you can call @register.filter and pass the name as the first parameter, as in these cases:

register.filter('cut', cut)
register.filter('lower', lower)


问:
I need assistance with Docusign API Authentication
I have tried authentication using DocuSign API.

When I send the request using jQuery ajax, I keep getting the "Access-Control-Allow-Origin" Header error.

When I try with PHP curl, I don't get any response. Do you have any idea of the issue.??

If you need more details, you can ask in the comments.
Thanks in advance.

答:
Thanks for the reply Ergin.
Here is what i tried.

```<code>$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://account-d.docusign.com/oauth/token&response_type=code&scope=signature&client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&state=a39fh23hnf23&redirect_uri=https://www.google.com/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_FOLLOWLOCATION => 1,
  CURLOPT_SSL_VERIFYHOST => false,
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "postman-token: a51a80ff-b741-3d19-4fd5-1099f034e1ae"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
   print_r($response);
}
</code>```

I am not sure about what headers to use in here, but I've tried using the code from Postman and it still doesn't work. Thanks

Body:
Thanks for the reply Ergin.
Here is what i tried.

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://account-d.docusign.com/oauth/token&response_type=code&scope=signature&client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&state=a39fh23hnf23&redirect_uri=https://www.google.com/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_FOLLOWLOCATION => 1,
  CURLOPT_SSL_VERIFYHOST => false,
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "postman-token: a51a80ff-b741-3d19-4fd5-1099f034e1ae"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
   print_r($response);
}

I am not sure about what headers to use in here, but I've tried using the code from Postman and it still doesn't work. Thanks


问:
Node-red users vs flows
How can I bind different
node-auth users to specific flows or tabs? </p>

<p>I succeeded to set more users with own login credentials, I would like to bind each to a different flow or even dashboard tab. </p>

答:
Short answer, you can not.

Node-RED is not a true multi-user environment. The only option is read-only vs read-write access to the flow editor.

Title: Node-red users vs flows

Body:
How can I bind different
node-auth users to specific flows or tabs?

I succeeded to set more users with own login credentials, I would like to bind each to a different flow or even dashboard tab.


问:
IOException Java
I tried to run this piece of code without an internet connection, expecting and IOException to trigger:

```<code>import java.net.*;
import java.io.*;

public class API_connect {

    public static void main(String[] args) {
        try {
            URL API = new URL("http://api.football-data.org");
            URLConnection API_connection = API.openConnection();
        }
        catch(MalformedURLException exception) {
            System.out.print(exception);
        }
        catch(IOException exception) {
            System.out.print(exception);
            System.out.print("is something going on here?");
        }
    }

}
</code>```

And well... To my surprise nothing was printed, and I can't figure out why. Wouldn't a lack of internet connection be the main reason why an IOException is thrown here?

答:
openConnection() does not actually try to connect:

It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect().

Try calling connect() on it.

Alternatively, you could try the following:

```<code>new URL(...).openStream().read();
</code>```

That would actually try to read 1 byte from that url and would fail.

Title: IOException Java

Body:
I tried to run this piece of code without an internet connection, expecting and IOException to trigger:

import java.net.*;
import java.io.*;

public class API_connect {

    public static void main(String[] args) {
        try {
            URL API = new URL("http://api.football-data.org");
            URLConnection API_connection = API.openConnection();
        }
        catch(MalformedURLException exception) {
            System.out.print(exception);
        }
        catch(IOException exception) {
            System.out.print(exception);
            System.out.print("is something going on here?");
        }
    }

}

And well... To my surprise nothing was printed, and I can't figure out why. Wouldn't a lack of internet connection be the main reason why an IOException is thrown here?

Body:
openConnection() does not actually try to connect:

It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect().

Try calling connect() on it.

Alternatively, you could try the following:

new URL(...).openStream().read();

That would actually try to read 1 byte from that url and would fail.


问:
Mathematica: define function controlling order of substitutions
I want to define a function s[t, n] that returns the value at point t of the FourierTrigSeries of n terms of a given function f(t). For instance, for f(t) = t^2:

```<code>s[t_, n_] = FourierTrigSeries[t^2, t, n];  (* 2nd input = indep. variable *)
s[t, 3]
    Out =   Pi^2 / 3 + 4 (-Cos[t] + 1/4 Cos[2 t] - 1/9 Cos[3 t])
</code>```

which is fine (a function of t). To evaluate it at t = 0:

```<code>s[t, 3] /. t -> 0
    Out =   -31 / 9 + Pi^2 / 3
</code>```

This is what I would like to see as the output of s[0, 3], meaning "evaluate at t=0 the FourierTrigSeries of 3 terms".

However doing s[0,3] makes t = 0 "too early", so the original function f(t)=t^2 becomes identically 0; even the independent variable t (second input to FourierTrigSeries) becomes 0 too, which makes no sense. The result is that Mathematica cannot read my mind and returns as follows:

```<code>s[0, 3]
    Out =     FourierTrigSeries[0,0,3]
</code>```

Summarizing: I would like to define the function s[t, n] such that n is substituted for its value first and, only after that, t is substituted by its value for evaluation.

I have tried doing s[n, t] instead of s[t, n]; also tried := (delayed evaluation) instead of = in different ways, and in combination with things like

```<code>ss[tdelay_, n_] = s[t, n] /. t -> tdelay
</code>```

But nothing seems to work. How can I get the behavior I want?

Thank you in advance!

答:
After seeing Chris's answer I've tried to see why Module was needed and I have found another way which, for some reason, escaped me when I first tried:

```<code>f[t_] = t^2;    (* or write t0^2 in line below *)
s[t_, n_] := FourierTrigSeries[f[t0], t0, n] /. t0 -> t
s[0, 3]
    Out =   -(31/9) + Pi^2 / 3
</code>```

Apparently it can be done without the Module thing...

Thank you anyway!

Body:
I want to define a function s[t, n] that returns the value at point t of the FourierTrigSeries of n terms of a given function f(t). For instance, for f(t) = t^2:

s[t_, n_] = FourierTrigSeries[t^2, t, n];  (* 2nd input = indep. variable *)
s[t, 3]
    Out =   Pi^2 / 3 + 4 (-Cos[t] + 1/4 Cos[2 t] - 1/9 Cos[3 t])

which is fine (a function of t). To evaluate it at t = 0:

s[t, 3] /. t -> 0
    Out =   -31 / 9 + Pi^2 / 3

This is what I would like to see as the output of s[0, 3], meaning "evaluate at t=0 the FourierTrigSeries of 3 terms".

However doing s[0,3] makes t = 0 "too early", so the original function f(t)=t^2 becomes identically 0; even the independent variable t (second input to FourierTrigSeries) becomes 0 too, which makes no sense. The result is that Mathematica cannot read my mind and returns as follows:

s[0, 3]
    Out =     FourierTrigSeries[0,0,3]

Summarizing: I would like to define the function s[t, n] such that n is substituted for its value first and, only after that, t is substituted by its value for evaluation.

I have tried doing s[n, t] instead of s[t, n]; also tried := (delayed evaluation) instead of = in different ways, and in combination with things like

ss[tdelay_, n_] = s[t, n] /. t -> tdelay

But nothing seems to work. How can I get the behavior I want?

Thank you in advance!

Body:
After seeing Chris's answer I've tried to see why Module was needed and I have found another way which, for some reason, escaped me when I first tried:

f[t_] = t^2;    (* or write t0^2 in line below *)
s[t_, n_] := FourierTrigSeries[f[t0], t0, n] /. t0 -> t
s[0, 3]
    Out =   -(31/9) + Pi^2 / 3

Apparently it can be done without the Module thing...

Thank you anyway!


问:
Remove & sort "using" statements in Visual Studio 2008?
Is there a way to automate the "Removal & Sorting" of "using" statements in Visual Studio 2008?</p>

答:
See the (free) "Power Commands" extensions, that has a "remove&sort usings" at the project level.
Plus a "remove and sort on save" option.

See: http://visualstudiogallery.msdn.microsoft.com/en-us/e5f41ad9-4edc-4912-bca3-91147db95b99


问:
Why can't I concatenate and print the value returned by a function?
I have a Perl program that calls a function, in this case ref, and checks the result. Specifically, I am testing that a variable is a hash reference. In that case, ref will return 'HASH'. I tested it and it worked.

Then I decided to log it, adding a print that displays the result of the same call, but it didn't work correctly. Here is a reduced version:

```<code>use strict;
use warnings;

my $book_ref = {};
$book_ref->{'title'} = 'The Lord of the Rings';

if (ref $book_ref eq 'HASH') {
    print "ref \$book_ref is a " . ref $book_ref . "\n";
}

print "Program is over\n";
</code>```

To my surprise, this was the output:

ref $book_ref is a Program is over
```

And despite using strict and warnings there were neither errors nor warnings.

The call to ref is exactly the same (it's a copy and paste), but while it works correctly inside the if condition, print doesn't display anything, and actually seems to be interrupted, as the newline character is clearly skipped. Why does the behaviour change?

答:
The reason is that the function ref is called without parentheses, and this causes the line to be parsed incorrectly.

When ref is called inside the if, the condition is clearly delimited by parentheses, which means that ref knows perfectly well what its argument is: $book_ref. There's no ambiguity.

Instead, when printing the result, the lack of parentheses means that Perl will parse the line in a way that was not intended:

First it will concatenate $book_ref and "\n". In scalar context, $book_ref evaluates to a string like HASH(0x1cbef70), therefore the result is the string "HASH(0x1cbef70)\n"

Then, ref will be called on the string "HASH(0x1cbef70)\n", producing as output an empty string: ''.

At this point, print prints the empty string, that is, nothing, and stops there. The newline character \n is skipped because it has already been consumed by ref, so print doesn't even see it. And there are no errors.

All of this descends from Perl's operator precedence: from the table,

```<code>(...)

 8.    left         + - .
 9.    left         << >>
10.    nonassoc     named unary operators
11.    nonassoc     < > <= >= lt gt le ge
12.    nonassoc     == != <=> eq ne cmp ~~

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

where the "function call" is actually a "named unary operator" (the unary operator being ref). So the . operator at line 8 has higher precedence than the function call at line 10, which is why the result of print is not the expected one. On the other hand, the function call has higher precedence than eq (at line 12), which is why inside the if everything works as expected.

The solution to precedence problems is to use .

A possibility is to use parentheses to emphasize the function call:

```<code>print "ref \$book_ref is a " . ref($book_ref) . "\n";
</code>```

Another one, which I like less but nevertheless works, is to use parentheses to isolate the string that must be concatenated, by putting the opening bracket just before ref:

```<code>print "ref \$book_ref is a " . (ref $book_ref) . "\n";
</code>```

Another possible approach, suggested by zdim in a comment, is to use commas:

```<code>print "ref \$book_ref is a ", ref $book_ref, "\n";
</code>```

When I first wrote the if I decided to avoid the parentheses to make the code more readable. Then I copied it and didn't notice the problem. I ended up wasting 2 hours to find the bug.

The best solution seems to be the first one, because if you copy it to another place (like another print) you are guaranteed to also copy the parentheses that prevent the problem. With the second one I probably wouldn't realize how important the parentheses are and wouldn't copy them. And the third one works only if you remember that you have to always use commas and not dots, which is not obvious and therefore error prone. So, although they work, I consider them less safe.

Other comments have also suggested to use printf, which requires dealing with format specifiers, or expression interpolation, like print "ref \$book_ref is a ${\ ref $book_ref }\n";, which I find harder to read.

Bottom line: always use the parentheses.

Body:
I have a Perl program that calls a function, in this case ref, and checks the result. Specifically, I am testing that a variable is a hash reference. In that case, ref will return 'HASH'. I tested it and it worked.

Then I decided to log it, adding a print that displays the result of the same call, but it didn't work correctly. Here is a reduced version:

use strict;
use warnings;

my $book_ref = {};
$book_ref->{'title'} = 'The Lord of the Rings';

if (ref $book_ref eq 'HASH') {
    print "ref \$book_ref is a " . ref $book_ref . "\n";
}

print "Program is over\n";

To my surprise, this was the output:

ref $book_ref is a Program is over

And despite using strict and warnings there were neither errors nor warnings.

The call to ref is exactly the same (it's a copy and paste), but while it works correctly inside the if condition, print doesn't display anything, and actually seems to be interrupted, as the newline character is clearly skipped. Why does the behaviour change?

Body:
The reason is that the function ref is called without parentheses, and this causes the line to be parsed incorrectly.

When ref is called inside the if, the condition is clearly delimited by parentheses, which means that ref knows perfectly well what its argument is: $book_ref. There's no ambiguity.

Instead, when printing the result, the lack of parentheses means that Perl will parse the line in a way that was not intended:

First it will concatenate $book_ref and "\n". In scalar context, $book_ref evaluates to a string like HASH(0x1cbef70), therefore the result is the string "HASH(0x1cbef70)\n"

Then, ref will be called on the string "HASH(0x1cbef70)\n", producing as output an empty string: ''.

At this point, print prints the empty string, that is, nothing, and stops there. The newline character \n is skipped because it has already been consumed by ref, so print doesn't even see it. And there are no errors.

All of this descends from Perl's operator precedence: from the table,

(...)

 8.    left         + - .
 9.    left         << >>
10.    nonassoc     named unary operators
11.    nonassoc     < > <= >= lt gt le ge
12.    nonassoc     == != <=> eq ne cmp ~~

(...)

where the "function call" is actually a "named unary operator" (the unary operator being ref). So the . operator at line 8 has higher precedence than the function call at line 10, which is why the result of print is not the expected one. On the other hand, the function call has higher precedence than eq (at line 12), which is why inside the if everything works as expected.

The solution to precedence problems is to use .

A possibility is to use parentheses to emphasize the function call:

print "ref \$book_ref is a " . ref($book_ref) . "\n";

Another one, which I like less but nevertheless works, is to use parentheses to isolate the string that must be concatenated, by putting the opening bracket just before ref:

print "ref \$book_ref is a " . (ref $book_ref) . "\n";

Another possible approach, suggested by zdim in a comment, is to use commas:

print "ref \$book_ref is a ", ref $book_ref, "\n";

When I first wrote the if I decided to avoid the parentheses to make the code more readable. Then I copied it and didn't notice the problem. I ended up wasting 2 hours to find the bug.

The best solution seems to be the first one, because if you copy it to another place (like another print) you are guaranteed to also copy the parentheses that prevent the problem. With the second one I probably wouldn't realize how important the parentheses are and wouldn't copy them. And the third one works only if you remember that you have to always use commas and not dots, which is not obvious and therefore error prone. So, although they work, I consider them less safe.

Other comments have also suggested to use printf, which requires dealing with format specifiers, or expression interpolation, like print "ref \$book_ref is a ${\ ref $book_ref }\n";, which I find harder to read.

Bottom line: always use the parentheses.


问:
Why validation is not working?
corporate.html

```<code>          <form #f="ngForm" name="corporateProfileForm" ng-submit="corporateFrmSave(objDS, objDSCurrency)" novalidate="">
             <div class="row  form-group">
               <div class="col-md-12" >
                  <input type="text" *ngIf="formData"  [(ngModel)]="formData.Corporate_Id"  id="corpid" title="Corporate ID" tab-index="1" name="corpid" maxlength="20"  #corpid="ngModel"  required/>
                 <label for="corp"><b>Corporate ID</b></label>
                 <div *ngIf="corpid.invalid && (corpid.dirty || corpid.touched)"  class="alert alert-danger">
                  <div *ngIf="corpid.errors.required">
                       Name is required.
                   </div>
                   <div *ngIf="ncorpidame.errors.minlength">
                       Name must be at least 4 characters long.
                   </div>
                   <div *ngIf="corpid.errors.forbiddenName">
                       Name cannot be Bob.
                   </div>

                  </div>
                   </div>
                </div>
           </form>
</code>```

Iam getting error message as

ERROR TypeError: Cannot read property 'invalid' of undefined

答:
The issue is with the *ngIf, so when that condition is checked, Angular renders the rest of the template, and while the small fraction of time while *ngIf is being evaluated, your template reference variable corpid does not exist, so it will throw an error when trying to check the validation intially.

Wrap the input field with the validation div's inside the *ngIf instead of applying it only on the input field.

  <input [(ngModel)]="formData.Corporate_Id" id="corpid" ... >

```

DEMO

Title: Why validation is not working?

Body:
corporate.html

          <form #f="ngForm" name="corporateProfileForm" ng-submit="corporateFrmSave(objDS, objDSCurrency)" novalidate="">

                  <input type="text" *ngIf="formData"  [(ngModel)]="formData.Corporate_Id"  id="corpid" title="Corporate ID" tab-index="1" name="corpid" maxlength="20"  #corpid="ngModel"  required/>
                 Corporate ID

                       Name is required.

                       Name must be at least 4 characters long.

                       Name cannot be Bob.

           </form>

Iam getting error message as

ERROR TypeError: Cannot read property 'invalid' of undefined

Body:
The issue is with the *ngIf, so when that condition is checked, Angular renders the rest of the template, and while the small fraction of time while *ngIf is being evaluated, your template reference variable corpid does not exist, so it will throw an error when trying to check the validation intially.

Wrap the input field with the validation div's inside the *ngIf instead of applying it only on the input field.

<div class="row  form-group" *ngIf="formData">
  <input [(ngModel)]="formData.Corporate_Id" id="corpid" ... >
  <!-- more code here... -->
</div>

DEMO


问:
Ramda: replace NULL values in json array
We have a json array that has the form:

```<code>[
{id: 123, name: 'abc', symbol: 'xyz'},
{id: 456, name: 'def', symbol: null},
...
]
</code>```

We are looking for a Ramda transformation that will replace all instances where the 'symbol' property is NULL, with a simple '' (empty string). Any ideas about how this can be done without getting into a forEach or for...next loop?

答:
const data = [
  {id: 123, name: 'abc', symbol: 'xyz'},
  {id: 456, name: 'def', symbol: null},
  // ...
];

const newData = R.map(R.over(R.lensProp('symbol'), R.defaultTo('')), data);

console.log(newData);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script></code>```

Body:
We have a json array that has the form:

[
{id: 123, name: 'abc', symbol: 'xyz'},
{id: 456, name: 'def', symbol: null},
...
]

We are looking for a Ramda transformation that will replace all instances where the 'symbol' property is NULL, with a simple '' (empty string). Any ideas about how this can be done without getting into a forEach or for...next loop?

Body:
const data = [
  {id: 123, name: 'abc', symbol: 'xyz'},
  {id: 456, name: 'def', symbol: null},
  // ...
];

const newData = R.map(R.over(R.lensProp('symbol'), R.defaultTo('')), data);

console.log(newData);

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>


问:
In LLVM, how to insert/declare a function with variable number of arguments?
I am trying to extract called functions to another module. I am successful if the function has a defined number of arguments.

```<code>    // Create the arguments vector from the my argument list
    SmallVector<Type *, sizeof(MyArgs)> ArgTys;
    for (Value *V : MyArgs)
      ArgTys.push_back(V->getType());

    // Just get a void return type
    Type *RetTy = Type::getVoidTy(TempContext);

    // Create a new function with MyArgs as arguments
    Constant *C = TempM->getOrInsertFunction(
        "TempF", FunctionType::get(RetTy, ArgTys, false));
</code>```

But if the function has a variable number of arguments, getOrInsertFunction only adds the arguments that I was able to capture with MyArgs in ArgTys.

How do I verify if source function has a variable number of arguments?

How do I use getOrInserFunction to declare a function with variable number of arguments?

答:
According to the documentation:

You can declare a variable argument function by

FunctionType::get(RetTy, ArgTys, true);

(So, in your case, change that false argument for the "TempF" function.)

You can query if a function is using a variable argument list with the method

bool isVarArg() const

Body:
I am trying to extract called functions to another module. I am successful if the function has a defined number of arguments.

    // Create the arguments vector from the my argument list
    SmallVector<Type *, sizeof(MyArgs)> ArgTys;
    for (Value *V : MyArgs)
      ArgTys.push_back(V->getType());

    // Just get a void return type
    Type *RetTy = Type::getVoidTy(TempContext);

    // Create a new function with MyArgs as arguments
    Constant *C = TempM->getOrInsertFunction(
        "TempF", FunctionType::get(RetTy, ArgTys, false));

But if the function has a variable number of arguments, getOrInsertFunction only adds the arguments that I was able to capture with MyArgs in ArgTys.

How do I verify if source function has a variable number of arguments?

How do I use getOrInserFunction to declare a function with variable number of arguments?


问:
Shell Bash - Split Multilne String into Array
I am trying to get an Array that contains each string line as an element...

```<code>stringy=$(ls -l | awk '{print$3,$6,$7,$8,$9}'| grep "$USER")

declare -a myarray=()

IFS="\n" read myarray <<< "$stringy"

echo "${myarray[0]}"
echo "${myarray[1]}"
echo "${myarray[2]}"

for line in "${myarray[@]}"; do
    echo "$line"
done
</code>```

The String looks something like this:

```<code>brunor Nov 17 17:38 22735
brunor Nov 17 15:38 5391
brunor Nov 17 15:38 5405
brunor Nov 17 15:38 5444
</code>```

(...)

the code outputs just the first element (0) even for the loop:

```<code>>brunor Nov 17 17:38 22735
>
>
>brunor Nov 17 17:38 22735
</code>```

答:
The primary issue is that you're reading myarray as a regular variable, not as an array. Use readarray instead:

```<code>readarray -t myarray <<< "$stringy"
</code>```

Other issues include:

IFS is being set to the letter "n" and a backslash, not a linefeed

read defaults to reading a single line regardless of IFS

echo is a bad way to check the contents of variables because it's ambiguous (declare -p myarray would have immediately shown the problem)

Body:
I am trying to get an Array that contains each string line as an element...

stringy=$(ls -l | awk '{print$3,$6,$7,$8,$9}'| grep "$USER")

declare -a myarray=()

IFS="\n" read myarray <<< "$stringy"

echo "${myarray[0]}"
echo "${myarray[1]}"
echo "${myarray[2]}"

for line in "${myarray[@]}"; do
    echo "$line"
done

The String looks something like this:

brunor Nov 17 17:38 22735
brunor Nov 17 15:38 5391
brunor Nov 17 15:38 5405
brunor Nov 17 15:38 5444

(...)

the code outputs just the first element (0) even for the loop:

>brunor Nov 17 17:38 22735
>
>
>brunor Nov 17 17:38 22735

Body:
The primary issue is that you're reading myarray as a regular variable, not as an array. Use readarray instead:

readarray -t myarray <<< "$stringy"

Other issues include:

IFS is being set to the letter "n" and a backslash, not a linefeed

read defaults to reading a single line regardless of IFS

echo is a bad way to check the contents of variables because it's ambiguous (declare -p myarray would have immediately shown the problem)


问:
Clip text overrun from beginning Javafx
Similar to OverrunStyle.LEADING_ELLIPSIS I would like to shorten my word from the words start, but without the ellipses, similar to ovverun style clip. Is this possible?

答:
If you are looking for something for use outside of the fx label etc, StringUtils might be able to help

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#abbreviate-java.lang.String-int-

```<code> StringUtils.abbreviate(null, *, *)                = null
 StringUtils.abbreviate("", 0, 4)                  = ""
 StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
 StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
 StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
 StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
 StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
</code>```

Title: Clip text overrun from beginning Javafx

Body:
If you are looking for something for use outside of the fx label etc, StringUtils might be able to help

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#abbreviate-java.lang.String-int-

 StringUtils.abbreviate(null, *, *)                = null
 StringUtils.abbreviate("", 0, 4)                  = ""
 StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
 StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
 StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
 StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
 StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"


问:
In the iOS SDK, how can I include a button in a UITextField like Mobile Safari does?
How can I display a button and/or activity indicator inside of a UITextField on the iPhone? I'm trying to reproduce Mobile Safari's location text field which contains either a reload button or a cancel (stop loading) button which is right-justified inside of the text field.

Similarly, when you click inside of the text field (not on the cancel/reload buttons) to edit the URL, a clear icon (x inside of a circle) is shown inside of the text field which will erase the contents of the text field.

How can I create this in my own apps? I cannot seem to do it via Interface Builder so I suspect it's being done in code.

答:
There is a built in option that worked for me...check here:

Adding the "Clear" Button to an iPhone UITextField


问:
use init to save multiple entries to a struct (swift4)
My code below uses init to save 1 entry to the struct. The problem is that it can only save 1 entry. I need to somehow make this into a array. So I am trying to use a button to submit a string to a struct where the struct can take multiple entires right now it can only take 1. </p>

```<code>    import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
    @IBOutlet var label: UILabel!

    @IBAction func save(_ sender: Any) {

  let judo = Person.init(name: a.text ?? "", phone: Int(c.text ?? "") ?? 0)
    }

    struct Person :  CustomStringConvertible  {
        var name: String
        var phone: Int
        static var myStruct = [String]();
        var description: String {
            return   "\(name),\(phone)"
        }}}
</code>```

答:
I understood that you want persons to be added to array on press of button

Here is the solution

```<code>var persons:[Person] = [Person]()

    @IBAction func save(_ sender: Any) {
        let judo = Person.init(name: a.text ?? "", phone: Int(c.text ?? "") ?? 0)
        self.persons.append(judo)
    }
</code>```

Hope you are looking for this

Body:
My code below uses init to save 1 entry to the struct. The problem is that it can only save 1 entry. I need to somehow make this into a array. So I am trying to use a button to submit a string to a struct where the struct can take multiple entires right now it can only take 1.

    import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
    @IBOutlet var label: UILabel!

    @IBAction func save(_ sender: Any) {

  let judo = Person.init(name: a.text ?? "", phone: Int(c.text ?? "") ?? 0)
    }

    struct Person :  CustomStringConvertible  {
        var name: String
        var phone: Int
        static var myStruct = [String]();
        var description: String {
            return   "\(name),\(phone)"
        }}}

Body:
I understood that you want persons to be added to array on press of button

Here is the solution

var persons:[Person] = [Person]()

    @IBAction func save(_ sender: Any) {
        let judo = Person.init(name: a.text ?? "", phone: Int(c.text ?? "") ?? 0)
        self.persons.append(judo)
    }

Hope you are looking for this