问:
How to disable a filed using form builder in Angular
Hello I want to disable a filed/drop-down based on conditions angular form builder:

I have 3 drop downs, first drop down will be loading while page loading.. when I select the option in first drop-down second should be enabled, when I select the option in second third should be enabled.

here is what I tried:

```<code>       ngOnInit(): void {

            this.someMethodToFetchDataForSelectbox();
            this.method1.subscribe(data => {
                this.data= data;
              }
            );
            this.constructForm();
          }

    constructForm() {
    this.form =  this.fb.group({
     listOfFruits: [''],
     listOfAnimals: [''],
listOfLetters: ['']
    });
this.form.get('listOfAnimals').disable();
    this.form.get('listOfLetters').disable();
    this.form.controls.listOfFruits.valueChanges.subscribe(value=>{
   his.forms.controls.listOfAnimals.enable();
      this.form.get('listOfLetters').disable();
//method to fetch list of animals from DB
fetchAnimals(value) ;

    });
    }
fetchAnimals(value) {
 this.form.controls.listOfAnimals.valueChanges.subscribe(value=>{
   this.forms.controls.listOfLetters.enable();
      //method to fetch list of letters from DB
fetchLetters(value) ;
  });
}
</code>```

I tried the above but it is not working..

答:
you need to use valueChange property not value

```<code>this.form.controls.listOfFruits.valueChanges.subscribe(value => {
  //...
})
</code>```

in case of disable the form control by default

```<code>constructForm() {
 this.form =  this.fb.group({
  listOfFruits: [''],
  listOfAnimals: ['']
 });

 this.form.get('listOfAnimals').disable(); //
 ....
}
</code>```

Body:
Hello I want to disable a filed/drop-down based on conditions angular form builder:

I have 3 drop downs, first drop down will be loading while page loading.. when I select the option in first drop-down second should be enabled, when I select the option in second third should be enabled.

here is what I tried:

       ngOnInit(): void {

            this.someMethodToFetchDataForSelectbox();
            this.method1.subscribe(data => {
                this.data= data;
              }
            );
            this.constructForm();
          }

    constructForm() {
    this.form =  this.fb.group({
     listOfFruits: [''],
     listOfAnimals: [''],
listOfLetters: ['']
    });
this.form.get('listOfAnimals').disable();
    this.form.get('listOfLetters').disable();
    this.form.controls.listOfFruits.valueChanges.subscribe(value=>{
   his.forms.controls.listOfAnimals.enable();
      this.form.get('listOfLetters').disable();
//method to fetch list of animals from DB
fetchAnimals(value) ;

    });
    }
fetchAnimals(value) {
 this.form.controls.listOfAnimals.valueChanges.subscribe(value=>{
   this.forms.controls.listOfLetters.enable();
      //method to fetch list of letters from DB
fetchLetters(value) ;
  });
}

I tried the above but it is not working..

Body:
you need to use valueChange property not value

this.form.controls.listOfFruits.valueChanges.subscribe(value => {
  //...
})

in case of disable the form control by default

constructForm() {
 this.form =  this.fb.group({
  listOfFruits: [''],
  listOfAnimals: ['']
 });

 this.form.get('listOfAnimals').disable(); //
 ....
}


来源: stackexchange

问:
Changing a Parents Key with a subarray value 3 Dimensional Array
So the code below is mainly to generate the same Array I have, This array is generated via some other process that I do not have control over thus direct editing is not possible.

What I need to do is change the key that outputs on the second tier array
Array with the 'uid' on the 3rd array.  Below I have a visual of what it looks like now and what I need it to be.

```<code>```

(
    [0] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [1] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [2] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [3] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [4] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [5] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)

Desired Output

Array
(
    [155] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [156] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [157] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [158] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [159] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [160] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)
```
</code>```

I have tried some for each loops but they have generated some strange output and I have attempted to pass the value during the 2cnd tier array via array_push but only got errors.

```<code>$p_array = array(
$alpha = array('uid' => 155,'amount' => 45),
$alpha = array('uid' => 156,'amount' => 45),
$alpha = array('uid' => 157,'amount' => 45),
$alpha = array('uid' => 158,'amount' => 45),
$alpha = array('uid' => 159,'amount' => 45),
$alpha = array('uid' => 160,'amount' => 45)
);
print_r($p_array);
</code>```

答:
Most elegant solution would be to use a reduction:

```<code><?php

$p_array = array(
    $alpha = array('uid' => 155,'amount' => 45),
    $alpha = array('uid' => 156,'amount' => 45),
    $alpha = array('uid' => 157,'amount' => 45),
    $alpha = array('uid' => 158,'amount' => 45),
    $alpha = array('uid' => 159,'amount' => 45),
    $alpha = array('uid' => 160,'amount' => 45)
);

$result = array_reduce(
    $p_array,
    function($acc, $cur) {
        $acc[$cur['uid']] = $cur;
        return $acc;
    },
    array()
);

print_r($result);
</code>```

array_reduce will start with the initial value (which is an empty array in our case) and then for each element call the callback with two elements: 1st the accumulator and 2nd the current item. The accumulator is initialized with our initial value (empty array) and then passed along with each consecutive call. Hence it is imporant to return the $acc after you've done modifying it.

Then to finally do the transformation you where asking for you put the current element into the accumulator with an index using the uid key of the current element: $acc[$cur['uid']] = $cur;

ContentLicense: CC BY-SA 4.0

Body:
So the code below is mainly to generate the same Array I have, This array is generated via some other process that I do not have control over thus direct editing is not possible.

What I need to do is change the key that outputs on the second tier array
Array with the 'uid' on the 3rd array.  Below I have a visual of what it looks like now and what I need it to be.

(
    [0] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [1] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [2] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [3] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [4] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [5] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)

Desired Output

Array
(
    [155] => Array
        (
            [uid] => 155
            [amount] => 45
        )

    [156] => Array
        (
            [uid] => 156
            [amount] => 45
        )

    [157] => Array
        (
            [uid] => 157
            [amount] => 45
        )

    [158] => Array
        (
            [uid] => 158
            [amount] => 45
        )

    [159] => Array
        (
            [uid] => 159
            [amount] => 45
        )

    [160] => Array
        (
            [uid] => 160
            [amount] => 45
        )

)

I have tried some for each loops but they have generated some strange output and I have attempted to pass the value during the 2cnd tier array via array_push but only got errors.

$p_array = array(
$alpha = array('uid' => 155,'amount' => 45),
$alpha = array('uid' => 156,'amount' => 45),
$alpha = array('uid' => 157,'amount' => 45),
$alpha = array('uid' => 158,'amount' => 45),
$alpha = array('uid' => 159,'amount' => 45),
$alpha = array('uid' => 160,'amount' => 45)
);
print_r($p_array);

Body:
Most elegant solution would be to use a reduction:

<?php

$p_array = array(
    $alpha = array('uid' => 155,'amount' => 45),
    $alpha = array('uid' => 156,'amount' => 45),
    $alpha = array('uid' => 157,'amount' => 45),
    $alpha = array('uid' => 158,'amount' => 45),
    $alpha = array('uid' => 159,'amount' => 45),
    $alpha = array('uid' => 160,'amount' => 45)
);

$result = array_reduce(
    $p_array,
    function($acc, $cur) {
        $acc[$cur['uid']] = $cur;
        return $acc;
    },
    array()
);

print_r($result);

array_reduce will start with the initial value (which is an empty array in our case) and then for each element call the callback with two elements: 1st the accumulator and 2nd the current item. The accumulator is initialized with our initial value (empty array) and then passed along with each consecutive call. Hence it is imporant to return the $acc after you've done modifying it.

Then to finally do the transformation you where asking for you put the current element into the accumulator with an index using the uid key of the current element: $acc[$cur['uid']] = $cur;


问:
Set up WinDbg as the default debugger
Whenever my application throws an unhandled exception, I would like WinDbg to catch that exception on my debugging machine rather than Dr. Watson, etc. How can this be configured?</p>

答:
Run windbg -I to install it at the default post mortem debugger.

As Kurt points out below WinDbg comes in both 32 and 64 bit versions. Executing windbg -I sets up the post mortem debugger for the processes corresponding to the bitness of the debugger.

You can install both versions of WinDbg side-by-side if you need to have both the 32 and 64 bit versions available.

From the help file:

-I[S]  Installs WinDbg as the postmortem debugger. For details, see
  Enabling Postmortem Debugging. After
  this action is attempted, a success or
  failure message is displayed. If S is
  included, this procedure is done
  silently if it is successful; only
  failure messages are displayed. The -I
  parameter must not be used with any
  other parameters. This command will
  not actually start WinDbg, although a
  WinDbg window may appear for a moment.

ContentLicense: CC BY-SA 3.0

Title: Set up WinDbg as the default debugger


问:
Center different size images in the same block size
I have different images encapsulated in square style blocks that I would like to always center in but I'm having a heck of a time trying to get them to do so.

I made an example of what's happening to me in similar design. Notice the product (the grill) is not actually centered in the imgblock container.

This starts to become very apparent with other product images that are much wider than narrow.

.imgBlock {
  width:100px;
  height:100px;
  border:2px solid black;
  margin:1px;
  padding:4px;
}

