问:
Keep uppercase after / in a string
I'm trying to title the following string:

"Men's L/S long sleeve"

I'm using string.capwords right now but it's not working as expected.

For example:

```<code>x = "Men's L/s Long Sleeve"
y = string.capwords(x)
print(y)
</code>```

outputs:

Men's L/s Long Sleeve

but I want:

Men's L/S Long Sleeve (uppercased S after the /)

Is there an easy way to go about doing this?

答:
It sounds like the / might not be a reliable indicator that a capital letter is needed. In case the more reliable indicator is actually that the letter was capitalised originally, you could try iterating through each string and only extracting the letters got promoted to upper:

```<code>import string
x = "Men's L/S long sleeve"
y = string.capwords(x)
z = ''
for i,l in enumerate(x):
    if(l.isupper()):
        z += l
    else:
        z += y[i]
</code>```

So on strings like:

```<code>"brand XXX"
"shirt S/M/L"
"Upper/lower"
</code>```

You'll get:

```<code>"Brand XXX"
"Shirt S/M/L"
"Upper/lower"
</code>```

Which I think it probably more desirable than using the / as an indicator.

Title: Keep uppercase after / in a string

Body:
I'm trying to title the following string:

"Men's L/S long sleeve"

I'm using string.capwords right now but it's not working as expected.

For example:

x = "Men's L/s Long Sleeve"
y = string.capwords(x)
print(y)

outputs:

Men's L/s Long Sleeve

but I want:

Men's L/S Long Sleeve (uppercased S after the /)

Is there an easy way to go about doing this?

Body:
It sounds like the / might not be a reliable indicator that a capital letter is needed. In case the more reliable indicator is actually that the letter was capitalised originally, you could try iterating through each string and only extracting the letters got promoted to upper:

import string
x = "Men's L/S long sleeve"
y = string.capwords(x)
z = ''
for i,l in enumerate(x):
    if(l.isupper()):
        z += l
    else:
        z += y[i]

So on strings like:

"brand XXX"
"shirt S/M/L"
"Upper/lower"

You'll get:

"Brand XXX"
"Shirt S/M/L"
"Upper/lower"

Which I think it probably more desirable than using the / as an indicator.


来源: stackexchange

问:
jQuery get json file from directory
I want to create json from folder.

For instance if there is a directory named test with structure as this image.

From here I want to create json file.

```<code>{
name:test,
children:[{
name:test1,
children:[{
...
}
,{name:test2.html},
{name:test3.txt}]}
</code>```

How can I do this without using nodejs or server side language.
Just using jquery?

Thanks.

答:
If I understood you correctly, you're basically trying to read folder structure entirely through JavaScript? If that is the case, you won't do without NodeJS or a backend API to provide you this information. JavaScript is not able to execute such kind of IO operations on its own. You can fetch specific local files but not obtain directory hierarchy in any "normal" way, which is the thing you're trying to do.

Check out this related thread for more information:
Javascript read files in folder

ContentLicense: CC BY-SA 4.0

Title: jQuery get json file from directory

Body:
I want to create json from folder.

For instance if there is a directory named test with structure as this image.

From here I want to create json file.