.imgBlock img{
  max-height:100%;
  max-width:100%;
  margin:auto;
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/WG-logo-short-black.png?43066">
  </div>
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/M1-Grill-FAQ.jpg?43066">
  </div>
</div></code>```

答:
First set the image to full width and height (or as desired). Now you can add object-fit: contain to contain the image to the imgBlock and now use object-position: center to align it - see demo below:

.imgBlock {
  width:100px;
  height:100px;
  border:2px solid black;
  margin:1px;
  padding:4px;
}

.imgBlock img{
  height:100%; /* set full height */
  width:100%; /* set full width */
  display:block;
  object-fit: contain; /* constrains the image maintaining aspect ratio */
  object-position: center; /* default position is center - so optional in this case */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/WG-logo-short-black.png?43066">
  </div>
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/M1-Grill-FAQ.jpg?43066">
  </div>
</div></code>```

Body:
First set the image to full width and height (or as desired). Now you can add object-fit: contain to contain the image to the imgBlock and now use object-position: center to align it - see demo below:

.imgBlock {
  width:100px;
  height:100px;
  border:2px solid black;
  margin:1px;
  padding:4px;
}

.imgBlock img{
  height:100%; /* set full height */
  width:100%; /* set full width */
  display:block;
  object-fit: contain; /* constrains the image maintaining aspect ratio */
  object-position: center; /* default position is center - so optional in this case */
}

<div class="container">
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/WG-logo-short-black.png?43066">
  </div>
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/M1-Grill-FAQ.jpg?43066">
  </div>
</div>


问:
Kill secondary task of a given process
I'm trying to kill a secondary task of a process using powershell, batch, python...anything I can save as script and run it remotely. TaskManager picture as following:

I'd like to kill the one with longer title leaving the "SAP Logon 740" open. Every task of the tree have the same PID, so I can't just kill the process.

I guess this is posible, because  I can do it manually going to Task MAnager, expanding the process and ending that specific task but everything I've found consist in killing the process, which isn't possible in my case.

I've so far tried with tasklist/taskkill, powershell (Get-Process, Get-Object Win32_Process...) but I haven't been able to find how to.

Here you have the output of TaskList (Status=Running)

Only one of the task (the one which is front) is showing there.

答:
As you have used the powershell tag, and even ran your tasklist command using powerhell.exe, I have decided to provide an examples using it.

If your criteria is to stop the process named saplogon with the longest window title string:

```<code>GPs saplogon|Sort{$_.mainWindowTitle.Length}|Select -L 1|SpPs -Wh
</code>```

If your criteria is to stop all processes named saplogon except for the one with the shortest window title string:

```<code>GPs saplogon|Sort{$_.mainWindowTitle.Length}|Select -Skip 1|SpPs -Wh`
</code>```

If you're happy with the output, you can remove  -Wh, (-WhatIf), to actually perform the task. If needed you could even replace that with the  -F, (-Force) option, if necessary.

Title: Kill secondary task of a given process

Body:
As you have used the powershell tag, and even ran your tasklist command using powerhell.exe, I have decided to provide an examples using it.

If your criteria is to stop the process named saplogon with the longest window title string:

GPs saplogon|Sort{$_.mainWindowTitle.Length}|Select -L 1|SpPs -Wh

If your criteria is to stop all processes named saplogon except for the one with the shortest window title string:

GPs saplogon|Sort{$_.mainWindowTitle.Length}|Select -Skip 1|SpPs -Wh`

If you're happy with the output, you can remove  -Wh, (-WhatIf), to actually perform the task. If needed you could even replace that with the  -F, (-Force) option, if necessary.


问:
How to append empty or null values without quote in uniVocity CsvWriter
Im trying to append row, using CSVWriter by uniVocity

When i set

settings.setQuoteAllFields(true);

then all fields are quoted, this is logical, but can i set any settings NOT to apply quotes in empty or null fields?

For example, when i call

String stringRow = writer.writeRowToString(new String[] {"null","","","123"})

the stringRow is

"";"";"";"123"

but i need

;;;"123"

How can i set this?

答: Author of the library here. Currently there is no such option. You'd have to write the CSV by hand.</p>


问:
Swapping alternate digits of a number
I am working with some of the problems that are given under hackerrank modules. The question is about swapping the alternate digits of the given number.

I have tried my logic in C. It worked for most of the test cases but couldn't crack some corner case which i am unable to check with. Here is what i have tried.

```<code>int main() {
    int n,i,j;
    char a[20];
    scanf("%s",a);
    n=strlen(a);
    if(n==1){
        printf("%s",a);
    }
    else{
        for(i=0,j=i+1;i<n-1 && j<n;i=i+2,j=j+2){
            a[i]^=a[j]^=a[i]^=a[j];
        }
        printf("%s",a);
    }
    return 0;
}
</code>```

I am not able to visualize the test cases provided by the module owner as i don't have access to them. These were some of the practice problems given in my college for placement preparation. So i don't have access to the test cases and that's why am not able to provide with those failing test cases and their outputs.  Someone please help me with what i had gone wrong in the logic. Thanks in advance.

答:
```<code>a[i]^=a[j]^=a[i]^=a[j];
</code>```

You're attempting to read and write both a[i] and a[j] in a single expression without a sequence point.  Doing so invokes undefined behavior.

Break up the expression into multiple lines.

```<code>a[i]^=a[j];
a[j]^=a[i];
a[i]^=a[j];
</code>```

Title: Swapping alternate digits of a number

Body:
I am working with some of the problems that are given under hackerrank modules. The question is about swapping the alternate digits of the given number.

I have tried my logic in C. It worked for most of the test cases but couldn't crack some corner case which i am unable to check with. Here is what i have tried.

int main() {
    int n,i,j;
    char a[20];
    scanf("%s",a);
    n=strlen(a);
    if(n==1){
        printf("%s",a);
    }
    else{
        for(i=0,j=i+1;i<n-1 && j<n;i=i+2,j=j+2){
            a[i]^=a[j]^=a[i]^=a[j];
        }
        printf("%s",a);
    }
    return 0;
}

I am not able to visualize the test cases provided by the module owner as i don't have access to them. These were some of the practice problems given in my college for placement preparation. So i don't have access to the test cases and that's why am not able to provide with those failing test cases and their outputs.  Someone please help me with what i had gone wrong in the logic. Thanks in advance.

Body:
a[i]^=a[j]^=a[i]^=a[j];

You're attempting to read and write both a[i] and a[j] in a single expression without a sequence point.  Doing so invokes undefined behavior.

Break up the expression into multiple lines.

a[i]^=a[j];
a[j]^=a[i];
a[i]^=a[j];


问:
match column "A" to "D" and use Column "B" id and place it in front of the matching value on "D"
I am fairly new to Excel and VBA.

Column "A" has an ID listed on "B" and column C has the total list not included on "A" what I am trying to do is (if "A"="C) then use the ID from "B" and place it/copy in front of "D"

```<code>=INDEX(B2,MATCH(A2,C2))
</code>```

I am thinking to create a macro where I can just copy the list of test to another sheet then match the values, as column "A" and "C" are not the same then copy the value from "B" to "D" if "A" is found on "C"
I have more than 2500 values that will be part of column "C" but column "A" will never have the same number of rows as "C"
I know it looks simple from the screenshot but the naming convention is different.

I hope it make sense what I am trying to explain here. if not please let me know

答:
Your "IF" logic can be captured by the IF function. So you put this formula in D2 and drag it down as far as you wish.

```<code>=if(A2=C2,B2,"")
</code>```

Revision: The above would work if the match were to be checked for in the same row. But I now understand we are supposed to look in the entire column A. In that case, we can do the following in D2 and drag,

```<code>=iferror(indirect(address(1+match(C2,A$2:A,0),2)),"")
</code>```

The iferror lets the thing stay empty if match fails. If match succeeds, 1+match is the row, and 2 is column B. We make an address of that and find what is at that address.

Body:
I am fairly new to Excel and VBA.

Column "A" has an ID listed on "B" and column C has the total list not included on "A" what I am trying to do is (if "A"="C) then use the ID from "B" and place it/copy in front of "D"

=INDEX(B2,MATCH(A2,C2))

I am thinking to create a macro where I can just copy the list of test to another sheet then match the values, as column "A" and "C" are not the same then copy the value from "B" to "D" if "A" is found on "C"
I have more than 2500 values that will be part of column "C" but column "A" will never have the same number of rows as "C"
I know it looks simple from the screenshot but the naming convention is different.

I hope it make sense what I am trying to explain here. if not please let me know

Body:
Your "IF" logic can be captured by the IF function. So you put this formula in D2 and drag it down as far as you wish.

=if(A2=C2,B2,"")

Revision: The above would work if the match were to be checked for in the same row. But I now understand we are supposed to look in the entire column A. In that case, we can do the following in D2 and drag,

=iferror(indirect(address(1+match(C2,A$2:A,0),2)),"")

The iferror lets the thing stay empty if match fails. If match succeeds, 1+match is the row, and 2 is column B. We make an address of that and find what is at that address.


问:
If a website loads a product on the back end but does not publish it for the public yet, can I access that information?
I'm new to web scraping and am trying to learn more. I know some websites load products on the back end before they make it available to the general public. Is there a way I can access that information using an HTML parser or any other library?

I suspect the website developers use dynamic javascript to alter the information after loading. Or use different tags/classes to hide the information?

答:
I see two questions here:

1)Can I access information on the webserver that isn't sent to the client page?

No. You can only scrape what exists on the page. Anything else would be illegally accessing a non-public server and goes beyond scraping into hacking.

2) If the site loads asynchronously and/or dynamically, can I access the content that loads after the main portion of the html?

Yes, using browser automation tools like selenium, you can approximate a user experiencing the site and wait for the full content to load before you scrape it. This is different from simple requests/beautifulsoup, which only gathers the HTML at the point when you send the request.


问:
RichTextBox text causing error in Microsoft Visual Studio
I'm trying to make my program display text into a text box but when I paste the text it causes errors

```<code>richTextBox1.Text = "/give @p sign 1 0 {    BlockEntityTag: {        Text1: "{\"text\":\"BUY FOR\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/playsound ui.button.click master @a ~ ~ ~ 10 2\"}}",        Text3: "{\"text\":\"2           LVL\",\"color\":\"white\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/scoreboard players tag @p add SHOP2\"}}"    },    display: { Name: "XP SIGN"    }}";
</code>```

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1056  Unexpected character '\'    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1010  Newline in constant MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1519  Invalid token '";' in class, struct, or interface member declaration    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1022  Type or namespace definition, or end-of-file expected   MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

答:
You need to escape your text as such:</p>

```<code>richTextBox1.Text = @"/give @p sign 1 0 {    BlockEntityTag: {        Text1: ""{\""text\"":\""BUY FOR\"",\""bold\"":true,\""clickEvent\"":{\""action\"":\""run_command\"",\""value\"":\""/playsound ui.button.click master @a ~ ~ ~ 10 2\""}}"",        Text3: ""{\""text\"":\""2           LVL\"",\""color\"":\""white\"",\""bold\"":true,\""clickEvent\"":{\""action\"":\""run_command\"",\""value\"":\""/scoreboard players tag @p add SHOP2\""}}""    },    display: { Name: ""XP SIGN""    }}"
</code>```

Body:
I'm trying to make my program display text into a text box but when I paste the text it causes errors

richTextBox1.Text = "/give @p sign 1 0 {    BlockEntityTag: {        Text1: "{\"text\":\"BUY FOR\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/playsound ui.button.click master @a ~ ~ ~ 10 2\"}}",        Text3: "{\"text\":\"2           LVL\",\"color\":\"white\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/scoreboard players tag @p add SHOP2\"}}"    },    display: { Name: "XP SIGN"    }}";

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1056  Unexpected character '\'    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1513  } expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1002  ; expected  MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1010  Newline in constant MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1519  Invalid token '";' in class, struct, or interface member declaration    MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Error CS1022  Type or namespace definition, or end-of-file expected   MSC C:\Users\Aprute\Desktop\Minecraft Shop Creator\MSC\MSC\Form1.cs

Body:
You need to escape your text as such:

richTextBox1.Text = @"/give @p sign 1 0 {    BlockEntityTag: {        Text1: ""{\""text\"":\""BUY FOR\"",\""bold\"":true,\""clickEvent\"":{\""action\"":\""run_command\"",\""value\"":\""/playsound ui.button.click master @a ~ ~ ~ 10 2\""}}"",        Text3: ""{\""text\"":\""2           LVL\"",\""color\"":\""white\"",\""bold\"":true,\""clickEvent\"":{\""action\"":\""run_command\"",\""value\"":\""/scoreboard players tag @p add SHOP2\""}}""    },    display: { Name: ""XP SIGN""    }}"


问:
Dictionary size reduces upon increasing one element
I ran this:

```<code>import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664
</code>```

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?

答:
Allocation of dict literals is handled here: dictobject.c#L685-L695.

Due to quirks of the implementation, size vs number of elements does not end up being monotonically increasing.

```<code>import sys

def getsizeof_dict_literal(n):
    pairs = ["{0}:{0}".format(i) for i in range(n)]
    dict_literal = "{%s}" % ", ".join(pairs)
    source = "sys.getsizeof({})".format(dict_literal)
    size = eval(source)
    return size
</code>```

The odd growing-and-shrinking behaviour exhibited is not just a weird once-off accident, it's a regularly repeating occurrence. For the first few thousand results, the visualization looks like this:

In more recent versions of Python, the dict implementation is completely different and allocation details are more sane.  See bpo28731 - _PyDict_NewPresized() creates too small dict, for an example of some recent changes. In Python 3.7.3, the visualization now looks like this with smaller dicts in general and a monotonic allocation:

Body:
I ran this:

import sys

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1}
print sys.getsizeof(diii)
# output: 1048

diii = {'key1':1,'key2':2,'key3':1,'key4':2,'key5':1,'key6':2,'key7':1,'key8':2}
print sys.getsizeof(diii)
# output: 664

Before asking here, I restarted my python shell and tried it online too and got the same result.

I thought a dictionary with one more element will either give same bytes as output or more, than the one containing one less element.

Any idea what am I doing wrong?

Body:
Allocation of dict literals is handled here: dictobject.c#L685-L695.

Due to quirks of the implementation, size vs number of elements does not end up being monotonically increasing.

import sys

def getsizeof_dict_literal(n):
    pairs = ["{0}:{0}".format(i) for i in range(n)]
    dict_literal = "{%s}" % ", ".join(pairs)
    source = "sys.getsizeof({})".format(dict_literal)
    size = eval(source)
    return size

The odd growing-and-shrinking behaviour exhibited is not just a weird once-off accident, it's a regularly repeating occurrence. For the first few thousand results, the visualization looks like this:

In more recent versions of Python, the dict implementation is completely different and allocation details are more sane.  See bpo28731 - _PyDict_NewPresized() creates too small dict, for an example of some recent changes. In Python 3.7.3, the visualization now looks like this with smaller dicts in general and a monotonic allocation:


问:
Swift Convert decimal coordinate into degrees, minutes, seconds, direction
How can I covert this to swift? My best guess is that all the int get changed to a var. Removing all the @ that lead ".  Also if any can point me to a good source to learn how things convert that would great.

```<code>- (NSString*)coordinateString {

int latSeconds = (int)(self.latitude * 3600);
int latDegrees = latSeconds / 3600;
latSeconds = ABS(latSeconds % 3600);
int latMinutes = latSeconds / 60;
latSeconds %= 60;

int longSeconds = (int)(self.longitude * 3600);
int longDegrees = longSeconds / 3600;
longSeconds = ABS(longSeconds % 3600);
int longMinutes = longSeconds / 60;
longSeconds %= 60;

NSString* result = [NSString stringWithFormat:@"%d°%d'%d\"%@ %d°%d'%d\"%@",
                    ABS(latDegrees),
                    latMinutes,
                    latSeconds,
                    latDegrees >= 0 ? @"N" : @"S",
                    ABS(longDegrees),
                    longMinutes,
                    longSeconds,
                    longDegrees >= 0 ? @"E" : @"W"];

return result;
}
</code>```

My attempt to convert it but Xcode proves me wrong. Reposted the fix suggest with the ABS. Does it look correct now?

```<code>func coordinateString {

var latSeconds = (Int8)(self.latitude * 3600);
var latDegrees = latSeconds / 3600;
latSeconds = abs(latSeconds % 3600);
var latMinutes = latSeconds / 60;
latSeconds %= 60;

var longSeconds = (Int8)(self.longitude * 3600);
var longDegrees = longSeconds / 3600;
longSeconds = abs(longSeconds % 3600);
var longMinutes = longSeconds / 60;
longSeconds %= 60;

    var result = (String(format: "%d°%d'%d\"%@ %d°%d'%d\"%@"),
abs(latDegrees),
latMinutes,
latSeconds,
latDegrees >= 0 ? "N" : "S",
abs(longDegrees),
longMinutes,
longSeconds,
longDegrees >= 0 ? "E" : "W",

return result;
}
</code>```

答:
I slightly modified Josue V.'s code to work in a timer that updates the location frequently

```<code>        if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() ==  .authorizedAlways){
        let currentLocation = locationManager.location
        var latitudeSeconds = currentLocation!.coordinate.latitude * 3600
        let latitudeDegrees = latitudeSeconds / 3600

            latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 3600)

        let latitudeMinutes = latitudeSeconds / 60

            latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 60)

        var longitudeSeconds = currentLocation!.coordinate.longitude * 3600
        let longitudeDegrees = longitudeSeconds / 3600

            longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 3600)

        let longitudeMinutes = longitudeSeconds / 60

            longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 60)

        let latitudeCardinalDirection = latitudeDegrees >= 0 ? "N" : "S"
        let longitudeCardinalDirection = longitudeDegrees >= 0 ? "E" : "W"

        let latitudeDescription = String(format:"%.2f°%.2f'%.2f\"%@",
                                         abs(latitudeDegrees), abs(latitudeMinutes),
                                         abs(latitudeSeconds), latitudeCardinalDirection)

        let longitudeDescription = String(format:"%.2f°%.2f'%.2f\"%@",
                                          abs(longitudeDegrees), abs(longitudeMinutes),
                                          abs(longitudeSeconds), longitudeCardinalDirection)

        cell5.text = latitudeDescription + " " + longitudeDescription

        }
    }
</code>```

and the timer

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(coordinate), userInfo: nil, repeats: true)

Body:
How can I covert this to swift? My best guess is that all the int get changed to a var. Removing all the @ that lead ".  Also if any can point me to a good source to learn how things convert that would great.

- (NSString*)coordinateString {

int latSeconds = (int)(self.latitude * 3600);
int latDegrees = latSeconds / 3600;
latSeconds = ABS(latSeconds % 3600);
int latMinutes = latSeconds / 60;
latSeconds %= 60;

int longSeconds = (int)(self.longitude * 3600);
int longDegrees = longSeconds / 3600;
longSeconds = ABS(longSeconds % 3600);
int longMinutes = longSeconds / 60;
longSeconds %= 60;

NSString* result = [NSString stringWithFormat:@"%d°%d'%d\"%@ %d°%d'%d\"%@",
                    ABS(latDegrees),
                    latMinutes,
                    latSeconds,
                    latDegrees >= 0 ? @"N" : @"S",
                    ABS(longDegrees),
                    longMinutes,
                    longSeconds,
                    longDegrees >= 0 ? @"E" : @"W"];

return result;
}

My attempt to convert it but Xcode proves me wrong. Reposted the fix suggest with the ABS. Does it look correct now?