{
name:test,
children:[{
name:test1,
children:[{
...
}
,{name:test2.html},
{name:test3.txt}]}

How can I do this without using nodejs or server side language.
Just using jquery?

Thanks.


问:
How to get file content in java?
to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

```<code>Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();
}
</code>```

Does the java api provide a way to get the content with one line of code like:

```<code>String content = FileUtils.readFileToString(new File("file.txt"))
</code>```

答:
Not the built-in API - but Guava does, amongst its other treasures. (It's a fabulous library.)

```<code>String content = Files.toString(new File("file.txt"), Charsets.UTF_8);
</code>```

There are similar methods for reading any Readable, or loading the entire contents of a binary file as a byte array, or reading a file into a list of strings, etc.

Note that this method is now deprecated. The new equivalent is:

```<code>String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get file content in java?

Body:
to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();
}

Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt"))

Body:
Not the built-in API - but Guava does, amongst its other treasures. (It's a fabulous library.)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

There are similar methods for reading any Readable, or loading the entire contents of a binary file as a byte array, or reading a file into a list of strings, etc.

Note that this method is now deprecated. The new equivalent is:

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();


问:
How to automatically add a worksheet from a template when a cell is filled out on a master sheet?
I have an excel workbook with two worksheets "Master" and "Template"
I want to copy "template" once a cell, from range A2:A20, in worksheet "Master" is filled out and name a new worksheet with A2:20 value.
I would like to copy value from Master sheet of two cells, into newly created worksheet (from master cells A2:B2 to new sheet (with a name A2) to cells D1:D2).
I want to do that for each cells A2:A20 that are filled out, so that it would not create a new worksheet for cells from A2:A20 that are empty.

So if I would have A2, A4, and A5 filled out I would get 3 new worksheet, like template worksheet, with names from A2, A4 and A5. In first new sheet A2:B2 from master, would be copied to D1:D2. In second new sheet A4:B4, would be copied to D1:D2 and on the third new worksheet A5:B5 would be copied to D1:D2

I would like to have this done, once excel is open, and if once done, not to repeat it

is this possible?

much appreciate any help

```<code>Sub CreateAndNameWorksheets()

    Dim c As Range

    Application.ScreenUpdating = False

    For Each c In Sheets("Master").Range("A2:A20")

        Sheets("Template").Copy After:=Sheets(Sheets.Count)

        With c

            ActiveSheet.Name = .Value

           .Parent.Hyperlinks.Add Anchor:=c, Address:="", SubAddress:= _
                "'" & .Text & "'!A1", TextToDisplay:=.Text

        End With

    Next c

    Application.ScreenUpdating = True

End Sub
</code>```

答:
Place this code in the Workbook module of the Excel file.

```<code>Option Explicit

Private Sub Workbook_Open()

    With Worksheets("Master")

        'check if sheet creation process has happened already
        If .Cells(1, .Columns.Count).Value = "" Then

            Dim c As Range

            Application.ScreenUpdating = False

            For Each c In .Range("A2:A20")

                Worksheets("Template").Copy After:=Sheets(Sheets.Count)

                With c

                    ActiveSheet.Name = .Value

                    .Parent.Hyperlinks.Add Anchor:=c, Address:="", SubAddress:= _
                         "'" & .Text & "'!A1", TextToDisplay:=.Text

                End With

            Next c

            .Cells(1, .Columns.Count).Value = "created" 'mark cell as created so it skips next time and each time after

        End If

    End With

End Sub
</code>```

ThisWorkbook class module:

Body:
I have an excel workbook with two worksheets "Master" and "Template"
I want to copy "template" once a cell, from range A2:A20, in worksheet "Master" is filled out and name a new worksheet with A2:20 value.
I would like to copy value from Master sheet of two cells, into newly created worksheet (from master cells A2:B2 to new sheet (with a name A2) to cells D1:D2).
I want to do that for each cells A2:A20 that are filled out, so that it would not create a new worksheet for cells from A2:A20 that are empty.

So if I would have A2, A4, and A5 filled out I would get 3 new worksheet, like template worksheet, with names from A2, A4 and A5. In first new sheet A2:B2 from master, would be copied to D1:D2. In second new sheet A4:B4, would be copied to D1:D2 and on the third new worksheet A5:B5 would be copied to D1:D2

I would like to have this done, once excel is open, and if once done, not to repeat it

is this possible?

much appreciate any help

Sub CreateAndNameWorksheets()

    Dim c As Range

    Application.ScreenUpdating = False

    For Each c In Sheets("Master").Range("A2:A20")

        Sheets("Template").Copy After:=Sheets(Sheets.Count)

        With c

            ActiveSheet.Name = .Value

           .Parent.Hyperlinks.Add Anchor:=c, Address:="", SubAddress:= _
                "'" & .Text & "'!A1", TextToDisplay:=.Text

        End With

    Next c

    Application.ScreenUpdating = True

End Sub

Body:
Place this code in the Workbook module of the Excel file.

Option Explicit

Private Sub Workbook_Open()

    With Worksheets("Master")

        'check if sheet creation process has happened already
        If .Cells(1, .Columns.Count).Value = "" Then

            Dim c As Range

            Application.ScreenUpdating = False

            For Each c In .Range("A2:A20")

                Worksheets("Template").Copy After:=Sheets(Sheets.Count)

                With c

                    ActiveSheet.Name = .Value

                    .Parent.Hyperlinks.Add Anchor:=c, Address:="", SubAddress:= _
                         "'" & .Text & "'!A1", TextToDisplay:=.Text

                End With

            Next c

            .Cells(1, .Columns.Count).Value = "created" 'mark cell as created so it skips next time and each time after

        End If

    End With

End Sub

ThisWorkbook class module:


问:
Create button formatting in android
I am working on a project where I will have many buttons of the same size.

I was wondering if there is a way to create a standard button formatting with a set

height

weight

padding

etc.

I have looked into styles but I am not sure if that is the road I should be taking. I also thought about extending the button class and programmatically setting these values to a standard.

答:
You can create a reusable component in a separate .xml file and use it everywhere since you said the dimensions exactly the same all across the app. Here is a sample:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners android:radius="4dp" />
<!--customize and animate stuff-->
    <gradient
        android:angle="270"
        android:endColor="#88b823"
        android:startColor="#b0dc54" />

</shape>
</code>```

Title: Create button formatting in android

Body:
You can create a reusable component in a separate .xml file and use it everywhere since you said the dimensions exactly the same all across the app. Here is a sample:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners android:radius="4dp" />
<!--customize and animate stuff-->
    <gradient
        android:angle="270"
        android:endColor="#88b823"
        android:startColor="#b0dc54" />

</shape>


答:
I think the question is on how to embed an svg into html markup.

It an be directly inserted inline as per your example or included through other means to point to an external file. You should change your markup to include the svg by other means, see:

Do I use , <object>, or <embed> for SVG files?

Title: Understanding how to change a SVG

Body:
I'm trying to understand how SVG works. I was trying to use some theme from Github (link). There was the following code: (in common/head_tag.html)

      <svg width="48px" height="45px" viewBox="0 0 48 45" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

      <title>Page 1 Copy 4</title>
      <desc>Created with Sketch.</desc>
      <defs>
          <polygon id="path-1" points="0 0.00434322457 42.9739472 0.00434322457 42.9739472 24.437827 0 24.437827"></polygon>
      </defs>
      <g id="Desktop" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
          <g id="Community-Landing-V2-Nav" transform="translate(-1197.000000, -562.000000)">
              <g id="Popular-Secion" transform="translate(960.000000, 417.000000)">
                  <g id="Group-3" transform="translate(189.000000, 110.000000)">
                      <g id="Page-1-Copy-4" transform="translate(48.000000, 35.000000)">
                          <path d="M40.4114464,0 L37.9103214,3.0488482 L40.8416071,3.0488482 L40.4114464,0 Z M26,7.90245367 L28.0533571,12 L43,12 L43,7.90245367 L26,7.90245367 Z" id="Fill-1" fill="#0073B9"></path>
                          <g id="Group-11" transform="translate(0.000000, 1.000000)">
                              <path d="M16.7680604,21.8779604 L15.2100226,22.300002 C14.8882113,22.387166 14.5564377,22.1990595 14.4685887,21.8800571 C14.3807396,21.5607552 14.5703245,21.2312692 14.8921358,21.1441052 L16.4498717,20.7220636 C16.771683,20.6348996 17.1034566,20.8230061 17.1913057,21.1420085 C17.2791547,21.4610108 17.0895698,21.7907964 16.7680604,21.8779604 M20.3502491,20.8334898 L18.5310792,21.3265206 C18.2092679,21.4136847 17.8771925,21.2258776 17.7893434,20.9065757 C17.7014943,20.5875734 17.8910792,20.2577879 18.2128906,20.1706238 L19.6782491,19.8312532 C19.9997585,19.7440892 20.6720604,20.7463257 20.3502491,20.8334898 M38.9739472,18.328198 L31.9550792,18.328198 C31.6214943,18.328198 31.3513057,18.0598167 31.3513057,17.7291326 C31.3513057,17.3984484 31.6214943,17.1300671 31.9550792,17.1300671 L38.9739472,17.1300671 C39.3069283,17.1300671 39.5777208,17.3984484 39.5777208,17.7291326 C39.5777208,18.0598167 39.3069283,18.328198 38.9739472,18.328198" id="Fill-2" fill="#0073B9"></path>
                              <path d="M44.2082113,37.5212369 C43.8830792,38.4746495 43.3665509,39.2977655 42.4313057,39.8264408 C41.4664755,40.3724889 40.4539472,40.432695 39.4233057,40.1646132 C38.600966,39.9510464 37.8661736,39.5397879 37.2403623,38.9479113 C36.744966,38.4785435 36.3277585,37.966642 36.0147019,37.3603878 C35.7493434,36.8472882 35.5685132,36.3213088 35.4380981,35.7587863 C35.2636075,35.0045629 35.2959094,34.2725049 35.483683,33.5389492 C35.6186264,33.0111726 35.8320604,32.4977735 36.1725887,32.0754323 C36.5445132,31.6138524 36.995834,31.2298514 37.5781736,30.9902252 C38.3111547,30.6885958 39.0544,30.5343364 39.827834,30.6945864 C40.7790792,30.891679 41.6454943,31.2819701 42.3763623,31.9388454 C42.8771925,32.3890431 43.2711547,32.9060366 43.6150038,33.4817385 C43.985117,34.1011722 44.1430038,34.7808119 44.3244377,35.4556592 C44.3890415,35.6964835 44.3561358,35.9633671 44.3679094,36.21797 L44.4005132,36.222463 C44.3404377,36.6567854 44.3473811,37.1132733 44.2082113,37.5212369 M29.0870038,24.4391449 C28.3781736,24.4391449 27.8039849,23.8697332 27.8039849,23.1661308 C27.8039849,22.4631275 28.3781736,21.8931167 29.0870038,21.8931167 C29.7955321,21.8931167 30.3700226,22.4631275 30.3700226,23.1661308 C30.3700226,23.8697332 29.7955321,24.4391449 29.0870038,24.4391449 M23.6675321,36.5348756 C23.3861736,37.49997 22.8850415,38.3865869 22.1031547,39.06413 C21.6928906,39.4202744 21.2267774,39.7201066 20.7618717,40.0076581 C20.1481358,40.3874656 19.4604377,40.5348357 18.7250415,40.5728763 C18.2540981,40.4821179 17.7668528,40.4392847 17.3170415,40.2871221 C16.8240604,40.1205819 16.4044377,39.805773 16.0382491,39.4244678 C15.6593811,39.0302828 15.3780226,38.5806841 15.1890415,38.0804645 C14.7751547,36.9877691 14.8083623,35.8678162 15.1359094,34.7736231 C15.3088906,34.1952254 15.6044377,33.6494768 15.9700226,33.1432665 C16.3706264,32.5888314 16.8319094,32.1020907 17.395834,31.7189884 C17.8667774,31.3990874 18.3824,31.1669496 18.9445132,31.0075981 C19.6373434,30.8114042 20.3205132,30.7946304 21.0042868,30.9566776 C21.5842113,31.0938636 22.0922868,31.3682356 22.547834,31.7773973 C23.1328906,32.3030772 23.4851925,32.9243081 23.7164377,33.6596609 C24.0225509,34.6334418 23.9392302,35.5997344 23.6675321,36.5348756 M46.6785509,31.9990515 C43.1380226,25.6681277 37.3433057,27.5093554 36.5034566,27.8088881 C35.6633057,28.1081213 35.2672302,27.5228344 35.2672302,27.5228344 L18.7751547,0.163514917 C18.7751547,0.163514917 17.3221736,5.61890451 17.1482868,6.31232278 C16.9740981,7.00604058 17.3224755,7.4748093 17.3224755,7.4748093 C17.3224755,7.4748093 25.8513811,21.9326551 26.1837585,22.467321 C26.515834,23.0016874 26.1004377,23.6657514 26.1004377,23.6657514 C26.1004377,23.6657514 24.5052679,26.3783198 23.9730415,27.3661788 C23.4402113,28.3543372 22.5128151,27.9170194 22.5128151,27.9170194 C18.2402113,26.4903451 15.8260226,28.4681597 13.9618717,30.2171313 C10.8605887,33.1255941 9.81938113,40.0328188 15.0115321,42.6357582 C22.0304,46.1552678 25.5461736,40.2517772 26.7232302,38.1859 C27.9002868,36.1200228 28.5668528,29.9211929 28.5668528,29.9211929 L29.5552302,28.1800092 C30.8530415,30.0116518 30.8587774,31.0216762 30.8587774,31.0216762 C31.4610415,36.21797 32.291834,37.5449 32.291834,37.5449 C35.496966,44.6971425 41.1244377,43.9087723 42.9644377,43.2453073 C44.8041358,42.5821419 50.2187774,38.3299752 46.6785509,31.9990515" id="Fill-4" fill="#0073B9"></path>
                              <polygon id="Fill-6" fill="#0073B9" points="10.3000453 11.6996885 1.19363019 14.2193578 2.33204528 17.9242781 13.8248755 14.9028915"></polygon>
                              <g id="Group-10" transform="translate(0.000000, 2.995327)">
                                  <mask id="mask-2" fill="white">
                                      <use xlink:href="#path-1"></use>
                                  </mask>
                                  <g id="Clip-9"></g>
                                  <path d="M33.4346264,16.5960601 L39.9116075,16.5960601 C40.7677585,16.5960601 41.4645132,15.9050381 41.4645132,15.0555633 L41.4645132,3.04250369 C41.4645132,2.19302887 40.7677585,1.50200687 39.9116075,1.50200687 L24.4199849,1.50200687 L33.4346264,16.5960601 Z M39.9116075,18.0937238 L32.5742491,18.0937238 L21.7709283,0.00434322457 L39.9116075,0.00434322457 C41.6000604,0.00434322457 42.9739472,1.36721714 42.9739472,3.04250369 L42.9739472,15.0555633 C42.9739472,16.7308499 41.6000604,18.0937238 39.9116075,18.0937238 Z M7.40141887,7.08529694 L2.20443774,8.56319142 C1.95809811,8.63328208 1.75432453,8.79413116 1.63024906,9.01668397 C1.50617358,9.23893726 1.47719245,9.49563681 1.54813585,9.73945645 L5.18375849,22.2539339 C5.3274566,22.7490615 5.8509283,23.0432026 6.35356981,22.9078138 L20.6050415,19.0854767 L7.40141887,7.08529694 Z M6.11024906,24.437827 C5.03794717,24.437827 4.04262642,23.7348237 3.73319245,22.6681876 L0.0975698113,10.1546088 C-0.0850716981,9.52588961 -0.00990188679,8.86422181 0.30949434,8.29151524 C0.628890566,7.71880866 1.1538717,7.30395583 1.78813585,7.12333759 L7.79779623,5.41450337 L23.6486642,19.8202304 L6.74753208,24.3533588 C6.53530566,24.4105695 6.32126792,24.437827 6.11024906,24.437827 Z" id="Fill-8" fill="#0073B9" mask="url(#mask-2)"></path>
                              </g>
                          </g>
                      </g>
                  </g>
              </g>
          </g>
      </g>
  </svg>

Beat Debt

But I can't understand how to change the svg to some other file (for example I have icon_book in the assets folder). I can't find the relative path to the svg files from the assets folder. What should I change? How does it work?

Body:
I think the question is on how to embed an svg into html markup.

It an be directly inserted inline as per your example or included through other means to point to an external file. You should change your markup to include the svg by other means, see:

Do I use <img>, <object>, or <embed> for SVG files?


问:
Access Denied When Retrieving Static Image From S3 Bucket
I am trying to store and display pictures I have uploaded through React.
Storing them works fine.  I can view them when I manually open my S3 bucket.
When I try to display them, I get a 403 error and if I click on the link returned to me I am shown an xml file like this:

```<code><Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>9E7DA968420809CA</RequestId>
<HostId>
vHBWGUStVMowVcphdjBXqetPIPGeV/xSd2aD70GSKqja2QhQgLirz9hcT5zj6bWogI4u4Z/6918=
</HostId>
</Error>
</code>```

Here is my React code:

```<code>import React , {Component} from 'react';
act-s3';
import S3FileUpload from 'react-s3';
import { uploadFile } from 'react-s3';

const config = {
    bucketName: 'testmypictures', // name of the bucket
    dirName: 'photos', /* optional */
    region: 'us-east-1',
    accessKeyId: 'xxxxxx',
    secretAccessKey: 'xxxxxxx',
}

class App extends Component {
  constructor() {
    super();
    this.state ={
      url: u,
    }
    this.upload = this.upload.bind(this);
  }

  upload(e) {
    const file = e.target.files[0];
    S3FileUpload.uploadFile(file, config)
      .then(data => this.setState({url: data.location}))
      .catch(err => console.log(err));
  }

  render() {
    return ( <div>
      Upload AWS S3
      <input
        type="file"
        onChange={this.upload}
      />
      <img src={this.state.url} />
    </div>);
  }
}

export default App;

</code>```

And attached is the picture of the error.
Thanks.

答:
The error message says Access Denied. This either indicates that the object does not exist or the the requester does not have permission to access the object.

You are not putting any authentication in the  tag, which means the object needs to be publicly accessible to be accessed. (That is, S3 doesn't know who you are, so it is not providing the object. If an object or bucket is publicly accessible, then the object can be accessed.)

There are two ways to do this:

You can make the whole testmypictures bucket (or part of it) public by using a Bucket Policy, or

You can mark the individual objects as public while uploading them by specifying an Access Control List (ACL)

Body:
I am trying to store and display pictures I have uploaded through React.
Storing them works fine.  I can view them when I manually open my S3 bucket.
When I try to display them, I get a 403 error and if I click on the link returned to me I am shown an xml file like this:

<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>9E7DA968420809CA</RequestId>
<HostId>
vHBWGUStVMowVcphdjBXqetPIPGeV/xSd2aD70GSKqja2QhQgLirz9hcT5zj6bWogI4u4Z/6918=
</HostId>
</Error>

Here is my React code:

import React , {Component} from 'react';
act-s3';
import S3FileUpload from 'react-s3';
import { uploadFile } from 'react-s3';

const config = {
    bucketName: 'testmypictures', // name of the bucket
    dirName: 'photos', /* optional */
    region: 'us-east-1',
    accessKeyId: 'xxxxxx',
    secretAccessKey: 'xxxxxxx',
}

class App extends Component {
  constructor() {
    super();
    this.state ={
      url: u,
    }
    this.upload = this.upload.bind(this);
  }

  upload(e) {
    const file = e.target.files[0];
    S3FileUpload.uploadFile(file, config)
      .then(data => this.setState({url: data.location}))
      .catch(err => console.log(err));
  }

  render() {
    return (

      Upload AWS S3
      <input
        type="file"
        onChange={this.upload}
      />

);
  }
}

export default App;

And attached is the picture of the error.
Thanks.

Body:
The error message says Access Denied. This either indicates that the object does not exist or the the requester does not have permission to access the object.

You are not putting any authentication in the <img> tag, which means the object needs to be publicly accessible to be accessed. (That is, S3 doesn't know who you are, so it is not providing the object. If an object or bucket is publicly accessible, then the object can be accessed.)

There are two ways to do this:

You can make the whole testmypictures bucket (or part of it) public by using a Bucket Policy, or

You can mark the individual objects as public while uploading them by specifying an Access Control List (ACL)


答:
the SVG file is not an image, such as PNG or JPG. SVG is a VECTOR image file.
SVG is built using XML Markup, and browsers print them out by plotting each point and line. (In other extensions, the browser only prints the entire file).
This is amazing because you have more flexibility and scalability. You can change the size of your svg image, it will not lose quality!

if u has other SVG file (XML markup), just copy and paste in this file.
Remove actual SVG Markup ( .... ) and paste the new.

If you havent, u need to create!

Title: Understanding how to change a SVG


问:
Difference between find and filter
I have recently jumped into the world of jQuery. I saw the methods find() and filter() but can not figure out the difference between the two.

What exactly is the difference between the two?

答: .find() will look and stop after the first match, whereas, .filter() will continue searching through the entire array</p>

Title: Difference between find and filter


答:
There are several ways to add svg inside html, the simple ones are:

Embedding (like in your example): open your svg file, copy <svg ...>...</svg> and replace <svg ...>...</svg> from example with new <svg ...>...</svg> copied from your file.

Add image as an  tag: replace <svg ...>...</svg> with  (implying assets folder is in the root folder of the server / project).

More info with examples.

Title: Understanding how to change a SVG

Body:
There are several ways to add svg inside html, the simple ones are:

Embedding (like in your example): open your svg file, copy <svg ...>...</svg> and replace <svg ...>...</svg> from example with new <svg ...>...</svg> copied from your file.

Add image as an <img> tag: replace <svg ...>...</svg> with <img src="/assets/icon_book.svg"> (implying assets folder is in the root folder of the server / project).

More info with examples.


问:
Can't send changed data from *ngFor generated form with inputs of object type
I have a problem with a form. I have a JSON object which includes some data and in HTML form I use ngFor to set every input tag in this form to have as value one of every value in this JSON.

The problem is that I won't after this when one of this inputs data change and the send button is clicked (its not necessary to have changes in the inputs values) all values to be stored back in the object and send to a method to console.log them.

The form template is:

```<code>    <form class="example-form"  style="margin-left: 500px;">
      <mat-form-field class="example-full-width" *ngFor=" let item of test | keyvalue">
        <input matInput placeholder="{{item.key}}" value="{{item.value}}" name="" >

      </mat-form-field>

      <button type="submit" (click)="send()">Send</button>

    </form>
</code>```

```<code>    async ngOnInit() {

        this.test= await this.authService.getMultilingual('au');
    }
</code>```

答:
Sounds like a perfect use case for a Reactive Form. Just create a Reactive Form around the Data Model.

Let's say you have some data model like this:

```<code>export interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}
</code>```

which is for the data that you're getting from JSONPlaceholder for eg.

You can generate a Reactive Form around it:

```<code>private generateTodoListForm(todo: Todo) {
  return this.fb.group({
    userId: [todo.userId],
    id: [todo.id],
    title: [todo.title],
    completed: [todo.completed]
  });
}
</code>```

And then use it in your template:

```<code><div *ngIf="(todoForm$ | async) as todoForm">
  <form [formGroup]="todoForm" (submit)="onSubmit(todoForm.value)">
    <label for="userId">User Id</label>
    <input name="userId" type="text" formControlName="userId">
    <br>
    <label for="id">Id</label>
    <input name="id" type="text" formControlName="id">
    <br>
    <label for="title">Title</label>
    <input name="title" type="text" formControlName="title">
    <br>
    <label for="completed">Completed</label>
    <input name="completed" type="checkbox" formControlName="completed">
    <br>
    <button type="submit">Submit</button>
  </form>
</div>
</code>```

Here's a Working Sample StackBlitz for your ref.

Body:
I have a problem with a form. I have a JSON object which includes some data and in HTML form I use ngFor to set every input tag in this form to have as value one of every value in this JSON.

The problem is that I won't after this when one of this inputs data change and the send button is clicked (its not necessary to have changes in the inputs values) all values to be stored back in the object and send to a method to console.log them.

The form template is:

    <form class="example-form"  style="margin-left: 500px;">
      <mat-form-field class="example-full-width" *ngFor=" let item of test | keyvalue">
        <input matInput placeholder="{{item.key}}" value="{{item.value}}" name="" >

      </mat-form-field>

      <button type="submit" (click)="send()">Send</button>

    </form>

    async ngOnInit() {

        this.test= await this.authService.getMultilingual('au');
    }

Body:
Sounds like a perfect use case for a Reactive Form. Just create a Reactive Form around the Data Model.

Let's say you have some data model like this:

export interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

which is for the data that you're getting from JSONPlaceholder for eg.

You can generate a Reactive Form around it:

private generateTodoListForm(todo: Todo) {
  return this.fb.group({
    userId: [todo.userId],
    id: [todo.id],
    title: [todo.title],
    completed: [todo.completed]
  });
}

And then use it in your template:

<div *ngIf="(todoForm$ | async) as todoForm">
  <form [formGroup]="todoForm" (submit)="onSubmit(todoForm.value)">
    <label for="userId">User Id</label>
    <input name="userId" type="text" formControlName="userId">
    <br>
    <label for="id">Id</label>
    <input name="id" type="text" formControlName="id">
    <br>
    <label for="title">Title</label>
    <input name="title" type="text" formControlName="title">
    <br>
    <label for="completed">Completed</label>
    <input name="completed" type="checkbox" formControlName="completed">
    <br>
    <button type="submit">Submit</button>
  </form>
</div>

Here's a Working Sample StackBlitz for your ref.


问:
Neo4j return nodes connected by relationships of a given label and property
I am trying to find the nodes connected that are connected by the relationships having a given label and a given attribute.

For example I want to find all nodes connected by a relationship Edge having as myID 123

I started from this query that returns the data on the relationships.

```<code>MATCH ()-[r:Edge{myID: "123"}]->()RETURN r;
</code>```

Counting these relationships with

```<code>MATCH ()-[r:Edge{myID: "123"}]->()RETURN count(r)
</code>```

I get 45.

I then created the following:

```<code>MATCH (a)-[r:Edge{myID: "123"}]->(b)RETURN a,b,r LIMIT 25
</code>```

However this is not working: it seems to return much more nodes than expected: first of all LIMIT is not limiting and hence the subgraph becomes very big and difficult to analyze but it seems that it is returning even nodes-relationship with a myID property different than 123, for sure more than 45.

How can I do that?

EDIT

Take as example the following graph:

```<code>//create 2 nodes
CREATE (: myNode{NID : 1});
CREATE (: myNode{NID : 1});
//create 2 relationships:
MATCH (n1:myNode{NID:1})
MATCH (n2:myNode{NID:1})
MErGE(n1)-[r:Edge{myID:2}]->(n2);

MATCH (n1:myNode{NID:1})
MATCH (n2:myNode{NID:2})
MErGE(n1)-[r:Edge{myID:2}]->(n2);
</code>```

The problem can be seen trying the following queries that will return both the edges:

```<code>MATCH p=(a)-[r:Edge{myID : 1}]->(b) return p limit 1;

MATCH (a)-[r:Edge{myID : 1}]->(b) return a,r,b limit 1;
</code>```

答:
Neo4J Browser by default tries to expand the nodes that are displayed in the view when nodes are returned.

Can you please try

```<code>MATCH p=(a)-[r:Edge{myID: "123"}]->(b) return p limit 25.
</code>```

Neo4J Browser should not try to expand the nodes now.

Body:
I am trying to find the nodes connected that are connected by the relationships having a given label and a given attribute.

For example I want to find all nodes connected by a relationship Edge having as myID 123

I started from this query that returns the data on the relationships.

MATCH ()-[r:Edge{myID: "123"}]->()RETURN r;

Counting these relationships with

MATCH ()-[r:Edge{myID: "123"}]->()RETURN count(r)

I get 45.

I then created the following:

MATCH (a)-[r:Edge{myID: "123"}]->(b)RETURN a,b,r LIMIT 25

However this is not working: it seems to return much more nodes than expected: first of all LIMIT is not limiting and hence the subgraph becomes very big and difficult to analyze but it seems that it is returning even nodes-relationship with a myID property different than 123, for sure more than 45.

How can I do that?

EDIT

Take as example the following graph:

//create 2 nodes
CREATE (: myNode{NID : 1});
CREATE (: myNode{NID : 1});
//create 2 relationships:
MATCH (n1:myNode{NID:1})
MATCH (n2:myNode{NID:1})
MErGE(n1)-[r:Edge{myID:2}]->(n2);

MATCH (n1:myNode{NID:1})
MATCH (n2:myNode{NID:2})
MErGE(n1)-[r:Edge{myID:2}]->(n2);

The problem can be seen trying the following queries that will return both the edges:

MATCH p=(a)-[r:Edge{myID : 1}]->(b) return p limit 1;

MATCH (a)-[r:Edge{myID : 1}]->(b) return a,r,b limit 1;

Body:
Neo4J Browser by default tries to expand the nodes that are displayed in the view when nodes are returned.

Can you please try

MATCH p=(a)-[r:Edge{myID: "123"}]->(b) return p limit 25.

Neo4J Browser should not try to expand the nodes now.


问:
Pseudo random number generator using the Blum Blum Shub algorithm
We're required to implement Blum Blum Shub Algorithm in a pseudo random number generator. I tried searching for implementations in c# to get an idea but was unsuccessful. Some methods we're required to implement are not clear enough (or maybe I'm not getting exactly what they're asking).

Anyone could provide some help with either the code or maybe an example in a similar fashion? I have a harder time grasping concepts from text.Any help would be greatly accepted!

First, I tried following the logic of the question. With little progress, I began searching on-line for better explanations and possibly finding implementations to better understanding. Finally, I attempted to fill in some of the requested methods with what I thought made sense.

```<code>static long seed = 6367859;
static long p = 3263849;
static long q = 1302498943;
static long m = p*q;

// Generates a random bit i.e. 0 or 1 using the Blum Blum Shub Algorithm and the Least Significant Bit
private byte generateRandomBit(){ }

// Method to generate a single positive 32 bit random number using the Blum Blum Shub Algorithm.
// The generateRandomBit() method is used to generate the random bits that make up the random number
// Not complete!!
public int GenerateNextRandomNumber()
{
    int nextRandomNumber = (int)((p * seed + q) % m);

    seed = nextRandomNumber;

    return nextRandomNumber;
}

// Generates a random number between min and max.
// The GenerateNextRandomNumber() method must be used to generate the initial random number which must then be manipulated (if necessary) to be between min and max
public int GenerateNextRandomNumber(int min, int max){ }

// Uses the GenerateNextRandomNumber Method to generate a sequence of Random Numbers between the minimum and the maximum value using the Blum Blum Shub Algorithm
public int[] GenerateRadmonSequence(int n, int min, int max)
{
    int[] sequence = new int[n];

    for (int i = 0; i < n; i++)
    {
        int randNum = Math.Abs(GenerateNextRandomNumber());

        randNum = min + randNum % (max + 1 +- min);
        sequence[i] = randNum;
    }

    return sequence;
}
</code>```

The result should be to generate a sequence of numbers from min to max.

答:
No, you cannot use longs for this type of RNG: It pretty much requires arbitrary precision math. And what you implemented actually looks like the Linear Congruential Generator algorithm, not the Blum Blum Shub algorithm.

Here is the code to get you going, using .NET Core 2.2 and Win10 x64. Using BigInteger, proper algorithm I believe, and parity to get next random bit. You could use least significant bit for random bit as well.

```<code>using System;
using System.Numerics;

namespace BlumBlumSnub
{
    class Program
    {
        public static readonly BigInteger p = 3263849;
        public static readonly BigInteger q = 1302498943;
        public static readonly BigInteger m = p*q;

        public static BigInteger next(BigInteger prev) {
            return (prev*prev) % m;
        }

        public static int parity(BigInteger n) {
            BigInteger q = n;
            BigInteger count = 0;
            while (q != BigInteger.Zero) {
                count += q & BigInteger.One;
                q >>= 1;
            }
            return ((count & BigInteger.One) != BigInteger.Zero) ? 1 : 0; // even parity
        }

        public static int LSB(BigInteger n) {
            return ((n & BigInteger.One) != BigInteger.Zero) ? 1 : 0;
        }

        static void Main(string[] args)
        {
            BigInteger seed = 6367859;

            BigInteger xprev = seed;
            for(int k = 0; k != 100; ++k) {
                BigInteger xnext = next(xprev);
                int bit = parity(xnext); // extract random bit from generated BBS number using parity,
                // or just int bit = LSB(xnext);
                Console.WriteLine($"Bit = {bit}");
                xprev = xnext;
            }
        }
    }
}
</code>```

Body:
We're required to implement Blum Blum Shub Algorithm in a pseudo random number generator. I tried searching for implementations in c# to get an idea but was unsuccessful. Some methods we're required to implement are not clear enough (or maybe I'm not getting exactly what they're asking).

Anyone could provide some help with either the code or maybe an example in a similar fashion? I have a harder time grasping concepts from text.Any help would be greatly accepted!

First, I tried following the logic of the question. With little progress, I began searching on-line for better explanations and possibly finding implementations to better understanding. Finally, I attempted to fill in some of the requested methods with what I thought made sense.

static long seed = 6367859;
static long p = 3263849;
static long q = 1302498943;
static long m = p*q;

// Generates a random bit i.e. 0 or 1 using the Blum Blum Shub Algorithm and the Least Significant Bit
private byte generateRandomBit(){ }

// Method to generate a single positive 32 bit random number using the Blum Blum Shub Algorithm.
// The generateRandomBit() method is used to generate the random bits that make up the random number
// Not complete!!
public int GenerateNextRandomNumber()
{
    int nextRandomNumber = (int)((p * seed + q) % m);

    seed = nextRandomNumber;

    return nextRandomNumber;
}

// Generates a random number between min and max.
// The GenerateNextRandomNumber() method must be used to generate the initial random number which must then be manipulated (if necessary) to be between min and max
public int GenerateNextRandomNumber(int min, int max){ }

// Uses the GenerateNextRandomNumber Method to generate a sequence of Random Numbers between the minimum and the maximum value using the Blum Blum Shub Algorithm
public int[] GenerateRadmonSequence(int n, int min, int max)
{
    int[] sequence = new int[n];

    for (int i = 0; i < n; i++)
    {
        int randNum = Math.Abs(GenerateNextRandomNumber());

        randNum = min + randNum % (max + 1 +- min);
        sequence[i] = randNum;
    }

    return sequence;
}

The result should be to generate a sequence of numbers from min to max.

Body:
No, you cannot use longs for this type of RNG: It pretty much requires arbitrary precision math. And what you implemented actually looks like the Linear Congruential Generator algorithm, not the Blum Blum Shub algorithm.

Here is the code to get you going, using .NET Core 2.2 and Win10 x64. Using BigInteger, proper algorithm I believe, and parity to get next random bit. You could use least significant bit for random bit as well.

using System;
using System.Numerics;

namespace BlumBlumSnub
{
    class Program
    {
        public static readonly BigInteger p = 3263849;
        public static readonly BigInteger q = 1302498943;
        public static readonly BigInteger m = p*q;

        public static BigInteger next(BigInteger prev) {
            return (prev*prev) % m;
        }

        public static int parity(BigInteger n) {
            BigInteger q = n;
            BigInteger count = 0;
            while (q != BigInteger.Zero) {
                count += q & BigInteger.One;
                q >>= 1;
            }
            return ((count & BigInteger.One) != BigInteger.Zero) ? 1 : 0; // even parity
        }

        public static int LSB(BigInteger n) {
            return ((n & BigInteger.One) != BigInteger.Zero) ? 1 : 0;
        }

        static void Main(string[] args)
        {
            BigInteger seed = 6367859;

            BigInteger xprev = seed;
            for(int k = 0; k != 100; ++k) {
                BigInteger xnext = next(xprev);
                int bit = parity(xnext); // extract random bit from generated BBS number using parity,
                // or just int bit = LSB(xnext);
                Console.WriteLine($"Bit = {bit}");
                xprev = xnext;
            }
        }
    }
}


问:
Program Google Apps Script to throw error when BigQuery "Resources exceeded during query execution"
I am using scripts to run views and use the query results to update tables in BigQuery. I then use these tables in Data Studio for tables/visualizations.

An issue I've noticed is that sometimes my views will suddenly throw an error "Resources exceeded during query execution". My Google Apps script will run successfully, however, but the table will remain unchanged because the view couldn't be executed. As a result, the data in my Data Studio visualizations and tables will be stale. And I will have no way to know this unless I go to edit the view and see that it is throwing the error.

Is there any way to add something to my script so that the script will fail or notify me when Bigquery throws the "Resources exceeded during query execution" error? This way I won't unknowingly have stale data due to the error.

```<code>  var configuration = {
    "query": {
    "useQueryCache": false,
    "destinationTable": {
          "projectId": "abc-123",
          "datasetId": "report_tables",
          "tableId": "dashboard_1"
        },
    "writeDisposition": "WRITE_TRUNCATE",
    "createDisposition": "CREATE_IF_NEEDED",
    "allowLargeResults": true,
    "useLegacySql": false,
    "query": "SELECT * FROM `abc-123.report_tables.dashboard_1_view`"
    }
  };

  var job = {
    "configuration": configuration
  };

  var jobResult = BigQuery.Jobs.insert(job, "abc-123");
  Logger.log(jobResult);
}

</code>```

I'm hoping you can help me add some clause to the above script so that when resources are exceeded in the BigQuery view, this will fail to execute or notify me in some way so I know to go correct the issue in BigQuery.

Thanks for the help!

答:
Your function is succeeding because all jobs/queries on BigQuery are async. The line var jobResult = BigQuery.Jobs.insert(job, "abc-123"); only submits the job/query to the BigQuery service to begin execution. Then your function returns.

So, you need to wait and poll for the status of the job while it's executing and then deal with any errors if it fails with something like this:

```<code>  [..]
  var job = BigQuery.Jobs.insert(job, "abc-123");
  Logger.log(job.status.state);
  var jobId = job.jobReference.jobId;

  // Check on status of the Query Job.
  var sleepTimeMs = 500;
  while (job.status.state !== "DONE") {
    Utilities.sleep(sleepTimeMs);
    job = BigQuery.Jobs.get("abc-123", jobId);
    Logger.log(job.status.state);
  }
  if(job.status.errors != null && job.status.errors.length > 0) {
     Logger.log("FAILED:" + job.status.errors);
  } else {
     Logger.log("SUCCEEDED")
  }
  [..]
</code>```

Sample output (failure):

```<code>[19-06-03 19:54:48:557 AEST] RUNNING
[19-06-03 19:54:49:161 AEST] RUNNING
[19-06-03 19:54:49:789 AEST] RUNNING
[19-06-03 19:54:50:368 AEST] RUNNING
[19-06-03 19:54:51:147 AEST] RUNNING
[19-06-03 19:54:51:783 AEST] RUNNING
[19-06-03 19:54:52:356 AEST] RUNNING
[19-06-03 19:54:52:957 AEST] RUNNING
[19-06-03 19:54:53:564 AEST] RUNNING
[19-06-03 19:54:54:151 AEST] RUNNING
[19-06-03 19:54:54:748 AEST] RUNNING
[19-06-03 19:54:55:338 AEST] RUNNING
[19-06-03 19:54:55:954 AEST] RUNNING
[19-06-03 19:54:56:539 AEST] RUNNING
[19-06-03 19:54:57:107 AEST] RUNNING
[19-06-03 19:54:57:724 AEST] RUNNING
[19-06-03 19:54:58:513 AEST] RUNNING
[19-06-03 19:54:59:524 AEST] RUNNING
[19-06-03 19:55:00:144 AEST] RUNNING
[19-06-03 19:55:00:993 AEST] RUNNING
[19-06-03 19:55:01:613 AEST] RUNNING
[19-06-03 19:55:02:219 AEST] RUNNING
[19-06-03 19:55:02:989 AEST] RUNNING
[19-06-03 19:55:03:557 AEST] RUNNING
[19-06-03 19:55:04:123 AEST] RUNNING
[19-06-03 19:55:04:684 AEST] RUNNING
[19-06-03 19:55:05:408 AEST] RUNNING
[19-06-03 19:55:06:018 AEST] RUNNING
[19-06-03 19:55:06:603 AEST] RUNNING
[19-06-03 19:55:07:215 AEST] RUNNING
[19-06-03 19:55:07:789 AEST] RUNNING
[19-06-03 19:55:08:424 AEST] RUNNING
[19-06-03 19:55:08:985 AEST] RUNNING
[19-06-03 19:55:09:580 AEST] RUNNING
[19-06-03 19:55:10:184 AEST] RUNNING
[19-06-03 19:55:10:802 AEST] RUNNING
[19-06-03 19:55:11:391 AEST] RUNNING
[19-06-03 19:55:11:984 AEST] RUNNING
[19-06-03 19:55:12:564 AEST] RUNNING
[19-06-03 19:55:13:154 AEST] RUNNING
[19-06-03 19:55:13:752 AEST] RUNNING
[19-06-03 19:55:14:372 AEST] RUNNING
[19-06-03 19:55:14:974 AEST] RUNNING
[19-06-03 19:55:15:661 AEST] RUNNING
[19-06-03 19:55:16:227 AEST] RUNNING
[19-06-03 19:55:16:815 AEST] RUNNING
[19-06-03 19:55:17:416 AEST] RUNNING
[19-06-03 19:55:18:002 AEST] DONE
[19-06-03 19:55:18:003 AEST] FAILED:{"reason":"resourcesExceeded","message":"Resources exceeded during query execution: The query could not be executed in the allotted memory. Peak usage: 121% of limit.\nTop memory consumer(s):\n  ORDER BY operations: 99%\n  other/unattributed: 1%\n"}
</code>```

Sample Output (success):

```<code>[19-06-03 19:59:48:206 AEST] RUNNING
[19-06-03 19:59:48:820 AEST] RUNNING
[19-06-03 19:59:49:433 AEST] RUNNING
[19-06-03 19:59:50:015 AEST] DONE
[19-06-03 19:59:50:016 AEST] SUCCEEDED
</code>```

Something to consider is that using Google Apps Script ties all this to your personal Google account i.e. not a service account. That might be ok for you, but in the enterprise it's a bit of a no-no.

Finally, I'd probably move your scripts into Cloud Build. I'd argue that it's much more powerful, maintainable, easier to use and flexible.

Body:
I am using scripts to run views and use the query results to update tables in BigQuery. I then use these tables in Data Studio for tables/visualizations.

An issue I've noticed is that sometimes my views will suddenly throw an error "Resources exceeded during query execution". My Google Apps script will run successfully, however, but the table will remain unchanged because the view couldn't be executed. As a result, the data in my Data Studio visualizations and tables will be stale. And I will have no way to know this unless I go to edit the view and see that it is throwing the error.

Is there any way to add something to my script so that the script will fail or notify me when Bigquery throws the "Resources exceeded during query execution" error? This way I won't unknowingly have stale data due to the error.

  var configuration = {
    "query": {
    "useQueryCache": false,
    "destinationTable": {
          "projectId": "abc-123",
          "datasetId": "report_tables",
          "tableId": "dashboard_1"
        },
    "writeDisposition": "WRITE_TRUNCATE",
    "createDisposition": "CREATE_IF_NEEDED",
    "allowLargeResults": true,
    "useLegacySql": false,
    "query": "SELECT * FROM `abc-123.report_tables.dashboard_1_view`"
    }
  };

  var job = {
    "configuration": configuration
  };

  var jobResult = BigQuery.Jobs.insert(job, "abc-123");
  Logger.log(jobResult);
}

I'm hoping you can help me add some clause to the above script so that when resources are exceeded in the BigQuery view, this will fail to execute or notify me in some way so I know to go correct the issue in BigQuery.

Thanks for the help!

Body:
Your function is succeeding because all jobs/queries on BigQuery are async. The line var jobResult = BigQuery.Jobs.insert(job, "abc-123"); only submits the job/query to the BigQuery service to begin execution. Then your function returns.

So, you need to wait and poll for the status of the job while it's executing and then deal with any errors if it fails with something like this:

  [..]
  var job = BigQuery.Jobs.insert(job, "abc-123");
  Logger.log(job.status.state);
  var jobId = job.jobReference.jobId;

  // Check on status of the Query Job.
  var sleepTimeMs = 500;
  while (job.status.state !== "DONE") {
    Utilities.sleep(sleepTimeMs);
    job = BigQuery.Jobs.get("abc-123", jobId);
    Logger.log(job.status.state);
  }
  if(job.status.errors != null && job.status.errors.length > 0) {
     Logger.log("FAILED:" + job.status.errors);
  } else {
     Logger.log("SUCCEEDED")
  }
  [..]

Sample output (failure):

[19-06-03 19:54:48:557 AEST] RUNNING
[19-06-03 19:54:49:161 AEST] RUNNING
[19-06-03 19:54:49:789 AEST] RUNNING
[19-06-03 19:54:50:368 AEST] RUNNING
[19-06-03 19:54:51:147 AEST] RUNNING
[19-06-03 19:54:51:783 AEST] RUNNING
[19-06-03 19:54:52:356 AEST] RUNNING
[19-06-03 19:54:52:957 AEST] RUNNING
[19-06-03 19:54:53:564 AEST] RUNNING
[19-06-03 19:54:54:151 AEST] RUNNING
[19-06-03 19:54:54:748 AEST] RUNNING
[19-06-03 19:54:55:338 AEST] RUNNING
[19-06-03 19:54:55:954 AEST] RUNNING
[19-06-03 19:54:56:539 AEST] RUNNING
[19-06-03 19:54:57:107 AEST] RUNNING
[19-06-03 19:54:57:724 AEST] RUNNING
[19-06-03 19:54:58:513 AEST] RUNNING
[19-06-03 19:54:59:524 AEST] RUNNING
[19-06-03 19:55:00:144 AEST] RUNNING
[19-06-03 19:55:00:993 AEST] RUNNING
[19-06-03 19:55:01:613 AEST] RUNNING
[19-06-03 19:55:02:219 AEST] RUNNING
[19-06-03 19:55:02:989 AEST] RUNNING
[19-06-03 19:55:03:557 AEST] RUNNING
[19-06-03 19:55:04:123 AEST] RUNNING
[19-06-03 19:55:04:684 AEST] RUNNING
[19-06-03 19:55:05:408 AEST] RUNNING
[19-06-03 19:55:06:018 AEST] RUNNING
[19-06-03 19:55:06:603 AEST] RUNNING
[19-06-03 19:55:07:215 AEST] RUNNING
[19-06-03 19:55:07:789 AEST] RUNNING
[19-06-03 19:55:08:424 AEST] RUNNING
[19-06-03 19:55:08:985 AEST] RUNNING
[19-06-03 19:55:09:580 AEST] RUNNING
[19-06-03 19:55:10:184 AEST] RUNNING
[19-06-03 19:55:10:802 AEST] RUNNING
[19-06-03 19:55:11:391 AEST] RUNNING
[19-06-03 19:55:11:984 AEST] RUNNING
[19-06-03 19:55:12:564 AEST] RUNNING
[19-06-03 19:55:13:154 AEST] RUNNING
[19-06-03 19:55:13:752 AEST] RUNNING
[19-06-03 19:55:14:372 AEST] RUNNING
[19-06-03 19:55:14:974 AEST] RUNNING
[19-06-03 19:55:15:661 AEST] RUNNING
[19-06-03 19:55:16:227 AEST] RUNNING
[19-06-03 19:55:16:815 AEST] RUNNING
[19-06-03 19:55:17:416 AEST] RUNNING
[19-06-03 19:55:18:002 AEST] DONE
[19-06-03 19:55:18:003 AEST] FAILED:{"reason":"resourcesExceeded","message":"Resources exceeded during query execution: The query could not be executed in the allotted memory. Peak usage: 121% of limit.\nTop memory consumer(s):\n  ORDER BY operations: 99%\n  other/unattributed: 1%\n"}

Sample Output (success):

[19-06-03 19:59:48:206 AEST] RUNNING
[19-06-03 19:59:48:820 AEST] RUNNING
[19-06-03 19:59:49:433 AEST] RUNNING
[19-06-03 19:59:50:015 AEST] DONE
[19-06-03 19:59:50:016 AEST] SUCCEEDED

Something to consider is that using Google Apps Script ties all this to your personal Google account i.e. not a service account. That might be ok for you, but in the enterprise it's a bit of a no-no.

Finally, I'd probably move your scripts into Cloud Build. I'd argue that it's much more powerful, maintainable, easier to use and flexible.


问:
Module and classes handling (dynamic linking)
Run into a bit of an issue, and I'm looking for the best solution concept/theory.

I have a system that needs to use objects. Each object that the system uses has a known interface, likely implemented as an abstract class. The interfaces are known at build time, and will not change. The exact implementation to be used will vary and I have no idea ahead of time what module will be providing it. The only guarantee is that they will provide the interface. The class name and module (DLL) come from a config file or may be changed programmatically.

Now, I have all that set up at the moment using a relatively simple system, set up something like so (rewritten pseudo-code, just to show the basics):

```<code>struct ClassID
{
    Module * module;
    int number;
};

class Module
{
    HMODULE module;
    function<void * (int)> * createfunc;

    static Module * Load(String filename);

    IObject * CreateClass(int number)
    {
        return createfunc(number);
    }
};

class ModuleManager
{
    bool LoadModule(String filename);

    IObject * CreateClass(String classname)
    {
        ClassID class = AvailableClasses.find(classname);
        return class.module->CreateObject(class.number);
    }

    vector<Module*> LoadedModules;
    map<String, ClassID> AvailableClasses;
};
</code>```

Modules have a few exported functions to give the number of classes they provide and the names/IDs of those, which are then stored. All classes derive from IObject, which has a virtual destructor, stores the source module and has some methods to get the class' ID, what interface it implements and such.

The only issue with this is each module has to be manually loaded somewhere (listed in the config file, at the moment). I would like to avoid doing this explicitly (outside of the ModuleManager, inside that I'm not really concerned as to how it's implemented).

I would like to have a similar system without having to handle loading the modules, just create an object and (once it's all set up) it magically appears.

I believe this is similar to what COM is intended to do, in some ways. I looked into the COM system briefly, but it appears to be overkill beyond belief. I only need the classes known within my system and don't need all the other features it handles, just implementations of interfaces coming from somewhere.

My other idea is to use the registry and keep a key with all the known/registered classes and their source modules and numbers, so I can just look them up and it will appear that Manager::CreateClass finds and makes the object magically. This seems like a viable solution, but I'm not sure if it's optimal or if I'm reinventing something.

So, after all that, my question is: How to handle this? Is there an existing technology, if not, how best to set it up myself? Are there any gotchas that I should be looking out for?

答:
COM very likely is what you want. It is very broad but you don't need to use all the functionality.  For example, you don't need to require participants to register GUIDs, you can define your own mechanism for creating instances of interfaces. There are a number of templates and other mechanisms to make it easy to create COM interfaces. What's more, since it is a standard, it is easy to document the requirements.

One very important thing to bear in mind is that importing/exporting C++ objects requires all participants to be using the same compiler. If you think that ever could be a problem to you then you should use COM.  If you are happy to accept that restriction then you can carry on as you are.

Body:
Run into a bit of an issue, and I'm looking for the best solution concept/theory.

I have a system that needs to use objects. Each object that the system uses has a known interface, likely implemented as an abstract class. The interfaces are known at build time, and will not change. The exact implementation to be used will vary and I have no idea ahead of time what module will be providing it. The only guarantee is that they will provide the interface. The class name and module (DLL) come from a config file or may be changed programmatically.

Now, I have all that set up at the moment using a relatively simple system, set up something like so (rewritten pseudo-code, just to show the basics):

struct ClassID
{
    Module * module;
    int number;
};

class Module
{
    HMODULE module;
    function<void * (int)> * createfunc;

    static Module * Load(String filename);

    IObject * CreateClass(int number)
    {
        return createfunc(number);
    }
};

class ModuleManager
{
    bool LoadModule(String filename);

    IObject * CreateClass(String classname)
    {
        ClassID class = AvailableClasses.find(classname);
        return class.module->CreateObject(class.number);
    }

    vector<Module*> LoadedModules;
    map<String, ClassID> AvailableClasses;
};

Modules have a few exported functions to give the number of classes they provide and the names/IDs of those, which are then stored. All classes derive from IObject, which has a virtual destructor, stores the source module and has some methods to get the class' ID, what interface it implements and such.

The only issue with this is each module has to be manually loaded somewhere (listed in the config file, at the moment). I would like to avoid doing this explicitly (outside of the ModuleManager, inside that I'm not really concerned as to how it's implemented).

I would like to have a similar system without having to handle loading the modules, just create an object and (once it's all set up) it magically appears.

I believe this is similar to what COM is intended to do, in some ways. I looked into the COM system briefly, but it appears to be overkill beyond belief. I only need the classes known within my system and don't need all the other features it handles, just implementations of interfaces coming from somewhere.

My other idea is to use the registry and keep a key with all the known/registered classes and their source modules and numbers, so I can just look them up and it will appear that Manager::CreateClass finds and makes the object magically. This seems like a viable solution, but I'm not sure if it's optimal or if I'm reinventing something.

So, after all that, my question is: How to handle this? Is there an existing technology, if not, how best to set it up myself? Are there any gotchas that I should be looking out for?


问:
How to fix an issue with running a script in Atom?
I am trying to run a Python script in Atom but it is not working. I see an hourglass appear but no window pane to enter my inputs and run the code. What should I do?

I have already downloaded the Script package and have tried running the script but it does not seem to work yet.

答:
Please try :

1.Open your atom editor

2.Press the combination key ctrl+shift+p to enter the setting Enter or click the file menu to select setting

3.Select install click on the search box

4.Search for atom-python-run or script

5.The former (recommended) uses F5 to start the program, the latter is the combination key ctrl+shift+b

6.After the installation is complete, open the python document and press the corresponding key combination to see if the terminal has been opened.


答:
Everything between and including the <svg> and </svg> is the code for the SVG. In this sample code below, I have change the original SVG to a different one.

In the second sample, changed to using a non embedded version where the source an  is a SVG resource. I believe this is what you are after.

    <svg width="64" height="64" viewBox="-70.5 -70.5 391 391" xmlns="http://www.w3.org/2000/svg">
       <rect x="25" y="25" width="200" height="200" fill="lime" stroke-width="4" stroke="pink" />
      <circle cx="125" cy="125" r="75" fill="orange" />
      <polyline points="50,150 50,200 200,200 200,100" stroke="red" stroke-width="4" fill="none" />
      <line x1="50" y1="50" x2="200" y2="200" stroke="blue" stroke-width="4" />
    </svg>

Beat Debt

And a non-embed version

Beat Debt

```

Title: Understanding how to change a SVG

Body:
Everything between and including the <svg> and </svg> is the code for the SVG. In this sample code below, I have change the original SVG to a different one.

In the second sample, changed to using a non embedded version where the source an <img /> is a SVG resource. I believe this is what you are after.

<div class="popular-item">
<a href="/c/debt" class="popular-link">
  <div class="popular-icon">
    <svg width="64" height="64" viewBox="-70.5 -70.5 391 391" xmlns="http://www.w3.org/2000/svg">
       <rect x="25" y="25" width="200" height="200" fill="lime" stroke-width="4" stroke="pink" />
      <circle cx="125" cy="125" r="75" fill="orange" />
      <polyline points="50,150 50,200 200,200 200,100" stroke="red" stroke-width="4" fill="none" />
      <line x1="50" y1="50" x2="200" y2="200" stroke="blue" stroke-width="4" />
    </svg>
  </div>
  <div class="popular-description">Beat Debt</div>
</a>
</div>
<p>
And a non-embed version
</p>
<div class="popular-item">
<a href="/c/debt" class="popular-link">
  <div class="popular-icon">
    <img src="https://upload.wikimedia.org/wikipedia/commons/b/bd/Test.svg" style="width:64px;height:64px" />
  </div>
  <div class="popular-description">Beat Debt</div>
</a>
</div>


问:
how to setup built-in webserver in PhpStorm
Set up:

1) OS - Win 8.1

2) WAMP

3) PhpStorm 7.1.3

I have been working on Dreamweaver for quite a long time and recently I ditched it because of its limited features. Setting up a local env using Dreamweaver is fairly simple and I had no problem with it. So I installed PhpStorm thinking it would quite easy to run my PHP web app in the same way when I was using DW, but When I try to run my web app in PhpStorm using its built-in webserver I get 502 Bad Gateway error, What I did is simply import the folder (which is in www directory) in PhpStorm and try to run it on browser, but I couldn't get it to work locally. I believe I have to set up Interpreter under settings, but how do I go ahead and what should I include?

When I run my webapp using WAMP the URL looks like

```<code>http://localhost/appname/trunk/public/
</code>```

When I run it using PhpStorm built-in webserver the URL looks like

```<code>http://localhost:63342/appname/trunk/public/
</code>```

Error: 502 bad gateway.

I am quite stuck now.

答:
I recently came across a similar problem when attempting to run on a different localhost on my computer.

One easy work around I found was by editing your run/debug configurations.

Before you do this, save a simple batch file to where ever you'd like on your hard drive and name it 'init.bat'.(eg. mine is 'C:\wamp64\www\myhost\init.bat'). Inside this batch file use this code to open your desired website:

```<code>start "" http://localhost/appname/trunk/public/
</code>```

So head over to the run/debug configurations and then choose the php script you want to run. For example mine was called "index.php". When there, at the bottom of the window there should be a section that says, "Before launch: External tool, Activate tool window".

Click 'Run external tool' and from there add your batch file location into the program box.

Now every time you press the green play button, it will open up a the desired website in your default browser.

Body:
Set up:

1) OS - Win 8.1

2) WAMP

3) PhpStorm 7.1.3

I have been working on Dreamweaver for quite a long time and recently I ditched it because of its limited features. Setting up a local env using Dreamweaver is fairly simple and I had no problem with it. So I installed PhpStorm thinking it would quite easy to run my PHP web app in the same way when I was using DW, but When I try to run my web app in PhpStorm using its built-in webserver I get 502 Bad Gateway error, What I did is simply import the folder (which is in www directory) in PhpStorm and try to run it on browser, but I couldn't get it to work locally. I believe I have to set up Interpreter under settings, but how do I go ahead and what should I include?

When I run my webapp using WAMP the URL looks like

http://localhost/appname/trunk/public/

When I run it using PhpStorm built-in webserver the URL looks like

http://localhost:63342/appname/trunk/public/

Error: 502 bad gateway.

I am quite stuck now.

Body:
I recently came across a similar problem when attempting to run on a different localhost on my computer.

One easy work around I found was by editing your run/debug configurations.

Before you do this, save a simple batch file to where ever you'd like on your hard drive and name it 'init.bat'.(eg. mine is 'C:\wamp64\www\myhost\init.bat'). Inside this batch file use this code to open your desired website:

start "" http://localhost/appname/trunk/public/

So head over to the run/debug configurations and then choose the php script you want to run. For example mine was called "index.php". When there, at the bottom of the window there should be a section that says, "Before launch: External tool, Activate tool window".

Click 'Run external tool' and from there add your batch file location into the program box.

Now every time you press the green play button, it will open up a the desired website in your default browser.


问:
How to Extract Value of Output in R?
How can you extract the index value of a result in R.

data.frame(sort(table(df$col1),decreasing=TRUE))

This results in an output of the col1 value and its count.
The output is the following:

```<code>          Var1   |    freq
   ---------------------------
    1     ABC    |      10
    2     DEF    |       9
   ...
</code>```

I'm basically trying to extract 'ABC'.

UPDATED ANSWER:

The following options will output the greatest reoccuring value in a column (col1) while retaining the original datatype:

```<code>subset(df,!is.na(df$col1),) %>% count(col1) %>% arrange(desc(n)) %>% c(1)[1][[1]]
OR
data.frame(sort(table(df$col1),decreasing=TRUE))[1,1]
OR
sqldf("SELECT COUNT(*) as count, col1 FROM df WHERE col1 IS NOT NULL GROUP BY col1 ORDER BY count DESC")$col1[1]

</code>```

答:
if you want to extract the values single column using dplyr package, you can use select. E.g- df%>%count(col1)%>%arrange(desc(n))%>%select(col1)

To find out the index of any column/attributes & index of values in a column, you can use which, this syntax need a logical operator and single value. E.g.- `which(colnames(df) == 'column_name'), this gives you the index of that column.

For finding the index of any values of that column, this can be used which(df$col1 == 1

Title: How to Extract Value of Output in R?

Body:
How can you extract the index value of a result in R.

data.frame(sort(table(df$col1),decreasing=TRUE))

This results in an output of the col1 value and its count.
The output is the following:

          Var1   |    freq
   ---------------------------
    1     ABC    |      10
    2     DEF    |       9
   ...

I'm basically trying to extract 'ABC'.

UPDATED ANSWER:

The following options will output the greatest reoccuring value in a column (col1) while retaining the original datatype:

subset(df,!is.na(df$col1),) %>% count(col1) %>% arrange(desc(n)) %>% c(1)[1][[1]]
OR
data.frame(sort(table(df$col1),decreasing=TRUE))[1,1]
OR
sqldf("SELECT COUNT(*) as count, col1 FROM df WHERE col1 IS NOT NULL GROUP BY col1 ORDER BY count DESC")$col1[1]


问:
.net Runtime - Silverlight Runtime =?
I've googled around a bit, and I haven't been able to find a good listing of what classes from the .net CLR are not included in the 'CoreCLR' aka Silverlight.

What is Silverlight missing from the Windows .net Framework?

Also, is there anything that the Silverlight runtime has that the .net Framework doesn't?

答:
Silverlight Runtime (Silverlight CLR) is essentially a mini-mini CLR :).

Microsoft did the work of removing many dependencies to .NET Framework assemblies not part of the Silverlight release

Silverlight CLR is a subset of the
  .NET Framework that contains
  components and libraries, including
  data integration, extensible Windows
  controls, networking, base class
  libraries, garbage collection, and the
  common language runtime (CLR).

Some parts of the .NET Framework for
  Silverlight are deployed with your
  application. These "Silverlight
  Libraries" are assemblies not included
  in the Silverlight runtime and are
  instead shipped in the Silverlight
  SDK. When Silverlight Libraries are
  used in your application, they are
  packaged up with your application and
  downloaded to the browser. These
  include new UI controls, XLINQ,
  Syndication (RSS/Atom), XML
  serialization, and the dynamic
  language runtime (DLR).

To read about a detailed comparison, see this link http://codebetter.com/blogs/patricksmacchia/archive/2008/10/01/comparing-silverlight-and-the-net-framework.aspx

OwnerDisplayName: TJB

ContentLicense: CC BY-SA 2.5

Title: .net Runtime - Silverlight Runtime =?


问:
How to validate three check boxes with reactive forms module?
This should be relatively easy, not sure why I am struggling.

I have three check-boxes and I want to make sure the user clicks one and only one. So the validator should check that any of the other two boxes have been checked and prevent another selection. It should make sure at least one is checked.

I have tried using a custom validator, but you can only pass a control in. I need something that checks all the boxes for validation.

```<code><form class="example-section" [formGroup]="queryType">
  <mat-checkbox class="example-margin" [(ngModel)]="artist" formControlName="artist">Artist</mat-checkbox>
  <mat-checkbox class="example-margin" [(ngModel)]="album" formControlName="album">Album</mat-checkbox>
  <mat-checkbox class="example-margin" [(ngModel)]="track" formControlName="track">Track</mat-checkbox>
</form>```

```

``` export class SearchComponent implements OnInit, OnChanges {

  filteredSearchItems: Observable<SearchResult[]>;
  isLoading = false;
  searchForm: FormGroup;
  queryType: FormGroup;
  disabled: boolean = false;
  artist: boolean;
  album: boolean;
  track: boolean;

constructor(private searchService: SearchService, private fb:
  FormBuilder) {
this.searchForm = this.fb.group({
  searchInput: new FormControl(null)
});
this.queryType = this.fb.group({
 'artist': new FormControl(false,[CustomValidators.validateQuery]),
  'album': new FormControl(false,[CustomValidators.validateQuery]),
  'track': new FormControl(false,[CustomValidators.validateQuery])
});
```

<p>}</p>

```export class CustomValidators {

    static validateQuery(control: FormGroup): { [s: string]: boolean }
       {//not sure how to pass in all boxes

   for(const con of control.controls) { // somewhere here is the answer
            if(con.value) {
            return { alreadyChecked: true}
            }
        }

        return null;
    };
}
```

答:
There 2 possible solutions for it.

1.) You can use a radio button instead of checkbox, that way you can only select either one of those 3 options.

2.) If you really want to use the checkbox. You can implement it like this. Have also created a Stackblitz Demo for your reference

```<code><mat-checkbox class="example-margin"
              formControlName="artist"
              [disabled]="album || track">Artist</mat-checkbox>   // This will be disabled when album or track is already checked

<mat-checkbox class="example-margin"
              formControlName="album"
              [disabled]="artist || track">Album</mat-checkbox>   // This will be disabled when artist or track is already checked

<mat-checkbox class="example-margin"
              formControlName="track"
              [disabled]="artist || album">Track</mat-checkbox>   // This will be disabled when artist or album is already checked.
</code>```

With that, the user can only check one item from those 3 options.

NOTE:

You should decide whether you'll use a Template Driven Form [(ngModel)] or Reactive Form Module (formControlName) since you can't merge those two inside an input tag.

Body:
This should be relatively easy, not sure why I am struggling.

I have three check-boxes and I want to make sure the user clicks one and only one. So the validator should check that any of the other two boxes have been checked and prevent another selection. It should make sure at least one is checked.

I have tried using a custom validator, but you can only pass a control in. I need something that checks all the boxes for validation.

<form class="example-section" [formGroup]="queryType">
  <mat-checkbox class="example-margin" [(ngModel)]="artist" formControlName="artist">Artist</mat-checkbox>
  <mat-checkbox class="example-margin" [(ngModel)]="album" formControlName="album">Album</mat-checkbox>
  <mat-checkbox class="example-margin" [(ngModel)]="track" formControlName="track">Track</mat-checkbox>
</form>```

 export class SearchComponent implements OnInit, OnChanges {

  filteredSearchItems: Observable<SearchResult[]>;
  isLoading = false;
  searchForm: FormGroup;
  queryType: FormGroup;
  disabled: boolean = false;
  artist: boolean;
  album: boolean;
  track: boolean;

constructor(private searchService: SearchService, private fb:
  FormBuilder) {
this.searchForm = this.fb.group({
  searchInput: new FormControl(null)
});
this.queryType = this.fb.group({
 'artist': new FormControl(false,[CustomValidators.validateQuery]),
  'album': new FormControl(false,[CustomValidators.validateQuery]),
  'track': new FormControl(false,[CustomValidators.validateQuery])
});

}

export class CustomValidators {

    static validateQuery(control: FormGroup): { [s: string]: boolean }
       {//not sure how to pass in all boxes

   for(const con of control.controls) { // somewhere here is the answer
            if(con.value) {
            return { alreadyChecked: true}
            }
        }

        return null;
    };
}

Body:
There 2 possible solutions for it.

1.) You can use a radio button instead of checkbox, that way you can only select either one of those 3 options.

2.) If you really want to use the checkbox. You can implement it like this. Have also created a Stackblitz Demo for your reference

<mat-checkbox class="example-margin"
              formControlName="artist"
              [disabled]="album || track">Artist</mat-checkbox>   // This will be disabled when album or track is already checked

<mat-checkbox class="example-margin"
              formControlName="album"
              [disabled]="artist || track">Album</mat-checkbox>   // This will be disabled when artist or track is already checked

<mat-checkbox class="example-margin"
              formControlName="track"
              [disabled]="artist || album">Track</mat-checkbox>   // This will be disabled when artist or album is already checked.

With that, the user can only check one item from those 3 options.

NOTE:

You should decide whether you'll use a Template Driven Form [(ngModel)] or Reactive Form Module (formControlName) since you can't merge those two inside an input tag.


问:
How to properly call a C# async method when overriding an non-async method?
I am creating a TagHelper for a RazorPage. The TagHelper class's only requirement is that the process method get overridden.

Here is the signature (and thank you for the solution Stephen let's just assume that ProcessAsync doesn't exist so we can still answer the question).

```<code>public override void Process(TagHelperContext context, TagHelperOutput output)
</code>```

The body is very simple

```<code>if(_roleService.CanRegisterAsync().Result)
{
    output.SuppressOutput();
}
</code>```

I hear that deadlocks can be caused by calling .Result on async methods so I don't want to call it as written above because it seems like I could run into some trouble.

So, I change the virtual override by adding async to

```<code>public override async void Process(TagHelperContext context, TagHelperOutput output)
</code>```

and the body to

```<code>if(await _roleService.CanRegisterAsync())
{
    output.SuppressOutput();
}
</code>```

This compiles fine but the output.SupressOutput() doesn't to seem to have any effect anymore so I am forced to go back to the original code which seems like a bad idea.

Is there any better way to deal with this situation so I don't potentially run into deadlocks as many people talk about in other async posts?

答:
Apparently what you are after is the following:

```<code>if(_roleService.CanRegisterAsync().WaitAndUnwrapException())
{
    output.SuppressOutput();
}
</code>```

Remark: The name of the method strongly suggests using a try/catch to handle possible exceptions

Body:
I am creating a TagHelper for a RazorPage. The TagHelper class's only requirement is that the process method get overridden.

Here is the signature (and thank you for the solution Stephen let's just assume that ProcessAsync doesn't exist so we can still answer the question).

public override void Process(TagHelperContext context, TagHelperOutput output)

The body is very simple

if(_roleService.CanRegisterAsync().Result)
{
    output.SuppressOutput();
}

I hear that deadlocks can be caused by calling .Result on async methods so I don't want to call it as written above because it seems like I could run into some trouble.

So, I change the virtual override by adding async to

public override async void Process(TagHelperContext context, TagHelperOutput output)

and the body to

if(await _roleService.CanRegisterAsync())
{
    output.SuppressOutput();
}

This compiles fine but the output.SupressOutput() doesn't to seem to have any effect anymore so I am forced to go back to the original code which seems like a bad idea.

Is there any better way to deal with this situation so I don't potentially run into deadlocks as many people talk about in other async posts?

Body:
Apparently what you are after is the following:

if(_roleService.CanRegisterAsync().WaitAndUnwrapException())
{
    output.SuppressOutput();
}

Remark: The name of the method strongly suggests using a try/catch to handle possible exceptions


问:
`' '.join(e)` isn't changing value of e
I'm creating a function to create all 26 combinations of words with a fixed suffix. The script works except for the JOIN in the second-to-last line.

```<code>def create_word(suffix):
    e=[]
    letters="abcefghijklmnopqrstuvwxyz"
    t=list(letters)
    for i in t:
        e.append(i)
        e.append(suffix)
    ' '.join(e)
    print e
</code>```

Currently, it is printing ['a', 'suffix', 'b', 'suffix, ...etc]. And I want it to print out as one long string: 'aSuffixbSuffixcSuffix...etc.' Why isn't the join working in this? How can I fix this?

In addition, how would I separate the characters once I have the string? For example to translate "take the last character of the suffix and add a space to it every time ('aSuffixbSuffixcSuffix' --> 'aSuffix bSuffix cSuffix')". Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).

答:
join doesn't change its arguments - it just returns a new string:</p>

```<code>result = ' '.join(e)
return result
</code>```

Title: `' '.join(e)` isn't changing value of e

Body:
I'm creating a function to create all 26 combinations of words with a fixed suffix. The script works except for the JOIN in the second-to-last line.

def create_word(suffix):
    e=[]
    letters="abcefghijklmnopqrstuvwxyz"
    t=list(letters)
    for i in t:
        e.append(i)
        e.append(suffix)
    ' '.join(e)
    print e

Currently, it is printing ['a', 'suffix', 'b', 'suffix, ...etc]. And I want it to print out as one long string: 'aSuffixbSuffixcSuffix...etc.' Why isn't the join working in this? How can I fix this?

In addition, how would I separate the characters once I have the string? For example to translate "take the last character of the suffix and add a space to it every time ('aSuffixbSuffixcSuffix' --> 'aSuffix bSuffix cSuffix')". Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).

Body:
join doesn't change its arguments - it just returns a new string:

result = ' '.join(e)
return result


问:
How to do corners right with Cocoa Touch (iOS) Graphics Context Drawing?
I am just experimenting, getting used to drawing with Quartz 2D on iOS.  I drew three offset squares (perimeter lines only) using Graphics Context move(to:) and addLine(_:CGPoint) functions.  Consider the following image of the result:

I am only showing the top part but it is enough to document my question.  You can see that the upper left corner of each square is incomplete (sharp square corners) where as the upper right looks OK.  The two bottom corners are like the upper right in being exactly what I expected.

So, my starting position for adding these lines (width set to 3.0) is the upper left corner which is located using Graphics Context move(to: CGPoiint).  Each subsequent corner is arrived by merely calling the addLine(_:CGPoint) method.

So, what am I doing wrong that results in the "broken" corner as shown.  How do I get that upper left corner to look like all others?

Code generating diagram

```<code>override func draw(_ rect: CGRect) {
    let colors: [(CGFloat,CGFloat,CGFloat)] =
          [(1.0,0.0,0.0),(0.25,1.0,0.5),(0.5,0.5,1.0)]
    let c = UIGraphicsGetCurrentContext()!
    c.setLineWidth(3.0)
    var dx = 0
    var dy = 0
    for q in 1...3 {
        c.move(to:CGPoint(x:dx+50, y:dy+50))
        c.addLine(to:CGPoint(x: dx+200, y: dy+50))
        c.addLine(to:CGPoint(x: dx+200, y: dy+200))
        c.addLine(to:CGPoint(x: dx+50,y: dy+200))
        c.addLine(to:CGPoint(x: dx+50,y: dy+50))
        c.setStrokeColor(
             red:colors[q-1].0
            ,green:colors[q-1].1
            ,blue:colors[q-1].2,alpha:1.0)
        c.strokePath()
        dx += 20
        dy += 20
    }
}
</code>```

答:
The artifact is caused by the thicker line width. All of the dimensions you give are for the center of each line. Since you give a line width of 3, each line is filled 1.5 points each side of the center line.

You could account for this in the first and last coordinate but that's error prone and depends on the line width.

The better solution is to use closePath() instead of adding the last line.

```<code>c.move(to:CGPoint(x:dx+50, y:dy+50))
c.addLine(to:CGPoint(x: dx+200, y: dy+50))
c.addLine(to:CGPoint(x: dx+200, y: dy+200))
c.addLine(to:CGPoint(x: dx+50,y: dy+200))
//c.addLine(to:CGPoint(x: dx+50,y: dy+50)) // not needed any more
c.closePath()
</code>```

closePath() will draw a straight line from the last point to the first point of the path. This also deals with properly filling in that little artifact at the join at the location of the first point.

The simplest solution is to use UIBezierPath to draw the rectangle but doing it all manually is a good way to learn.

Body:
I am just experimenting, getting used to drawing with Quartz 2D on iOS.  I drew three offset squares (perimeter lines only) using Graphics Context move(to:) and addLine(_:CGPoint) functions.  Consider the following image of the result:

I am only showing the top part but it is enough to document my question.  You can see that the upper left corner of each square is incomplete (sharp square corners) where as the upper right looks OK.  The two bottom corners are like the upper right in being exactly what I expected.

So, my starting position for adding these lines (width set to 3.0) is the upper left corner which is located using Graphics Context move(to: CGPoiint).  Each subsequent corner is arrived by merely calling the addLine(_:CGPoint) method.

So, what am I doing wrong that results in the "broken" corner as shown.  How do I get that upper left corner to look like all others?

Code generating diagram

override func draw(_ rect: CGRect) {
    let colors: [(CGFloat,CGFloat,CGFloat)] =
          [(1.0,0.0,0.0),(0.25,1.0,0.5),(0.5,0.5,1.0)]
    let c = UIGraphicsGetCurrentContext()!
    c.setLineWidth(3.0)
    var dx = 0
    var dy = 0
    for q in 1...3 {
        c.move(to:CGPoint(x:dx+50, y:dy+50))
        c.addLine(to:CGPoint(x: dx+200, y: dy+50))
        c.addLine(to:CGPoint(x: dx+200, y: dy+200))
        c.addLine(to:CGPoint(x: dx+50,y: dy+200))
        c.addLine(to:CGPoint(x: dx+50,y: dy+50))
        c.setStrokeColor(
             red:colors[q-1].0
            ,green:colors[q-1].1
            ,blue:colors[q-1].2,alpha:1.0)
        c.strokePath()
        dx += 20
        dy += 20
    }
}

Body:
The artifact is caused by the thicker line width. All of the dimensions you give are for the center of each line. Since you give a line width of 3, each line is filled 1.5 points each side of the center line.

You could account for this in the first and last coordinate but that's error prone and depends on the line width.

The better solution is to use closePath() instead of adding the last line.

c.move(to:CGPoint(x:dx+50, y:dy+50))
c.addLine(to:CGPoint(x: dx+200, y: dy+50))
c.addLine(to:CGPoint(x: dx+200, y: dy+200))
c.addLine(to:CGPoint(x: dx+50,y: dy+200))
//c.addLine(to:CGPoint(x: dx+50,y: dy+50)) // not needed any more
c.closePath()

closePath() will draw a straight line from the last point to the first point of the path. This also deals with properly filling in that little artifact at the join at the location of the first point.

The simplest solution is to use UIBezierPath to draw the rectangle but doing it all manually is a good way to learn.


问:
Web Garden vs Tuning ASP.NET Web.config file by using parameters such as MaxWorkerThreads
Some people recommend to avoid using Web Garden. Instead they recommend to try first tuning some parameters in ASP.NET app web.config file by using this.

As far as I know Web Garden consists on incrementing the number of worker processes in the Pool. It is like having multiple threads serving the incoming requests.

So what's the difference between using multiple worker processes for the Pool and tuning the ASP.NET web.config file by using parameters such as MaxWorkerThreads, MaxIOThreads, etc.?

Both consists on using more than one thread so I am not be able to see the difference between these two techniques.

答:
I feel when working with scalability, you want to scale vertically as far as you can before scaling horizontally.

The advice you're hearing is suggesting the same thing. That you make sure to set max worker threads for one IIS instance, to give it a fighting chance.  It's better to do this and increase CPU before looking to scale horizontally.


问:
jQuery get json file from directory
I want to create json from folder.

For instance if there is a directory named test with structure as this image.

From here I want to create json file.

```<code>{
name:test,
children:[{
name:test1,
children:[{
...
}
,{name:test2.html},
{name:test3.txt}]}
</code>```

How can I do this without using nodejs or server side language.
Just using jquery?

Thanks.

答:
If I understood correctly, you need to access the html files inside folders and create a JSON file to work as 'index'.

You can create an index.html in the root and, with JS, set a loop to that json file.
You create rows with links to child folders.

Title: jQuery get json file from directory

Body:
I want to create json from folder.

For instance if there is a directory named test with structure as this image.

From here I want to create json file.

{
name:test,
children:[{
name:test1,
children:[{
...
}
,{name:test2.html},
{name:test3.txt}]}

How can I do this without using nodejs or server side language.
Just using jquery?

Thanks.


问:
Get document collections in Firestore
this is my firebase database

```<code>- conversations (collection)
-- xxx (document)
--- users (collection)
---- xxx (document)
</code>```

I want to list all the conversations and its users

```<code>this.db.collection('conversations').get().then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
        console.log(doc.collection('users').get())
    });
});
</code>```

I´m getting doc.collection is not a function

update: this is what I have after getting the id and making a new query. now the question is. is this performant?

```<code>    this.db.collection('conversations').get().then(conversationsQuerySnapshot => {
        conversationsQuerySnapshot.docs.forEach(doc => {
            this.db.collection('conversations').doc(doc.id).collection('users').get().then(usersQuerySnapshot => {
                usersQuerySnapshot.docs.forEach(doc => {
                    console.table(doc.data());
                });
            });
        });
    });
</code>```

答:
you would call it: db.collection('conversations').doc({docID}).collection('users')

Your current query is set up to look through every conversation and then get every user in each of those. Plus the second part (getting the users) has no base document to pull from, which is why you're seeing an error.

I recommend watching this video

Title: Get document collections in Firestore

Body:
this is my firebase database

- conversations (collection)
-- xxx (document)
--- users (collection)
---- xxx (document)

I want to list all the conversations and its users

this.db.collection('conversations').get().then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
        console.log(doc.collection('users').get())
    });
});

I´m getting doc.collection is not a function

update: this is what I have after getting the id and making a new query. now the question is. is this performant?

    this.db.collection('conversations').get().then(conversationsQuerySnapshot => {
        conversationsQuerySnapshot.docs.forEach(doc => {
            this.db.collection('conversations').doc(doc.id).collection('users').get().then(usersQuerySnapshot => {
                usersQuerySnapshot.docs.forEach(doc => {
                    console.table(doc.data());
                });
            });
        });
    });


问:
How to show the same DIV container and different content based on the link click
I am attempting to have a hidden DIV that is displayed based on a link clicked in the table and it shows the associated information about that specific link click. A different link click should show that same table, however different information that is associated only with that link click.

I have tried utilizing some jquery. And everything works, as in showing the div and hiding content behind it. But it only shows the first content, not the second if I click the second link.

  <div id="link"
Link Table and DIV

          Link 1
       Link 1 Description

       href="#" value="link_2">Link 2
       Link 2 Description

href="">

 blah blah blah

 blah blah blah blah

```

答:
@NewToJS 's fiddle seems to work, but if you want to display only the corresponding div to that link click. You should try

```<code>$(".accept").click(function() {
    $(".hidden_div").show("slow");
    $("#link").hide("slow");
    if($(this).hasClass("link_1")){
        $("#link_1").show("slow");
    }
    if($(this).hasClass("link_2")){
        $("#link_2").show("slow");
    }
});
</code>```

And add classes to your link row like

```<code><tr class="accept link_1">
<tr class="accept link_2">
</code>```

Here is a working Fiddle

Hope it helps.

EDIT: I changed value attribute of anchor to name, so it can be accessed in jQuery. Here is the Fiddle when large number of options are present for links.

Body:
I am attempting to have a hidden DIV that is displayed based on a link clicked in the table and it shows the associated information about that specific link click. A different link click should show that same table, however different information that is associated only with that link click.

I have tried utilizing some jquery. And everything works, as in showing the div and hiding content behind it. But it only shows the first content, not the second if I click the second link.

  <div id="link"
Link Table and DIV

          Link 1
       Link 1 Description

       Link 2
       Link 2 Description

 blah blah blah

 blah blah blah blah

Body:
@NewToJS 's fiddle seems to work, but if you want to display only the corresponding div to that link click. You should try

$(".accept").click(function() {
    $(".hidden_div").show("slow");
    $("#link").hide("slow");
    if($(this).hasClass("link_1")){
        $("#link_1").show("slow");
    }
    if($(this).hasClass("link_2")){
        $("#link_2").show("slow");
    }
});

And add classes to your link row like

<tr class="accept link_1">
<tr class="accept link_2">

Here is a working Fiddle

Hope it helps.

EDIT: I changed value attribute of anchor to name, so it can be accessed in jQuery. Here is the Fiddle when large number of options are present for links.


问:
Modifying HTML form while getting new code from php
I'm trying to make an red error warning signal but instead of modifying the current input box, it creates another.

Can you help me?

```<code>.error form input[type="text"]{
    box-shadow: 0 0 1em red;
    -webkit-box-shadow: 0 0 1em red;
    -o-box-shadow: 0 0 1em red;
    -moz-box-shadow: 0 0 1em red;
}

.error3 input[type="password"]{
    box-shadow: 0 0 1em red;
    -webkit-box-shadow: 0 0 1em red;
    -o-box-shadow: 0 0 1em red;
    -moz-box-shadow: 0 0 1em red;
}
</code>```

PHP

```<code>$errors = array();
if (empty($Username)) { array_push($errors, "Username is required"); }

if ($Password_1 != $Password_2) {
    array_push($errors, "<div class='error3'>Password isn't the same.</div>");
}
</code>```

HTML (a part of it, there's more inputs form email, username etc)

```<code><?php include('includes/errors.php'); ?>
<div class="form-group">
    <label for="Password_2">Verify password</label>
    <div class="input-icon">
        <i class="mdi mdi-lock"></i>
        <span class="passtoggle mdi mdi-eye toggle-password"></span>
        <input type="password" class="form-control" id="password" name="Password_2" placeholder="Verify password" required>
    </div>
</div>
</code>```

I tried to modify the code, didn't work. The error3 divclass closes too fast.

答:
Fixed. I added in the PHP section only this</p>

```<code>        if ($Password_1 != $Password_2) {
            array_push($errors, "

            <style>
            .form-group input[type='password']{
    box-shadow: 0 0 1em red;
    -webkit-box-shadow: 0 0 1em red;
    -o-box-shadow: 0 0 1em red;
    -moz-box-shadow: 0 0 1em red;
}</style>

            Not the same password.");
        }
</code>```

Body:
I'm trying to make an red error warning signal but instead of modifying the current input box, it creates another.

Can you help me?

.error form input[type="text"]{
    box-shadow: 0 0 1em red;
    -webkit-box-shadow: 0 0 1em red;
    -o-box-shadow: 0 0 1em red;
    -moz-box-shadow: 0 0 1em red;
}

.error3 input[type="password"]{
    box-shadow: 0 0 1em red;
    -webkit-box-shadow: 0 0 1em red;
    -o-box-shadow: 0 0 1em red;
    -moz-box-shadow: 0 0 1em red;
}

PHP

$errors = array();
if (empty($Username)) { array_push($errors, "Username is required"); }

if ($Password_1 != $Password_2) {
    array_push($errors, "
Password isn't the same.
");
}

HTML (a part of it, there's more inputs form email, username etc)

<?php include('includes/errors.php'); ?>

    Verify password

        <input type="password" class="form-control" id="password" name="Password_2" placeholder="Verify password" required>

I tried to modify the code, didn't work. The error3 divclass closes too fast.

Body:
Fixed. I added in the PHP section only this

        if ($Password_1 != $Password_2) {
            array_push($errors, "

            <style>
            .form-group input[type='password']{
    box-shadow: 0 0 1em red;
    -webkit-box-shadow: 0 0 1em red;
    -o-box-shadow: 0 0 1em red;
    -moz-box-shadow: 0 0 1em red;
}</style>

            Not the same password.");
        }


问:
Binding the value of a variable to a text input
I've been looking all over the internet but I couldn't find an answer to the following question: Is it possible to have the value of some string variable bound to the text inside a text input control? To clarify, whatever text was entered into the text input would be stored as the value of the variable.</p>

答:
You could set the value of the variable using the change event of the TextInput.

Example (untested):

```<code><fx:Script>
  <![CDATA[
  [Bindable] public var someText:String = "foo";

  protected function myText_changeHandler(event:TextOperationEvent):void
  {
    someText = myText.text;
  }
  ]]>
</fx:Script>

<s:TextInput id="myText" text="{someText}" change="myText_changeHandler(event)" />
</code>```

Body:
You could set the value of the variable using the change event of the TextInput.

Example (untested):

<fx:Script>
  <![CDATA[
  [Bindable] public var someText:String = "foo";

  protected function myText_changeHandler(event:TextOperationEvent):void
  {
    someText = myText.text;
  }
  ]]>
</fx:Script>

<s:TextInput id="myText" text="{someText}" change="myText_changeHandler(event)" />