func coordinateString {

var latSeconds = (Int8)(self.latitude * 3600);
var latDegrees = latSeconds / 3600;
latSeconds = abs(latSeconds % 3600);
var latMinutes = latSeconds / 60;
latSeconds %= 60;

var longSeconds = (Int8)(self.longitude * 3600);
var longDegrees = longSeconds / 3600;
longSeconds = abs(longSeconds % 3600);
var longMinutes = longSeconds / 60;
longSeconds %= 60;

    var result = (String(format: "%d°%d'%d\"%@ %d°%d'%d\"%@"),
abs(latDegrees),
latMinutes,
latSeconds,
latDegrees >= 0 ? "N" : "S",
abs(longDegrees),
longMinutes,
longSeconds,
longDegrees >= 0 ? "E" : "W",

return result;
}

Body:
I slightly modified Josue V.'s code to work in a timer that updates the location frequently

        if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
            CLLocationManager.authorizationStatus() ==  .authorizedAlways){
        let currentLocation = locationManager.location
        var latitudeSeconds = currentLocation!.coordinate.latitude * 3600
        let latitudeDegrees = latitudeSeconds / 3600

            latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 3600)

        let latitudeMinutes = latitudeSeconds / 60

            latitudeSeconds = latitudeSeconds.truncatingRemainder(dividingBy: 60)

        var longitudeSeconds = currentLocation!.coordinate.longitude * 3600
        let longitudeDegrees = longitudeSeconds / 3600

            longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 3600)

        let longitudeMinutes = longitudeSeconds / 60

            longitudeSeconds = longitudeSeconds.truncatingRemainder(dividingBy: 60)

        let latitudeCardinalDirection = latitudeDegrees >= 0 ? "N" : "S"
        let longitudeCardinalDirection = longitudeDegrees >= 0 ? "E" : "W"

        let latitudeDescription = String(format:"%.2f°%.2f'%.2f\"%@",
                                         abs(latitudeDegrees), abs(latitudeMinutes),
                                         abs(latitudeSeconds), latitudeCardinalDirection)

        let longitudeDescription = String(format:"%.2f°%.2f'%.2f\"%@",
                                          abs(longitudeDegrees), abs(longitudeMinutes),
                                          abs(longitudeSeconds), longitudeCardinalDirection)

        cell5.text = latitudeDescription + " " + longitudeDescription

        }
    }

and the timer

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(coordinate), userInfo: nil, repeats: true)


问:
How to automatically play next song on a list
I'm making a musicplayer for my downloaded songs. I got it to play the songs I select but I would like the next song to start automatically after the previous one ended.

I've tried using the PlayStateChange event but it doesn't seem to work, when trying to debug (F11) it just doesn't do anything after the song ended.

```<code>private void lstSongs_SelectedIndexChanged(object sender, EventArgs e)
        {
            index = lstSongs.SelectedIndex;
            axWindowsMediaPlayer1.URL = paths[lstSongs.SelectedIndex];

        }
</code>```

this is the code to play the selected song

```<code>void axWindowsMediaPlayer1_PlayStateChange()
        {
            index++;
            axWindowsMediaPlayer1.URL = paths[lstSongs.SelectedIndex];
        }
</code>```

this is the last thing I tried but it just doesn't execute that code

I expected it to just go to the next song on the list, I don't get any errors

答:
One way would be to build a playlist of all the songs instead of playing them one by one, that way the next song in the playlist would automatically play after the last one finishes:

```<code>WMPLib.IWMPPlaylist Playlist = axWindowsMediaPlayer1.newPlaylist("MyPlayList", "");
foreach(String song in lstSongs.Items)
{
    Playlist.appendItem(axWindowsMediaPlayer1.newMedia(song));
}
axWindowsMediaPlayer1.currentPlaylist = Playlist;
axWindowsMediaPlayer1.Ctlcontrols.play();
</code>```

It's unclear if you will have multiple selections in your listbox, or if you want to play all entries in the listbox.

You can get the currently playing song when it changes with:

```<code>private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
    if (e.newState == 3)
    {
        label1.Text = "Playing: " + axWindowsMediaPlayer1.Ctlcontrols.currentItem.name;
    }
}
</code>```

Body:
I'm making a musicplayer for my downloaded songs. I got it to play the songs I select but I would like the next song to start automatically after the previous one ended.

I've tried using the PlayStateChange event but it doesn't seem to work, when trying to debug (F11) it just doesn't do anything after the song ended.

private void lstSongs_SelectedIndexChanged(object sender, EventArgs e)
        {
            index = lstSongs.SelectedIndex;
            axWindowsMediaPlayer1.URL = paths[lstSongs.SelectedIndex];

        }

this is the code to play the selected song

void axWindowsMediaPlayer1_PlayStateChange()
        {
            index++;
            axWindowsMediaPlayer1.URL = paths[lstSongs.SelectedIndex];
        }

this is the last thing I tried but it just doesn't execute that code

I expected it to just go to the next song on the list, I don't get any errors

Body:
One way would be to build a playlist of all the songs instead of playing them one by one, that way the next song in the playlist would automatically play after the last one finishes:

WMPLib.IWMPPlaylist Playlist = axWindowsMediaPlayer1.newPlaylist("MyPlayList", "");
foreach(String song in lstSongs.Items)
{
    Playlist.appendItem(axWindowsMediaPlayer1.newMedia(song));
}
axWindowsMediaPlayer1.currentPlaylist = Playlist;
axWindowsMediaPlayer1.Ctlcontrols.play();

It's unclear if you will have multiple selections in your listbox, or if you want to play all entries in the listbox.

You can get the currently playing song when it changes with:

private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
    if (e.newState == 3)
    {
        label1.Text = "Playing: " + axWindowsMediaPlayer1.Ctlcontrols.currentItem.name;
    }
}


问:
Where does ".type" come from in ts-node?
I found this code on https://github.com/TypeStrong/ts-node:

const x = 10;
.type x

What is does is clear but i found nothing about it in official typescript documentation...

答:
That command is an extension registered in ts-node. In fact, it's the only such extension currently in ts-node.

The format (and additional commands such as .exit) comes from Node's built-in repl package, which ts-node consumes and extends.


问:
What does Dotty offer to replace type projections?
I have been reading about Dotty, since it looks like it is about to become scala 3, and noticed that type projections are deemed "unsound" and removed from the language ...

This seems like a bummer, as I have seen several use cases where they were really useful. For example:

```<code>trait Contents
class Foo extends Contents
class Bar extends Contents

trait Container[T <: Contents] { type ContentType = T }
class FooContainer extends Container[Foo]
class BarContainer extends Container[Bar]

trait Manager[T <: Container[_]] {
  type ContainerType = T
  type ContentType = T#ContentType
  def getContents: ContentType
  def createContainer(contents: ContentType): ContainerType
}
</code>```

How would one do something like this in Dotty? Add a second type parameter to Manager? But, aside from the fact that it makes it really tedious to create and manipulate instances of the Manager, it also doesn't quite work, as there is no way to enforce the relationship between the two types (Manager[FooContainer, Bar] should not be legal).

Then, there are other uses, like type lambdas, and partially applied types, that are useful for creating biased functors etc ... Or do these (partially applied types) become "first class citizens" in Dotty?

EDIT

To answer the question in the comments, here is a somewhat contrived example of his this may be used. Let's suppose, my Managers are actually Akka Actors:

```<code>abstract class BaseManager[T <: Container[_]](
  val storage: ContentStorage[T#ContentType]
) extends Actor with Manager[T] {
    def withContents(container: T, content: ContentType): ContainerType
    def withoutContents: T

    var container: T = withoutContents

    def receive: Receive {
       case ContentsChanged =>
          container = withContents(container, storage.get)
       case ContainerRequester =>
           sender ! container
       // ... other common actions
    }
}

class FooManager(storage: FooStorage) extends BaseManager[FooContainer](storage) {
   def withContents(container: FooContainer, content: Foo) =
       container.copy(Some(content))
   def withoutContent = FooContainer(None)

   override def receive: Receive = super.receive orElse {
    // some additional actions, specific to Foo
   }
}

case class FooContainer(content: Option[Foo]) extends Container[Foo]{
  // some extremely expensive calculations that happen when
  // content is assigned, so that we can cache the result in container
}
</code>```

答:
In Scala 2.12 type projections sometimes can be replaced with type class + path-dependent types

```<code>trait ContentType[T <: Container[_]] {
  type Out
}
object ContentType {
  type Aux[T <: Container[_], Out0] = ContentType[T] { type Out = Out0 }
  def instance[T <: Container[_], Out0]: Aux[T, Out0] = new ContentType[T] { type Out = Out0 }

  implicit def mk[T <: Contents]: Aux[Container[T], T] = instance
}

abstract class Manager[T <: Container[_]](implicit val contentType: ContentType[T]) {
  type ContainerType = T
  def getContents: contentType.Out
  def createContainer(contents: contentType.Out): ContainerType
}
</code>```

Checked in Dotty 0.16.0-bin-20190529-3361d44-NIGHTLY (in 0.16.0-RC3 delegate should be instead of implied)

```<code>trait Contents
class Foo extends Contents
class Bar extends Contents

trait Container[T <: Contents] { type ContentType = T }
class FooContainer extends Container[Foo]
class BarContainer extends Container[Bar]

trait ContentType[T <: Container[_]] {
  type Out
}
object ContentType {
  implied [T <: Contents] for ContentType[Container[T]] {
    type Out = T
  }
}

trait Manager[T <: Container[_]] given (val contentType: ContentType[T]) {
  type ContainerType = T
  type ContentType = contentType.Out
  def getContents: ContentType
  def createContainer(contents: ContentType): ContainerType
}
</code>```

One more option is to use match types

```<code>trait Contents
class Foo extends Contents
class Bar extends Contents

trait Container[T <: Contents] { type ContentType = T }
class FooContainer extends Container[Foo]
class BarContainer extends Container[Bar]

type ContentType[T <: Container[_]] = T match {
  case Container[t] => t
}

trait Manager[T <: Container[_]] {
  type ContainerType = T
  def getContents: ContentType[T]
  def createContainer(contents: ContentType[T]): ContainerType
}
</code>```

Body:
I have been reading about Dotty, since it looks like it is about to become scala 3, and noticed that type projections are deemed "unsound" and removed from the language ...

This seems like a bummer, as I have seen several use cases where they were really useful. For example:

trait Contents
class Foo extends Contents
class Bar extends Contents

trait Container[T <: Contents] { type ContentType = T }
class FooContainer extends Container[Foo]
class BarContainer extends Container[Bar]

trait Manager[T <: Container[_]] {
  type ContainerType = T
  type ContentType = T#ContentType
  def getContents: ContentType
  def createContainer(contents: ContentType): ContainerType
}

How would one do something like this in Dotty? Add a second type parameter to Manager? But, aside from the fact that it makes it really tedious to create and manipulate instances of the Manager, it also doesn't quite work, as there is no way to enforce the relationship between the two types (Manager[FooContainer, Bar] should not be legal).

Then, there are other uses, like type lambdas, and partially applied types, that are useful for creating biased functors etc ... Or do these (partially applied types) become "first class citizens" in Dotty?

EDIT

To answer the question in the comments, here is a somewhat contrived example of his this may be used. Let's suppose, my Managers are actually Akka Actors:

abstract class BaseManager[T <: Container[_]](
  val storage: ContentStorage[T#ContentType]
) extends Actor with Manager[T] {
    def withContents(container: T, content: ContentType): ContainerType
    def withoutContents: T

    var container: T = withoutContents

    def receive: Receive {
       case ContentsChanged =>
          container = withContents(container, storage.get)
       case ContainerRequester =>
           sender ! container
       // ... other common actions
    }
}

class FooManager(storage: FooStorage) extends BaseManager[FooContainer](storage) {
   def withContents(container: FooContainer, content: Foo) =
       container.copy(Some(content))
   def withoutContent = FooContainer(None)

   override def receive: Receive = super.receive orElse {
    // some additional actions, specific to Foo
   }
}

case class FooContainer(content: Option[Foo]) extends Container[Foo]{
  // some extremely expensive calculations that happen when
  // content is assigned, so that we can cache the result in container
}

Body:
In Scala 2.12 type projections sometimes can be replaced with type class + path-dependent types

trait ContentType[T <: Container[_]] {
  type Out
}
object ContentType {
  type Aux[T <: Container[_], Out0] = ContentType[T] { type Out = Out0 }
  def instance[T <: Container[_], Out0]: Aux[T, Out0] = new ContentType[T] { type Out = Out0 }

  implicit def mk[T <: Contents]: Aux[Container[T], T] = instance
}

abstract class Manager[T <: Container[_]](implicit val contentType: ContentType[T]) {
  type ContainerType = T
  def getContents: contentType.Out
  def createContainer(contents: contentType.Out): ContainerType
}

Checked in Dotty 0.16.0-bin-20190529-3361d44-NIGHTLY (in 0.16.0-RC3 delegate should be instead of implied)

trait Contents
class Foo extends Contents
class Bar extends Contents

trait Container[T <: Contents] { type ContentType = T }
class FooContainer extends Container[Foo]
class BarContainer extends Container[Bar]

trait ContentType[T <: Container[_]] {
  type Out
}
object ContentType {
  implied [T <: Contents] for ContentType[Container[T]] {
    type Out = T
  }
}

trait Manager[T <: Container[_]] given (val contentType: ContentType[T]) {
  type ContainerType = T
  type ContentType = contentType.Out
  def getContents: ContentType
  def createContainer(contents: ContentType): ContainerType
}

One more option is to use match types

trait Contents
class Foo extends Contents
class Bar extends Contents

trait Container[T <: Contents] { type ContentType = T }
class FooContainer extends Container[Foo]
class BarContainer extends Container[Bar]

type ContentType[T <: Container[_]] = T match {
  case Container[t] => t
}

trait Manager[T <: Container[_]] {
  type ContainerType = T
  def getContents: ContentType[T]
  def createContainer(contents: ContentType[T]): ContainerType
}


问:
Getting current directory in VBScript
I'm trying to get the current directory and use it to run an application no matter where the file is put and no matter how the path is changed

```<code>Dim fso: set fso = CreateObject("Scripting.FileSystemObject")
Dim CurrentDirectory
CurrentDirectory = fso.GetAbsolutePathName(".")
Dim Directory
Directory = CurrentDirectory\attribute.exe

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "Directory" & Chr(34), 0
Set WinScriptHost = Nothing
</code>```

How do I actually set up this code so it does what I want it to do correctly?

答:
Use With in the code.

Try this way :

```<code>''''Way 1

currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))

''''Way 2

With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With

''''Way 3

With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With
</code>```

Title: Getting current directory in VBScript

Body:
I'm trying to get the current directory and use it to run an application no matter where the file is put and no matter how the path is changed

Dim fso: set fso = CreateObject("Scripting.FileSystemObject")
Dim CurrentDirectory
CurrentDirectory = fso.GetAbsolutePathName(".")
Dim Directory
Directory = CurrentDirectory\attribute.exe

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "Directory" & Chr(34), 0
Set WinScriptHost = Nothing

How do I actually set up this code so it does what I want it to do correctly?

Body:
Use With in the code.

Try this way :

''''Way 1

currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))

''''Way 2

With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With

''''Way 3

With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With


问:
Calculate recall for each class after each epoch in Tensorflow 2
I am trying to calculate the recall in both binary and multi class (one hot encoded) classification scenarios for each class after each epoch in a model that uses Tensorflow 2's Keras API. e.g. for binary classification I'd like to be able to do something like

import tensorflow as tf
model = tf.keras.Sequential()
model.add(...)
model.add(tf.keras.layers.Dense(1))

model.compile(metrics=[binary_recall(label=0), binary_recall(label=1)], ...)
history = model.fit(...)

plt.plot(history.history['binary_recall_0'])
plt.plot(history.history['binary_recall_1'])
plt.show()
```

<p>or in a multi class scenario I'd like to do something like</p>

<pre class="lang-py prettyprint-override"><code>model = tf.keras.Sequential()
model.add(...)
model.add(tf.keras.layers.Dense(3))

model.compile(metrics=[recall(label=0), recall(label=1), recall(label=2)], ...)
history = model.fit(...)

plt.plot(history.history['recall_0'])
plt.plot(history.history['recall_1'])
plt.plot(history.history['recall_2'])
plt.show()
</code>```

I'm working on a classifier for an unbalanced dataset and want to be able to see at what point the recall for my minority class(s) starts to degrade.

I found an implementation of precision for a specific class in a multi-class classifier here https://stackoverflow.com/a/41717938/373655. I'm am trying to adapt this into what I need but keras.backend is still pretty foreign to me so any help would be greatly appreciated.

I am also not clear on if I can use Keras metrics (as they are calculated at the end of each batch and then averaged) or if I need to use Keras callbacks (which can run at the end of each epoch). It seems to me like it shouldn't make a difference for recall (e.g. 8/10 == (3/5 + 5/5) / 2) but this is why recall was removed in Keras 2 so maybe I'm missing something (https://github.com/keras-team/keras/issues/5794)

Edit - partial solution (multi-class classification)
@mujjiga's solution works for both binary classification and multi-class classification but as @P-Gn pointed out, tensorflow 2's Recall metric supports this out of the box for multi-class classification. e.g.

```<code>from tensorflow.keras.metrics import Recall

model = ...

model.compile(loss='categorical_crossentropy', metrics=[
    Recall(class_id=0, name='recall_0')
    Recall(class_id=1, name='recall_1')
    Recall(class_id=2, name='recall_2')
])

history = model.fit(...)

plt.plot(history.history['recall_2'])
plt.plot(history.history['val_recall_2'])
plt.show()
</code>```

答:
There are multiple ways to do this but using a callback seems the best and most kerasy way of doing it. One side-note before I show you how:

I am also not clear on if I can use Keras metrics (as they are
  calculated at the end of each batch and then averaged) or if I need to
  use Keras callbacks (which can run at the end of each epoch).

This is not true. Keras' callbacks can use the following methods:

on_epoch_begin: called at the beginning of every epoch.

on_epoch_end: called at the end of every epoch.

on_batch_begin: called at the beginning of every batch.

on_batch_end: called at the end of every batch.

on_train_begin: called at the beginning of model training.

on_train_end: called at the end of model training.

This is true regardless of whether you are using keras or tf.keras.

Below you can find my implementation of a custom callback.

```<code>class RecallHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.recall = {}

    def on_epoch_end(self, epoch, logs={}):
        # Compute and store recall for each class here.
        self.recall[...] = 42

history = RecallHistory()
model.fit(..., callbacks=[history])

print(history.recall)
</code>```

Body:
I am trying to calculate the recall in both binary and multi class (one hot encoded) classification scenarios for each class after each epoch in a model that uses Tensorflow 2's Keras API. e.g. for binary classification I'd like to be able to do something like

import tensorflow as tf
model = tf.keras.Sequential()
model.add(...)
model.add(tf.keras.layers.Dense(1))

model.compile(metrics=[binary_recall(label=0), binary_recall(label=1)], ...)
history = model.fit(...)

plt.plot(history.history['binary_recall_0'])
plt.plot(history.history['binary_recall_1'])
plt.show()

or in a multi class scenario I'd like to do something like

model = tf.keras.Sequential()
model.add(...)
model.add(tf.keras.layers.Dense(3))

model.compile(metrics=[recall(label=0), recall(label=1), recall(label=2)], ...)
history = model.fit(...)

plt.plot(history.history['recall_0'])
plt.plot(history.history['recall_1'])
plt.plot(history.history['recall_2'])
plt.show()

I'm working on a classifier for an unbalanced dataset and want to be able to see at what point the recall for my minority class(s) starts to degrade.

I found an implementation of precision for a specific class in a multi-class classifier here https://stackoverflow.com/a/41717938/373655. I'm am trying to adapt this into what I need but keras.backend is still pretty foreign to me so any help would be greatly appreciated.

I am also not clear on if I can use Keras metrics (as they are calculated at the end of each batch and then averaged) or if I need to use Keras callbacks (which can run at the end of each epoch). It seems to me like it shouldn't make a difference for recall (e.g. 8/10 == (3/5 + 5/5) / 2) but this is why recall was removed in Keras 2 so maybe I'm missing something (https://github.com/keras-team/keras/issues/5794)

Edit - partial solution (multi-class classification)
@mujjiga's solution works for both binary classification and multi-class classification but as @P-Gn pointed out, tensorflow 2's Recall metric supports this out of the box for multi-class classification. e.g.

from tensorflow.keras.metrics import Recall

model = ...

model.compile(loss='categorical_crossentropy', metrics=[
    Recall(class_id=0, name='recall_0')
    Recall(class_id=1, name='recall_1')
    Recall(class_id=2, name='recall_2')
])

history = model.fit(...)

plt.plot(history.history['recall_2'])
plt.plot(history.history['val_recall_2'])
plt.show()

Body:
There are multiple ways to do this but using a callback seems the best and most kerasy way of doing it. One side-note before I show you how:

I am also not clear on if I can use Keras metrics (as they are
  calculated at the end of each batch and then averaged) or if I need to
  use Keras callbacks (which can run at the end of each epoch).

This is not true. Keras' callbacks can use the following methods:

on_epoch_begin: called at the beginning of every epoch.

on_epoch_end: called at the end of every epoch.

on_batch_begin: called at the beginning of every batch.

on_batch_end: called at the end of every batch.

on_train_begin: called at the beginning of model training.

on_train_end: called at the end of model training.

This is true regardless of whether you are using keras or tf.keras.

Below you can find my implementation of a custom callback.

class RecallHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.recall = {}

    def on_epoch_end(self, epoch, logs={}):
        # Compute and store recall for each class here.
        self.recall[...] = 42

history = RecallHistory()
model.fit(..., callbacks=[history])

print(history.recall)


问:
python split string by delimiter only it is outside of quotes
My string has the following format:

```<code>string = 'token1 -token2 +"token 3"'
</code>```

I want to extract the tokens and fields as follows:

```<code>result = [
    'token1',
    '-token2',
    '+token 3'
]
</code>```

I am using the csv module for that but unsuccessfully getting the last token as '+"token', '3"'

```<code># for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

tokens = csv.reader(f, delimiter=' ', doublequote=False, quotechar='"', quoting=csv.QUOTE_NONE)

for t in tokens: print(t)
# > ['token1', '-token2', '+"token', '3"']
</code>```

答:
I wrote a customer splitter for this specific case, since the format was too specific. The below code works fine for the provided inputs.

```<code># for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

def check_and_split(line):
    tokens = []
    is_quote = False
    token = ''
    for c in line:
        if c == ' ' and (not is_quote):
            is_quote = False
            tokens.append(token)
            token = ''
        elif c == '"':
            is_quote = True
        else:
            token += c
    tokens.append(token)
    return tokens

for line in f:
    tokens = check_and_split(line)
    for t in tokens:
        print(t)
</code>```

Output:

```<code>token1
-token2
+token 3
</code>```

Body:
My string has the following format:

string = 'token1 -token2 +"token 3"'

I want to extract the tokens and fields as follows:

result = [
    'token1',
    '-token2',
    '+token 3'
]

I am using the csv module for that but unsuccessfully getting the last token as '+"token', '3"'

# for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

tokens = csv.reader(f, delimiter=' ', doublequote=False, quotechar='"', quoting=csv.QUOTE_NONE)

for t in tokens: print(t)
# > ['token1', '-token2', '+"token', '3"']

Body:
I wrote a customer splitter for this specific case, since the format was too specific. The below code works fine for the provided inputs.

# for Python 2.x
try: from StringIO import StringIO
# for Python 3.x
except ImportError: from io import StringIO
import csv

f = StringIO('token1 -token2 +"token 3"')

def check_and_split(line):
    tokens = []
    is_quote = False
    token = ''
    for c in line:
        if c == ' ' and (not is_quote):
            is_quote = False
            tokens.append(token)
            token = ''
        elif c == '"':
            is_quote = True
        else:
            token += c
    tokens.append(token)
    return tokens

for line in f:
    tokens = check_and_split(line)
    for t in tokens:
        print(t)

Output:

token1
-token2
+token 3


问:
CSS positioning of a text and underline
I'm trying to achieve the following effect, but I have some trouble positioning the text and making the underline go to end of the screen.

.header {
  height: 550px;
  width: 100%;
  background-color: #1F2041;
  position: relative;
}

.header h1, .header h2{
  color: white;
  font-size: 52px;
  text-transform: uppercase;
  margin-bottom: 20px;
  border-bottom: 1.5px solid currentColor;
  line-height: 0.7;
  position: absolute;
  top: 210px;
}

.header p {
  margin-top: 40px;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h2>About</h2>
  <h2>Nikola</h2>
  <p>Simple. Modern. Yours.</p>
</div></code>```

This is what I'm trying to achieve

答:
Try something like this, using float and clear. Adjust the size of the 400px as you prefer. Perhaps this way (float) is not the best way and using solely margins may be preferred, but try to avoid using position: absolute or elements can overlap quickly.

.header {
    height: 550px;
    width: 100%;
    background-color: #1F2041;
    text-align: right;
}
.header * {
    float: right;
    clear: right;
    width: 400px;
    text-align: left;
    color: white;
    margin: 0 0 20px;
}

.header h1, .header h2{
    color: white;
    font-size: 52px;
    text-transform: uppercase;
    border-bottom: 1.5px solid currentColor;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    <h2>About</h2>
    <h2>Nikola</h2>
    <p>Simple. Modern. Yours.</p>
</div></code>```

Title: CSS positioning of a text and underline

Body:
I'm trying to achieve the following effect, but I have some trouble positioning the text and making the underline go to end of the screen.

.header {
  height: 550px;
  width: 100%;
  background-color: #1F2041;
  position: relative;
}

.header h1, .header h2{
  color: white;
  font-size: 52px;
  text-transform: uppercase;
  margin-bottom: 20px;
  border-bottom: 1.5px solid currentColor;
  line-height: 0.7;
  position: absolute;
  top: 210px;
}

.header p {
  margin-top: 40px;
  color: white;
}

About

Nikola

Simple. Modern. Yours.

This is what I'm trying to achieve

Body:
Try something like this, using float and clear. Adjust the size of the 400px as you prefer. Perhaps this way (float) is not the best way and using solely margins may be preferred, but try to avoid using position: absolute or elements can overlap quickly.

.header {
    height: 550px;
    width: 100%;
    background-color: #1F2041;
    text-align: right;
}
.header * {
    float: right;
    clear: right;
    width: 400px;
    text-align: left;
    color: white;
    margin: 0 0 20px;
}

.header h1, .header h2{
    color: white;
    font-size: 52px;
    text-transform: uppercase;
    border-bottom: 1.5px solid currentColor;
}

<div class="header">
    <h2>About</h2>
    <h2>Nikola</h2>
    <p>Simple. Modern. Yours.</p>
</div>


问:
UISearchBar not changing search icon and placeholder color for iOS 12.1
I have tried every approach to change the color of search icon and placeholder text search bar but nothing worked. Can anyone please help me out!

This is the implementation I am following for search bar.

```<code>func configureSearchBar() {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchBar.delegate = self

    searchController.searchBar.tintColor = .white
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.searchBarStyle = .default
    navigationItem.searchController = searchController

    let textFieldInsideSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideSearchBar?.attributedPlaceholder = NSAttributedString(string: "Suche", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

    searchController.searchBar.setText(color: .white)
    searchController.searchBar.setTextField(color: UIColor.white.withAlphaComponent(0.2))
    searchController.searchBar.setPlaceholderText(color: .white)
    searchController.searchBar.setSearchImage(color: .white)
    searchController.searchBar.setClearButton(color: .white)
}

extension UISearchBar {

func getTextField() -> UITextField? { return value(forKey: "searchField") as? UITextField }
func setText(color: UIColor) { if let textField = getTextField() { textField.textColor = color } }
func setPlaceholderText(color: UIColor) { getTextField()?.setPlaceholderText(color: color) }
func setClearButton(color: UIColor) { getTextField()?.setClearButton(color: color) }

func setTextField(color: UIColor) {
    guard let textField = getTextField() else { return }
    switch searchBarStyle {
    case .minimal:
        textField.backgroundColor = color
        textField.layer.backgroundColor = color.cgColor
        textField.layer.cornerRadius = 6
    case .prominent, .default: textField.backgroundColor = color
    @unknown default: break
    }
}

func setSearchImage(color: UIColor) {
    guard let imageView = getTextField()?.leftView as? UIImageView else { return }
    imageView.tintColor = color
    imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
}
</code>```

}

答:
Try this way it change the seachbar placeholder color

```<code>     var searchTextField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
        if searchTextField!.responds(to: #selector(getter: UITextField.attributedPlaceholder)) {
            let attributeDict = [NSForegroundColorAttributeName: UIColor.white]
            searchTextField!.attributedPlaceholder = NSAttributedString(string: "Search", attributes: attributeDict)
        }
</code>```

OR

```<code>  extension UISearchBar
{

    func setMagnifyingGlassColorTo(color: UIColor)
    {
        // Search Icon
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView
        glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
        glassIconView?.tintColor = color
    }

    func setClearButtonColorTo(color: UIColor)
    {
        // Clear Button
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let crossIconView = textFieldInsideSearchBar?.value(forKey: "clearButton") as? UIButton
        crossIconView?.setImage(crossIconView?.currentImage?.withRenderingMode(.alwaysTemplate), for: .normal)
        crossIconView?.tintColor = color
    }

    func setPlaceholderTextColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = color
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = color
    }
}
</code>```

Body:
I have tried every approach to change the color of search icon and placeholder text search bar but nothing worked. Can anyone please help me out!

This is the implementation I am following for search bar.

func configureSearchBar() {
    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchBar.delegate = self

    searchController.searchBar.tintColor = .white
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.searchBarStyle = .default
    navigationItem.searchController = searchController

    let textFieldInsideSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideSearchBar?.attributedPlaceholder = NSAttributedString(string: "Suche", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

    searchController.searchBar.setText(color: .white)
    searchController.searchBar.setTextField(color: UIColor.white.withAlphaComponent(0.2))
    searchController.searchBar.setPlaceholderText(color: .white)
    searchController.searchBar.setSearchImage(color: .white)
    searchController.searchBar.setClearButton(color: .white)
}

extension UISearchBar {

func getTextField() -> UITextField? { return value(forKey: "searchField") as? UITextField }
func setText(color: UIColor) { if let textField = getTextField() { textField.textColor = color } }
func setPlaceholderText(color: UIColor) { getTextField()?.setPlaceholderText(color: color) }
func setClearButton(color: UIColor) { getTextField()?.setClearButton(color: color) }

func setTextField(color: UIColor) {
    guard let textField = getTextField() else { return }
    switch searchBarStyle {
    case .minimal:
        textField.backgroundColor = color
        textField.layer.backgroundColor = color.cgColor
        textField.layer.cornerRadius = 6
    case .prominent, .default: textField.backgroundColor = color
    @unknown default: break
    }
}

func setSearchImage(color: UIColor) {
    guard let imageView = getTextField()?.leftView as? UIImageView else { return }
    imageView.tintColor = color
    imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
}

}

Body:
Try this way it change the seachbar placeholder color

     var searchTextField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
        if searchTextField!.responds(to: #selector(getter: UITextField.attributedPlaceholder)) {
            let attributeDict = [NSForegroundColorAttributeName: UIColor.white]
            searchTextField!.attributedPlaceholder = NSAttributedString(string: "Search", attributes: attributeDict)
        }

OR

  extension UISearchBar
{

    func setMagnifyingGlassColorTo(color: UIColor)
    {
        // Search Icon
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView
        glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
        glassIconView?.tintColor = color
    }

    func setClearButtonColorTo(color: UIColor)
    {
        // Clear Button
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let crossIconView = textFieldInsideSearchBar?.value(forKey: "clearButton") as? UIButton
        crossIconView?.setImage(crossIconView?.currentImage?.withRenderingMode(.alwaysTemplate), for: .normal)
        crossIconView?.tintColor = color
    }

    func setPlaceholderTextColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = color
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = color
    }
}


问:
Can't add data from json in ArrayList
I'm trying to display data from JSON in listView, but whenever I'll try to add some value from json, my list shows me nothing.

Activity

```<code>public static final String LOG = hourlyWeather.class.getSimpleName();
    double test;
    RequestQueue mQuene;
    ArrayList<Weather> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hourly_weather);
        mQuene =  Volley.newRequestQueue(this);

        list = new ArrayList<Weather>();
        test();

        hourlyWeatherAdapter adapter = new hourlyWeatherAdapter(this, list);

        ListView listView = (ListView) findViewById(R.id.weatherListView);

        listView.setAdapter(adapter);
    }
    public void test() {
        String url = "https://api.openweathermap.org/data/2.5/weather?lat=50.7578594&lon=16.2127653&units=metric&appid=ID";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                response -> {
                    try {
                        JSONObject object = response.getJSONObject("main");
                        for (int i = 0; i<object.length(); i++){
                            test = object.getDouble("temp");
                        }
                        Log.i(LOG,String.valueOf(test));
                        list.add(new Weather(test));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, Throwable::printStackTrace);
        mQuene.add(request);
    }
}
</code>```

Adapter

```<code>public class hourlyWeatherAdapter extends ArrayAdapter<Weather> {

public hourlyWeatherAdapter(@NonNull Context context, ArrayList<Weather> list) {
    super(context, 0, list);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    View view = convertView;
    if (view == null) {
        view = LayoutInflater.from(getContext()).inflate(R.layout.weather_list_item, parent, false);
    }
    Weather model = getItem(position);

    TextView temperature = (TextView) view.findViewById(R.id.hourly_time);
    temperature.append(String.valueOf(model.getTemp()));

    return view;
 }
}

public class Weather {

private double temp;

public Weather(double temp) {
    this.temp = temp;
}

public double getTemp() {
    return temp;
 }
}
</code>```

When I'll using the Log.i, I can clearly see value from json in my logcat. Where can be issue? I've tried to add some dummy data, and it works out just fine.

答:
You must declare hourlyWeatherAdapter adapter = new hourlyWeatherAdapter(this, list); outside your onCreate() method, and after change your array, you must call notifyDataSetChanged();. Also, you must initialize your list and adapter before call test().

```<code>public static final String LOG = hourlyWeather.class.getSimpleName();
    double test;
    RequestQueue mQuene;
    ArrayList<Weather> list;
    hourlyWeatherAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hourly_weather);
        mQuene =  Volley.newRequestQueue(this);

        list = new ArrayList<Weather>();
        adapter = new hourlyWeatherAdapter(this, list);

        ListView listView = (ListView) findViewById(R.id.weatherListView);
        listView.setAdapter(adapter);

        test();
    }

    public void test() {
        String url = "https://api.openweathermap.org/data/2.5/weather?lat=50.7578594&lon=16.2127653&units=metric&appid=ID";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            response -> {
                try {
                    JSONObject object = response.getJSONObject("main");
                    for (int i = 0; i<object.length(); i++){
                        test = object.getDouble("temp");
                    }
                    Log.i(LOG,String.valueOf(test));
                    list.add(new Weather(test));

                    // Update list
                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, Throwable::printStackTrace);
       mQuene.add(request);
    }
}
</code>```

Title: Can't add data from json in ArrayList

Body:
I'm trying to display data from JSON in listView, but whenever I'll try to add some value from json, my list shows me nothing.

Activity

public static final String LOG = hourlyWeather.class.getSimpleName();
    double test;
    RequestQueue mQuene;
    ArrayList<Weather> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hourly_weather);
        mQuene =  Volley.newRequestQueue(this);

        list = new ArrayList<Weather>();
        test();

        hourlyWeatherAdapter adapter = new hourlyWeatherAdapter(this, list);

        ListView listView = (ListView) findViewById(R.id.weatherListView);

        listView.setAdapter(adapter);
    }
    public void test() {
        String url = "https://api.openweathermap.org/data/2.5/weather?lat=50.7578594&lon=16.2127653&units=metric&appid=ID";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                response -> {
                    try {
                        JSONObject object = response.getJSONObject("main");
                        for (int i = 0; i<object.length(); i++){
                            test = object.getDouble("temp");
                        }
                        Log.i(LOG,String.valueOf(test));
                        list.add(new Weather(test));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, Throwable::printStackTrace);
        mQuene.add(request);
    }
}

Adapter

public class hourlyWeatherAdapter extends ArrayAdapter<Weather> {

public hourlyWeatherAdapter(@NonNull Context context, ArrayList<Weather> list) {
    super(context, 0, list);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    View view = convertView;
    if (view == null) {
        view = LayoutInflater.from(getContext()).inflate(R.layout.weather_list_item, parent, false);
    }
    Weather model = getItem(position);

    TextView temperature = (TextView) view.findViewById(R.id.hourly_time);
    temperature.append(String.valueOf(model.getTemp()));

    return view;
 }
}

public class Weather {

private double temp;

public Weather(double temp) {
    this.temp = temp;
}

public double getTemp() {
    return temp;
 }
}

When I'll using the Log.i, I can clearly see value from json in my logcat. Where can be issue? I've tried to add some dummy data, and it works out just fine.

Body:
You must declare hourlyWeatherAdapter adapter = new hourlyWeatherAdapter(this, list); outside your onCreate() method, and after change your array, you must call notifyDataSetChanged();. Also, you must initialize your list and adapter before call test().

public static final String LOG = hourlyWeather.class.getSimpleName();
    double test;
    RequestQueue mQuene;
    ArrayList<Weather> list;
    hourlyWeatherAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hourly_weather);
        mQuene =  Volley.newRequestQueue(this);

        list = new ArrayList<Weather>();
        adapter = new hourlyWeatherAdapter(this, list);

        ListView listView = (ListView) findViewById(R.id.weatherListView);
        listView.setAdapter(adapter);

        test();
    }

    public void test() {
        String url = "https://api.openweathermap.org/data/2.5/weather?lat=50.7578594&lon=16.2127653&units=metric&appid=ID";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            response -> {
                try {
                    JSONObject object = response.getJSONObject("main");
                    for (int i = 0; i<object.length(); i++){
                        test = object.getDouble("temp");
                    }
                    Log.i(LOG,String.valueOf(test));
                    list.add(new Weather(test));

                    // Update list
                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, Throwable::printStackTrace);
       mQuene.add(request);
    }
}


问:
C# VS 2010 reports error while editing but it compiles and runs successfully
I have optional parameters generated by CodeDom. For example:

```<code>class Square
{
    public Square([Optional()] int side) { }
}
</code>```

I have a call statement:

```<code>Square sq = new Square();
</code>```

While I'm editing, my Error List window shows:
    'Square' does not contain a constructor that takes 0 arguments'

But it compiles and runs successfully. How can I get rid of the error in 'Error List' window? Thanks!

答:
What you're seeing is the difference between IDE live semantic error checking and the actual compiler running.  The live semantic checking uses the C# compiler but doesn't have 100% parity with it and it can produce false positives in corner cases of the language.

To get rid of this disable live semantic checking

Tools -> Options

Text Editor -> C# -> Advanced

Uncheck "Show live semantic errors"

Another way to fix this is to use the actual C# supported syntax for optional values

```<code>public Square(int side = 0) { }
</code>```

Body:
I have optional parameters generated by CodeDom. For example:

class Square
{
    public Square([Optional()] int side) { }
}

I have a call statement:

Square sq = new Square();

While I'm editing, my Error List window shows:
    'Square' does not contain a constructor that takes 0 arguments'

But it compiles and runs successfully. How can I get rid of the error in 'Error List' window? Thanks!

Body:
What you're seeing is the difference between IDE live semantic error checking and the actual compiler running.  The live semantic checking uses the C# compiler but doesn't have 100% parity with it and it can produce false positives in corner cases of the language.

To get rid of this disable live semantic checking

Tools -> Options

Text Editor -> C# -> Advanced

Uncheck "Show live semantic errors"

Another way to fix this is to use the actual C# supported syntax for optional values

public Square(int side = 0) { }


问:
Filtering pandas dataframe by date to count views for timeline of programs
I need to count viewers by program for a streaming channel from a json logfile.
I identify the programs by their starttimes, such as:

So far I have two Dataframes like this:

The first one contains all the timestamps from the logfile

```<code>viewers_from_log = pd.read_json('sqllog.json', encoding='UTF-8')
# Convert date string to pandas datetime object:
viewers_from_log['time'] = pd.to_datetime(viewers_from_log['time'])
</code>```

Source JSON file:

```<code>[
    {
        "logid": 191605,
        "time": "0:00:17"
    },
    {
        "logid": 191607,
        "time": "0:00:26"
    },
    {
        "logid": 191611,
        "time": "0:01:20"
    }
]
</code>```

The second contains the starting times and titles of the programs

```<code>programs_start_time = pd.DataFrame.from_dict('programs.json', orient='index')
</code>```

Source JSON file:

```<code>{
    "2019-05-29": [
        {
            "title": "\"Amiről a kövek mesélnek\"",
            "startTime_dt": "2019-05-29T00:00:40Z"
        },
        {
            "title": "Koffer - Kedvcsináló Kul(t)túrák Külföldön",
            "startTime_dt": "2019-05-29T00:22:44Z"
        },
        {
            "title": "Gubancok",
            "startTime_dt": "2019-05-29T00:48:08Z"
        }
    ]
}
</code>```

So what I need to do is to count the entries / program in the log file and link them to the program titles.

答:
My approach is to slice log data for each date range from program data and get the shape. Next add column for program data with results:

```<code>import pandas as pd

# setup test data
log_data = {'Time': ['2019-05-30 00:00:26', '2019-05-30 00:00:50', '2019-05-30 00:05:50','2019-05-30 00:23:26']}
log_data = pd.DataFrame(data=log_data)

program_data = {'Time': ['2019-05-30 00:00:00', '2019-05-30 00:22:44'],
            'Program': ['Program 1', 'Program 2']}
program_data = pd.DataFrame(data=program_data)

counts = []
for index, row in program_data.iterrows():
    # get counts on selected range
    try:
        log_range = log_data[(log_data['Time'] > program_data.loc[index].values[0]) & (log_data['Time'] < program_data.loc[index+1].values[0])]
        counts.append(log_range.shape[0])
    except:
        log_range = log_data[log_data['Time'] > program_data.loc[index].values[0]]
        counts.append(log_range.shape[0])

 # add aditional column with collected counts
 program_data['Counts'] = counts
</code>```

Output:

```<code>                  Time    Program  Counts
 0  2019-05-30 00:00:00  Program 1       3
 1  2019-05-30 00:22:44  Program 2       1
</code>```

Body:
I need to count viewers by program for a streaming channel from a json logfile.
I identify the programs by their starttimes, such as:

So far I have two Dataframes like this:

The first one contains all the timestamps from the logfile

viewers_from_log = pd.read_json('sqllog.json', encoding='UTF-8')
# Convert date string to pandas datetime object:
viewers_from_log['time'] = pd.to_datetime(viewers_from_log['time'])

Source JSON file:

[
    {
        "logid": 191605,
        "time": "0:00:17"
    },
    {
        "logid": 191607,
        "time": "0:00:26"
    },
    {
        "logid": 191611,
        "time": "0:01:20"
    }
]

The second contains the starting times and titles of the programs

programs_start_time = pd.DataFrame.from_dict('programs.json', orient='index')

Source JSON file:

{
    "2019-05-29": [
        {
            "title": "\"Amiről a kövek mesélnek\"",
            "startTime_dt": "2019-05-29T00:00:40Z"
        },
        {
            "title": "Koffer - Kedvcsináló Kul(t)túrák Külföldön",
            "startTime_dt": "2019-05-29T00:22:44Z"
        },
        {
            "title": "Gubancok",
            "startTime_dt": "2019-05-29T00:48:08Z"
        }
    ]
}

So what I need to do is to count the entries / program in the log file and link them to the program titles.

Body:
My approach is to slice log data for each date range from program data and get the shape. Next add column for program data with results:

import pandas as pd

# setup test data
log_data = {'Time': ['2019-05-30 00:00:26', '2019-05-30 00:00:50', '2019-05-30 00:05:50','2019-05-30 00:23:26']}
log_data = pd.DataFrame(data=log_data)

program_data = {'Time': ['2019-05-30 00:00:00', '2019-05-30 00:22:44'],
            'Program': ['Program 1', 'Program 2']}
program_data = pd.DataFrame(data=program_data)

counts = []
for index, row in program_data.iterrows():
    # get counts on selected range
    try:
        log_range = log_data[(log_data['Time'] > program_data.loc[index].values[0]) & (log_data['Time'] < program_data.loc[index+1].values[0])]
        counts.append(log_range.shape[0])
    except:
        log_range = log_data[log_data['Time'] > program_data.loc[index].values[0]]
        counts.append(log_range.shape[0])

 # add aditional column with collected counts
 program_data['Counts'] = counts

Output:

                  Time    Program  Counts
 0  2019-05-30 00:00:00  Program 1       3
 1  2019-05-30 00:22:44  Program 2       1


问:
Build Nested structure using BeamSQL
In BigQuery we have "ARRAY_AGG" function which helps to convert the normal collection to Nested collection. Is there a similar way to build same kind of nested structure collection using BeamSQL?. Something like below query in BeamSQL,

"Select column1, ARRAY_AGG(STRUCT(column2, column3)) from PCOLLECTION Group by Column1"

答:
If I understood your question correctly, you should be able to use ARRAY constructor like "SELECT ARRAY[1, 2, 3] f_arr", this passes:

  @Test
  public void testArrayConstructor() {
    BeamSqlEnv sqlEnv = BeamSqlEnv.inMemory(readOnlyTableProvider);
    PCollection<Row> stream =
        BeamSqlRelUtils.toPCollection(pipeline, sqlEnv.parseQuery("SELECT ARRAY[1, 2, 3] f_arr"));
    PAssert.that(stream)
        .containsInAnyOrder(
            Row.withSchema(Schema.builder().addArrayField("f_arr", FieldType.INT32).build())
                .addValue(Arrays.asList(1, 2, 3))
                .build());
    pipeline.run().waitUntilFinish(Duration.standardMinutes(2));
  }
```

See also:

Calcite SQL reference guide (it is the parser used by Beam SQL);

Beam complex types test;

Beam nested rows test

Title: Build Nested structure using BeamSQL

Body:
If I understood your question correctly, you should be able to use ARRAY constructor like "SELECT ARRAY[1, 2, 3] f_arr", this passes:

  @Test
  public void testArrayConstructor() {
    BeamSqlEnv sqlEnv = BeamSqlEnv.inMemory(readOnlyTableProvider);
    PCollection<Row> stream =
        BeamSqlRelUtils.toPCollection(pipeline, sqlEnv.parseQuery("SELECT ARRAY[1, 2, 3] f_arr"));
    PAssert.that(stream)
        .containsInAnyOrder(
            Row.withSchema(Schema.builder().addArrayField("f_arr", FieldType.INT32).build())
                .addValue(Arrays.asList(1, 2, 3))
                .build());
    pipeline.run().waitUntilFinish(Duration.standardMinutes(2));
  }

See also:

Calcite SQL reference guide (it is the parser used by Beam SQL);

Beam complex types test;

Beam nested rows test


问:
Missing Script Start
I'm trying to run this example. I have these errors when I start running it:

npm ERR! missing script: start

npm ERR! A complete log of this run can be found in:

npm ERR!/home/username/.npm/_logs/2018-04-15T09_19_49_453Z-debug.log

any help?

答:
It looks like there is no start command in scripts i.e in your package.json file. Below is the start command you need to add to your scripts in package.json file, if it is not available.

```<code>"scripts": {
    "start": "node your-script.js"
}
</code>```

Or you could directly run the following command

```<code>node your-script.js
</code>```

This error can also occur if there is a second entry of script key in your package.json file, try removing the second entry and run it works.

Title: Missing Script Start

Body:
It looks like there is no start command in scripts i.e in your package.json file. Below is the start command you need to add to your scripts in package.json file, if it is not available.

"scripts": {
    "start": "node your-script.js"
}

Or you could directly run the following command

node your-script.js

This error can also occur if there is a second entry of script key in your package.json file, try removing the second entry and run it works.