问:
Unable to find Dir due to credentials not recognized?
I am trying to copy some files from a local location to a network location accessible only via specific user - So far I have

```<code>Import-Module bitstransfer
$username = "domain\user"
$password =  Get-Content 'C:\securestring.txt' | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist ($username, $password)
$sourcePath = 'C:\folder\file.csv', 'C:\folder\file2.csv'
$destPath = '\\server\share$\', '\\server\share$\'
Start-BitsTransfer -Source $sourcePath -Destination $destPath -Credential $cred
</code>```

I am having issues with authentication, script doesn't seem to be able to pass the parameters through

UPDATE: Appears there is a bug with Bits transfer handling -creds as expected, in order to success one must do net use command to manually establish a connection.

Appreciate your input!

答:
Are these servers in the same domain?

Are the creds the same for both servers?

If this is servers in multiple domains, this may be a Windows double hop Auth issue. See the articles on that topic.

I just did the following in one of my WS2K12 labs and it works as expected, but I have a single forest single domain, and did this only on one server.

```<code>PS C:\Scripts> Test-Path -Path '\\FileServer01\Data'
True

PS C:\Scripts> Test-Path -Path '\\FileServer01\TargetShare$'
True

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\Data\*.*'

    Directory: \\FileServer01\Data

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/17/2017   3:57 AM     176640 High_Impact_Data.docx
-a---        11/17/2017   3:57 AM     184320 Low_Impact_Data.docx
-a---         2/12/2018   4:00 PM         64 New Text Document.txt

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

PS C:\Scripts> Copy-Item -Path '\\FileServer01\Data\*.*' -Destination '\\FileServer01\TargetShare$\'

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

    Directory: \\FileServer01\TargetShare$

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/17/2017   3:57 AM     176640 High_Impact_Data.docx
-a---        11/17/2017   3:57 AM     184320 Low_Impact_Data.docx
-a---         2/12/2018   4:00 PM         64 New Text Document.txt

PS C:\Scripts> Import-Module -Name BitsTransfer

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

PS C:\Scripts> Start-BitsTransfer -Source '\\FileServer01\Data\*.*' -Destination '\\FileServer01\TargetShare$\'

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

    Directory: \\FileServer01\TargetShare$

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/17/2017   3:57 AM     176640 High_Impact_Data.docx
-a---        11/17/2017   3:57 AM     184320 Low_Impact_Data.docx
-a---         2/12/2018   4:00 PM         64 New Text Document.txt
</code>```

Update for OP

As for this ...

'different domain but cred are the same'

Are saying, same forest, with multiple domains or a domain in separate forest?

In either case, are the default bi-directional transitive trusts in place?
(if not, then these are different namespaces and Auth will fail unless you pass two set of creds with the appropriate domain identity)

When you say, the creds are the same, does that mean the account exists in the each domain? That use account can exist in both, but that still means the creds are different, since the domains need to be specified?

So, domain1\postanote is not the same thing as domain2\postanote. Yet, if you were using UPN, domain hints, etc., as the user identity, then it's more flexible than that NetBios one.

This is of course all ADDS requirements, and is a restriction not only on PowerShell, but for any thing requiring Auth.

How does Authentication Work Cross Domain?

Body:
I am trying to copy some files from a local location to a network location accessible only via specific user - So far I have

Import-Module bitstransfer
$username = "domain\user"
$password =  Get-Content 'C:\securestring.txt' | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist ($username, $password)
$sourcePath = 'C:\folder\file.csv', 'C:\folder\file2.csv'
$destPath = '\\server\share$\', '\\server\share$\'
Start-BitsTransfer -Source $sourcePath -Destination $destPath -Credential $cred

I am having issues with authentication, script doesn't seem to be able to pass the parameters through

UPDATE: Appears there is a bug with Bits transfer handling -creds as expected, in order to success one must do net use command to manually establish a connection.

Appreciate your input!

Body:
Are these servers in the same domain?

Are the creds the same for both servers?

If this is servers in multiple domains, this may be a Windows double hop Auth issue. See the articles on that topic.

I just did the following in one of my WS2K12 labs and it works as expected, but I have a single forest single domain, and did this only on one server.

PS C:\Scripts> Test-Path -Path '\\FileServer01\Data'
True

PS C:\Scripts> Test-Path -Path '\\FileServer01\TargetShare$'
True

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\Data\*.*'

    Directory: \\FileServer01\Data

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/17/2017   3:57 AM     176640 High_Impact_Data.docx
-a---        11/17/2017   3:57 AM     184320 Low_Impact_Data.docx
-a---         2/12/2018   4:00 PM         64 New Text Document.txt

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

PS C:\Scripts> Copy-Item -Path '\\FileServer01\Data\*.*' -Destination '\\FileServer01\TargetShare$\'

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

    Directory: \\FileServer01\TargetShare$

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/17/2017   3:57 AM     176640 High_Impact_Data.docx
-a---        11/17/2017   3:57 AM     184320 Low_Impact_Data.docx
-a---         2/12/2018   4:00 PM         64 New Text Document.txt

PS C:\Scripts> Import-Module -Name BitsTransfer

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

PS C:\Scripts> Start-BitsTransfer -Source '\\FileServer01\Data\*.*' -Destination '\\FileServer01\TargetShare$\'

PS C:\Scripts> Get-ChildItem -Path '\\FileServer01\TargetShare$\'

    Directory: \\FileServer01\TargetShare$

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/17/2017   3:57 AM     176640 High_Impact_Data.docx
-a---        11/17/2017   3:57 AM     184320 Low_Impact_Data.docx
-a---         2/12/2018   4:00 PM         64 New Text Document.txt

Update for OP

As for this ...

'different domain but cred are the same'

Are saying, same forest, with multiple domains or a domain in separate forest?

In either case, are the default bi-directional transitive trusts in place?
(if not, then these are different namespaces and Auth will fail unless you pass two set of creds with the appropriate domain identity)

When you say, the creds are the same, does that mean the account exists in the each domain? That use account can exist in both, but that still means the creds are different, since the domains need to be specified?

So, domain1\postanote is not the same thing as domain2\postanote. Yet, if you were using UPN, domain hints, etc., as the user identity, then it's more flexible than that NetBios one.

This is of course all ADDS requirements, and is a restriction not only on PowerShell, but for any thing requiring Auth.

How does Authentication Work Cross Domain?


来源: stackexchange

问:
Rails: ORA-00911 error while executing query, doesn't appear when copy and pasted
We had some queries saved in a secondary database which are used to query an Oracle Database.

It kept showing us the ORA-00911 Invalid Character error, but we couldn't find it.

We searched for extra colons, semi-colons or comma as other suggested but we couldn't find it.

We then printed the query to the HTML output, copied it and pasted it on the console and it worked.

Are there any other possible characters that could fail?

答:
What we finally did was to paste the query from the console to Visual Studio Code, and then we installed the extension Highlight Bad Chars. That showed us that some invalid characters (** **) were placed in the text.

We took the queries right from our Confluence site, maybe it got confused with some markup element that brought the error.

ContentLicense: CC BY-SA 4.0


问:
is it possible to disable mp3 controls when loading an mp3 file via http headers using php
I'm creating a portfolio website for my music and want to allow users to play my songs without them being able to see the source/download the mp3 files.

I'm using PHP for this project and loading the files via HTTP headers.

```<code><?php
 $mp3 ='72vox.mp3';
 if(file_exists($mp3)) {
   header('Content-Type: audio/mpeg');
   header('Content-Disposition: inline; filename="mp3_file.mp3"');
   header('Content-length: '. filesize($mp3));
   header('Cache-Control: no-cache');
   header('Content-Transfer-Encoding: chunked');
   readfile($mp3);
   exit;
  }
?>
</code>```

When the page loads, my mp3 plays. However, I can't seem to figure out how to display any HTML on the page (and more importantly, how to place the audio controls in a div).

Thank you for any help in advance

答:
I'm creating a portfolio website for my music and want to allow users to play my songs without them being able to see the source/download the mp3 files.

That's impossible.

In this case, the URL of your PHP script is effectively the URL of the audio file.

When the page loads, my mp3 plays. However, I can't seem to figure out how to display any HTML on the page (and more importantly, how to place the audio controls in a div).

That has nothing to do with the way you serve the file.  You need to make a page with an <audio> tag, or with appropriate JavaScript.  When you go to this URL, it's not a "page" from your server, it's just the browser's default handling of your MP3 file.  Other browsers will just download it or open it up in the user's default audio player.

Body:
I'm creating a portfolio website for my music and want to allow users to play my songs without them being able to see the source/download the mp3 files.

I'm using PHP for this project and loading the files via HTTP headers.

<?php
 $mp3 ='72vox.mp3';
 if(file_exists($mp3)) {
   header('Content-Type: audio/mpeg');
   header('Content-Disposition: inline; filename="mp3_file.mp3"');
   header('Content-length: '. filesize($mp3));
   header('Cache-Control: no-cache');
   header('Content-Transfer-Encoding: chunked');
   readfile($mp3);
   exit;
  }
?>

When the page loads, my mp3 plays. However, I can't seem to figure out how to display any HTML on the page (and more importantly, how to place the audio controls in a div).

Thank you for any help in advance


问:
Vue js vee validate password confirmation with custom components
I use vee-validate in my project with custom components with no problems.

But now for a Password Confirmation input field, I'm not able to make it work properly.

I have custom components for the input fields, somethink like <base-input-field>.

If I add a ref="password" attribute in my custom component (<base-input-field ref="password">), it will not reference the <input> inside my custom component, but the
 wrapper that encapsulates the <input> html component.

Code example:

```<code>            <!-- Password -->
            <div class="row">
              <base-text-field
                ref="password"
                name="password"
                type="password"
                :error="isVisible && errors.first('password')"
                v-validate="{
                  required: true,
                  min: 6,
                  max: 30,
                }"
                v-model.trim="password"
                required
              />
            </div>

            <!-- Confirm Password -->
            <div class="row">
              <base-text-field
                name="password_conf"
                type="password"
                :error="isVisible && errors.first('password_conf')"
                v-validate="{
                  required: true,
                  confirmed: 'password',
                }"
                :data-vv-as="password"
                v-model.trim="password_conf"
                required
              />
            </div>
</code>```

答:
I don't know vee-validate but here is an idea from a similar problem I had with custom components not having access to <input> directly:

Get the reference to the input using JS:

this.$refs.password.$el.querySelector("input")

You could save it in a variable and pass it to your component I guess. Again, I don't know vee-validate. Hope it gives you some ideas.

Body:
I use vee-validate in my project with custom components with no problems.

But now for a Password Confirmation input field, I'm not able to make it work properly.

I have custom components for the input fields, somethink like <base-input-field>.

If I add a ref="password" attribute in my custom component (<base-input-field ref="password">), it will not reference the <input> inside my custom component, but the
 wrapper that encapsulates the <input> html component.

Code example:

              <base-text-field
                ref="password"
                name="password"
                type="password"
                :error="isVisible && errors.first('password')"
                v-validate="{
                  required: true,
                  min: 6,
                  max: 30,
                }"
                v-model.trim="password"
                required
              />

              <base-text-field
                name="password_conf"
                type="password"
                :error="isVisible && errors.first('password_conf')"
                v-validate="{
                  required: true,
                  confirmed: 'password',
                }"
                :data-vv-as="password"
                v-model.trim="password_conf"
                required
              />


问:
How to reference every cell of another tab using indirect
I want to create a tab that will display all the cell values of another tab based on the tab name provided on a cell.

I have played around with the indirect function, but I cannot write a formula so that by dragging down and right it will access the cells.

```<code>=INDIRECT("'"&$A$1&"'!A1")
</code>```

This part &$A$1& is getting the name of the tab.
If I drag down this formula, the last A1 does not change though.

答:
Simply use following formula</p>

```<code>=INDIRECT($A$1&"!A" & ROW(1:1))
</code>```

Body:
I want to create a tab that will display all the cell values of another tab based on the tab name provided on a cell.

I have played around with the indirect function, but I cannot write a formula so that by dragging down and right it will access the cells.

=INDIRECT("'"&$A$1&"'!A1")

This part &$A$1& is getting the name of the tab.
If I drag down this formula, the last A1 does not change though.

Body:
Simply use following formula

=INDIRECT($A$1&"!A" & ROW(1:1))


答:
Try building the string like this.  The final A1 will work as you want it to.</p>

```<code>=INDIRECT(CONCATENATE("'",$A$1,"'!", CELL("address",A1)))
</code>```

Title: How to reference every cell of another tab using indirect

Body:
Try building the string like this.  The final A1 will work as you want it to.

=INDIRECT(CONCATENATE("'",$A$1,"'!", CELL("address",A1)))


问:
Core Data Inverse RelationShip
I am creating Travel guide app using core data. I have 4 entities CITY ,RESTAURANTS ,
HOTEL AND FAMOUS PLACES. City is connected with all other entity because one city may have number of restaurants , hotels and places. City entity has 3 attribute Name ,Image ,Description. I am able to display list restaurants of selected city.In Restaurant Entity I have 4 attribute Name, Description ,Address and phone no..Now I want to show
this attribute detail of selected restaurant(of selected city) in next view.But how can I access restaurant description in next view..
Here is my code.

```<code>     - (void)viewWillAppear:(BOOL)animated {

        [super viewWillAppear:animated];

        NSMutableArray *restaurants = [[NSMutableArray alloc]initWithArray:[city.cityTorestaurants allObjects]];

        NSSortDescriptor *nameDescriptor  = [[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];

        NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:nameDescriptor,nil];
        [restaurants sortUsingDescriptors:sortDescriptors];
        [hotels sortUsingDescriptors:sortDescriptors];
        [self setArrayOfRestaurants:restaurants];
        [restaurants release];
        [nameDescriptor release];
        [sortDescriptors release];
        [tableView reloadData];

    }

- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil ) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier]autorelease];

    }

    //set up cell

    NSLog(@"For Restaurants List");
    Restaurants *restaurants = [arrayOfRestaurants objectAtIndex:indexPath.row];
cell.textLabel.text = restaurants.Name;

return cell;
}
</code>```

cityTorestaurants and restaurantTocity is relationship in core data..
Help Please..

答:
In your RestaurantViewController create a property Restaurant* currentRestaurant

in your didSelectRowAtIndexPath:of the CityViewController set the property with self.restaurantVC.currentRestaurant = [arrayOfRestaurants objectAtIndex:indexPath.row];

ContentLicense: CC BY-SA 3.0

Title: Core Data Inverse RelationShip

Body:
I am creating Travel guide app using core data. I have 4 entities CITY ,RESTAURANTS ,
HOTEL AND FAMOUS PLACES. City is connected with all other entity because one city may have number of restaurants , hotels and places. City entity has 3 attribute Name ,Image ,Description. I am able to display list restaurants of selected city.In Restaurant Entity I have 4 attribute Name, Description ,Address and phone no..Now I want to show
this attribute detail of selected restaurant(of selected city) in next view.But how can I access restaurant description in next view..
Here is my code.

     - (void)viewWillAppear:(BOOL)animated {

        [super viewWillAppear:animated];

        NSMutableArray *restaurants = [[NSMutableArray alloc]initWithArray:[city.cityTorestaurants allObjects]];

        NSSortDescriptor *nameDescriptor  = [[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];

        NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:nameDescriptor,nil];
        [restaurants sortUsingDescriptors:sortDescriptors];
        [hotels sortUsingDescriptors:sortDescriptors];
        [self setArrayOfRestaurants:restaurants];
        [restaurants release];
        [nameDescriptor release];
        [sortDescriptors release];
        [tableView reloadData];

    }

- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil ) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier]autorelease];

    }

    //set up cell

    NSLog(@"For Restaurants List");
    Restaurants *restaurants = [arrayOfRestaurants objectAtIndex:indexPath.row];
cell.textLabel.text = restaurants.Name;

return cell;
}

cityTorestaurants and restaurantTocity is relationship in core data..
Help Please..


问:
How to catch at compile-time an assignment of a subtype to a supertype?
I learnt that the

rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x

This allows an assignment of a variable of a subtype to a variable of a supertype. Is there a way to get a compile-time error regarding that assignment?

(TypeScript Playground)

interface SuperT {
    field: string
}

// an explicitly declared subtype object for a supertype variable generates an error
const super1: SuperT = {field: 'value', extra: 1} // compile-time error: Type '{ field: string; extra: number; }' is not assignable to type 'SuperT'

function subTValue() { return {field: 'value', extra: 1} }
const super2: SuperT = subTValue() // no compile-time error, BUT HOW TO get a compile-time error here?
```

答:
As Ray Toal found out, an answer for a very similar issue can be found here. (And I knew this in the first place, I just wanted to check jcalz's reaction time. Pretty impressive, @jcalz!)

Based on that approach, my code would look like:

(TypeScript Playground)

type StrictPropertyCheck<T, TExpected, TError> = Exclude<keyof T, keyof TExpected> extends never ? {} : TError

interface SuperT {
    field: string
}

function doIdentity<T extends SuperT>(a: T & StrictPropertyCheck<T, SuperT, "Only allowed properties of SuperT">) {
    return a
}

function subTValue() { return { field: 'value', extra: 1 } }

const super3: SuperT = doIdentity(subTValue()) // we do get a compile-time error!
```

Body:
I learnt that the

rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x

This allows an assignment of a variable of a subtype to a variable of a supertype. Is there a way to get a compile-time error regarding that assignment?

(<a href="https://www.typescriptlang.org/play/#src=interface%20SuperT%20%7B%0D%0A%20%20%20%20field%3A%20string%0D%0A%7D%0D%0A%0D%0A%2F%2F%20an%20explicitly%20declared%20subtype%20object%20for%20a%20supertype%20variable%20generates%20an%20error%0D%0Aconst%20super1%3A%20SuperT%20%3D%20%7Bfield%3A%20'value'%2C%20extra%3A%201%7D%20%2F%2F%20compile-time%20error%3A%20Type%20'%7B%20field%3A%20string%3B%20extra%3A%20number%3B%20%7D'%20is%20not%20assignable%20to%20type%20'SuperT'%0D%0A%0D%0Afunction%20subTValue()%20%7B%20return%20%7Bfield%3A%20'value'%2C%20extra%3A%201%7D%20%7D%0D%0Aconst%20super2%3A%20SuperT%20%3D%20subTValue()%20%2F%2F%20no%20compile-time%20error%2C%20BUT%20HOW%20TO%20get%20a%20compile-time%20error%20here%3F%20%0D%0A" rel="nofollow noreferrer">TypeScript Playground)

interface SuperT {
    field: string
}

// an explicitly declared subtype object for a supertype variable generates an error
const super1: SuperT = {field: 'value', extra: 1} // compile-time error: Type '{ field: string; extra: number; }' is not assignable to type 'SuperT'

function subTValue() { return {field: 'value', extra: 1} }
const super2: SuperT = subTValue() // no compile-time error, BUT HOW TO get a compile-time error here?

Body:
As Ray Toal found out, an answer for a very similar issue can be found here. (And I knew this in the first place, I just wanted to check jcalz's reaction time. Pretty impressive, @jcalz!)

Based on that approach, my code would look like:

(<a href="https://www.typescriptlang.org/play/#src=type%20StrictPropertyCheck%3CT%2C%20TExpected%2C%20TError%3E%20%3D%20Exclude%3Ckeyof%20T%2C%20keyof%20TExpected%3E%20extends%20never%20%3F%20%7B%7D%20%3A%20TError%0D%0A%0D%0Ainterface%20SuperT%20%7B%0D%0A%20%20%20%20field%3A%20string%0D%0A%7D%0D%0A%0D%0Afunction%20doIdentity%3CT%20extends%20SuperT%3E(a%3A%20T%20%26%20StrictPropertyCheck%3CT%2C%20SuperT%2C%20%22Only%20allowed%20properties%20of%20SuperT%22%3E)%20%7B%0D%0A%20%20%20%20return%20a%0D%0A%7D%0D%0A%0D%0A%0D%0Afunction%20subTValue()%20%7B%20return%20%7B%20field%3A%20'value'%2C%20extra%3A%201%20%7D%20%7D%0D%0A%0D%0Aconst%20super3%3A%20SuperT%20%3D%20doIdentity(subTValue())%20%2F%2F%20we%20do%20get%20a%20compile-time%20error!%0D%0A" rel="nofollow noreferrer">TypeScript Playground)

type StrictPropertyCheck<T, TExpected, TError> = Exclude<keyof T, keyof TExpected> extends never ? {} : TError

interface SuperT {
    field: string
}

function doIdentity<T extends SuperT>(a: T & StrictPropertyCheck<T, SuperT, "Only allowed properties of SuperT">) {
    return a
}

function subTValue() { return { field: 'value', extra: 1 } }

const super3: SuperT = doIdentity(subTValue()) // we do get a compile-time error!


问:
XMLHttpRequest returns undefined response, but works on console.log
I am trying to read from a local myjson.json file and print its content to my index.html.
I am using the following JavaScript code:

```<code>function getJSON() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/myfolder/myjson.json', false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
        var response = xhr.responseText;
        console.log("response: " + response); //Correctly prints JSON content to console
        return response; //response is undefined when called from html
        }
    }
    xhr.send(null);
}
</code>```

I am calling the function getJSON() like so:

```<code>document.getElementById("contentOfJSON").innerHTML += "JSON: "+getJSON();
</code>```

This prints out the content of myjson.json correctly to console.log, but my HTML-Element "contentOfJSON" contains only "JSON: undefined".
Why am I getting an undefined response eventhough the console.log is working?

答:
You're returning the string to the call on onreadystatechange.

Your function getJSON returns nothing.

From what I've seen, sync is suppose to be depreciated so just make it async by passing a success function into getJSON and then calling it by passing the result string into callback.

```<code>function getJSON(mycallback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/myfolder/myjson.json', false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
        var response = xhr.responseText;
        console.log("response: " + response); //Correctly prints JSON content to console

        // call it here
        mycallback(response);
        }
    }
    xhr.send(null);
}

getJSON(function(result)
{
    document.getElementById("contentOfJSON").innerHTML += "JSON: " + result;
});
</code>```

Body:
I am trying to read from a local myjson.json file and print its content to my index.html.
I am using the following JavaScript code:

function getJSON() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/myfolder/myjson.json', false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
        var response = xhr.responseText;
        console.log("response: " + response); //Correctly prints JSON content to console
        return response; //response is undefined when called from html
        }
    }
    xhr.send(null);
}

I am calling the function getJSON() like so:

document.getElementById("contentOfJSON").innerHTML += "JSON: "+getJSON();

This prints out the content of myjson.json correctly to console.log, but my HTML-Element "contentOfJSON" contains only "JSON: undefined".
Why am I getting an undefined response eventhough the console.log is working?

Body:
You're returning the string to the call on onreadystatechange.

Your function getJSON returns nothing.

From what I've seen, sync is suppose to be depreciated so just make it async by passing a success function into getJSON and then calling it by passing the result string into callback.

function getJSON(mycallback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/myfolder/myjson.json', false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
        var response = xhr.responseText;
        console.log("response: " + response); //Correctly prints JSON content to console

        // call it here
        mycallback(response);
        }
    }
    xhr.send(null);
}

getJSON(function(result)
{
    document.getElementById("contentOfJSON").innerHTML += "JSON: " + result;
});


问:
nvcc compilation errors with "M_PI" and "or"
When trying to compile this piece of code:

```<code>#define _USE_MATH_DEFINES
#include <cmath>
#include <cstdio>

void minimal_example(){
    int i=2;
    if(i==3 or i==4) printf("I want %d!\n",M_PI);
}
</code>```

using

```<code>nvcc -x cu -Xcompiler=/permissive- -dc cuda_nvcc_cl_test.cu -o cuda_nvcc_cl_test.obj
</code>```

I get the follwing errors (in line 7):

```<code>error: expected a ")"
error: identifier "M_PI" is undefined
</code>```

I am using Windows 10 with Visual Studio's cl.exe (Version 19.16.27031.1 for x64) and CUDA toolkit 10.1.

When replacing cmath with math.h and or with || (alternatively add #include <ciso646>), the errors disappear. However, are there some compiler options or other possibilities so that I can keep the code as is?

Also why did -Xcompiler=/permissive- not help?

答:
There are 2 issues here:

Apparently nvcc includes cmath prior to parsing your code.  As discussed in the accepted answer here, if you include cmath and you don't have the define instantiated at that point, you won't get M_PI defined, and subsequent inclusions of cmath won't fix this, due to include guards.  A possible workaround for this is to add -D_USE_MATH_DEFINES to your compile command line.  This puts the define in place from the start of the compilation process, and M_PI gets defined that way.

Contrary to what I read as correct or standard behavior, the use of or in place of || seems to be conditioned on inclusion of ciso646 (on nvcc on windows/visual studio only.  nvcc on linux doesn't seem to need this).  Yes, I understand it is not supposed to work that way, but nevertheless it appears to be necessary.  This may be an issue with Visual Studio.  You can experiment with the /Za switch if you like.   (It didn't seem to help when I tried it.)

With CUDA 10.1, on VS2019, when I compile this:

```<code>#include <cstdio>
#include <ciso646>

void minimal_example(){
    int i=2;
    if(i==3 or i==4) printf("I want %f!\n",M_PI);
}
</code>```

with this command line:

```<code>nvcc -x cu -dc test.cu -o test.obj -D_USE_MATH_DEFINES
</code>```

I get no errors or warnings.  Note that I have also changed your printf format specifier from %d to %f to be consistent with the type of M_PI.

If you really don't want to include ciso646, nvcc supports the -include switch to include a file directly from the command line.  Therefore I can compile this:

```<code>#include <cstdio>

void minimal_example(){
    int i=2;
    if(i==3 or i==4) printf("I want %f!\n",M_PI);
}
</code>```

like this:

```<code>nvcc -x cu -dc test.cu -o test.obj -D_USE_MATH_DEFINES -include ciso646
</code>```

with no errors or warnings.

Body:
When trying to compile this piece of code:

#define _USE_MATH_DEFINES
#include <cmath>
#include <cstdio>

void minimal_example(){
    int i=2;
    if(i==3 or i==4) printf("I want %d!\n",M_PI);
}

using

nvcc -x cu -Xcompiler=/permissive- -dc cuda_nvcc_cl_test.cu -o cuda_nvcc_cl_test.obj

I get the follwing errors (in line 7):

error: expected a ")"
error: identifier "M_PI" is undefined

I am using Windows 10 with Visual Studio's cl.exe (Version 19.16.27031.1 for x64) and CUDA toolkit 10.1.

When replacing cmath with math.h and or with || (alternatively add #include <ciso646>), the errors disappear. However, are there some compiler options or other possibilities so that I can keep the code as is?

Also why did -Xcompiler=/permissive- not help?

Body:
There are 2 issues here:

Apparently nvcc includes cmath prior to parsing your code.  As discussed in the accepted answer here, if you include cmath and you don't have the define instantiated at that point, you won't get M_PI defined, and subsequent inclusions of cmath won't fix this, due to include guards.  A possible workaround for this is to add -D_USE_MATH_DEFINES to your compile command line.  This puts the define in place from the start of the compilation process, and M_PI gets defined that way.

Contrary to what I read as correct or standard behavior, the use of or in place of || seems to be conditioned on inclusion of ciso646 (on nvcc on windows/visual studio only.  nvcc on linux doesn't seem to need this).  Yes, I understand it is not supposed to work that way, but nevertheless it appears to be necessary.  This may be an issue with Visual Studio.  You can experiment with the /Za switch if you like.   (It didn't seem to help when I tried it.)

With CUDA 10.1, on VS2019, when I compile this:

#include <cstdio>
#include <ciso646>

void minimal_example(){
    int i=2;
    if(i==3 or i==4) printf("I want %f!\n",M_PI);
}

with this command line:

nvcc -x cu -dc test.cu -o test.obj -D_USE_MATH_DEFINES

I get no errors or warnings.  Note that I have also changed your printf format specifier from %d to %f to be consistent with the type of M_PI.

If you really don't want to include ciso646, nvcc supports the -include switch to include a file directly from the command line.  Therefore I can compile this:

#include <cstdio>

void minimal_example(){
    int i=2;
    if(i==3 or i==4) printf("I want %f!\n",M_PI);
}

like this:

nvcc -x cu -dc test.cu -o test.obj -D_USE_MATH_DEFINES -include ciso646

with no errors or warnings.


问:
Regex: Match alphanumeric and spaces with exception of leading spaces
My goal is to capture alphanumeric characters and all spaces (minus the leading space).
The issue I am having is not being able to capture spaces that follow non-alphanumeric characters (symbols).
I am willing to use look-arounds if necessary, but have yet to solve this even when doing so.

Here is what I have accomplished, as described above:

Text: # one 123: two `three` four (five) six

Desired result: one 123 two three four five six

*Regex attempts:

with look-around:

(?! )[A-Za-z0-9 ]*(?<! )

result:
one 123twothreefourfivesix

without look around:

[A-Za-z0-9]+(?: +[A-Za-z0-9]+)*

result: one 123twothreefourfive

答:
You can use this regex

```<code>^[^a-z0-9]+|[^a-z0-9 ]+|\s{2,}|[^a-z0-9]+$
</code>```

^[^a-z0-9]+ - Matches anything else than alphanumeric at start of string

[^a-z0-9 ]+ - Matches anything else than alphanumeric and space

\s{2,} - Matches two or more consecutive space characters

[^a-z0-9 ]+$ - Matches anything else than alphanumeric at end of string

Demo

Body:
You can use this regex

^[^a-z0-9]+|[^a-z0-9 ]+|\s{2,}|[^a-z0-9]+$

^[^a-z0-9]+ - Matches anything else than alphanumeric at start of string

[^a-z0-9 ]+ - Matches anything else than alphanumeric and space

\s{2,} - Matches two or more consecutive space characters

[^a-z0-9 ]+$ - Matches anything else than alphanumeric at end of string

Demo


问:
Drawing circle and setting it visible on canvas
I have some codes making jFrame and canvas. They are visible. But I don't know how to set a circle visible on the canvas

```<code>    package unitcirclevisulaization;

    import java.awt.Canvas;
    import java.awt.Graphics;
    import javax.swing.JFrame;

    public class UnitCircleVisulaization extends Canvas {

        public static void main(String[] args) {
            JFrame frame = new JFrame("Unit Circle");
            Canvas canvas = new Canvas();
            canvas.setSize(800,800);
            frame.add(canvas);
            frame.pack();
            frame.setVisible(true);
        }

        public void paint(Graphics g)
        {
            g.fillOval(400, 400, 400, 400);
        }

    }
</code>```

I just want a circle to appear on the canvas, and be able to set color of the circle

答:
Your paint method is inside the UnitCircleVisulaization class which is never instantiated, so the paint method is never called.

To fix this, just replace the line

```<code>Canvas canvas = new Canvas();
</code>```

with

```<code>Canvas canvas = new UnitCircleVisulaization();
</code>```

This works because UnitCircleVisulaization extends Canvas which contains the paint method.  Then the paint method is automatically called when the frame is made visible.

Body:
I have some codes making jFrame and canvas. They are visible. But I don't know how to set a circle visible on the canvas

    package unitcirclevisulaization;

    import java.awt.Canvas;
    import java.awt.Graphics;
    import javax.swing.JFrame;

    public class UnitCircleVisulaization extends Canvas {

        public static void main(String[] args) {
            JFrame frame = new JFrame("Unit Circle");
            Canvas canvas = new Canvas();
            canvas.setSize(800,800);
            frame.add(canvas);
            frame.pack();
            frame.setVisible(true);
        }

        public void paint(Graphics g)
        {
            g.fillOval(400, 400, 400, 400);
        }

    }

I just want a circle to appear on the canvas, and be able to set color of the circle

Body:
Your paint method is inside the UnitCircleVisulaization class which is never instantiated, so the paint method is never called.

To fix this, just replace the line

Canvas canvas = new Canvas();

with

Canvas canvas = new UnitCircleVisulaization();

This works because UnitCircleVisulaization extends Canvas which contains the paint method.  Then the paint method is automatically called when the frame is made visible.


问:
looking for a replace() wildcard for numbers
I not an expert in C# i've only been doing it for a few months.

I have a token @Html.Raw(Model.Prices.SitePrice.Text) that displays a price for a product ($9.99)

I needed to remove the $ sign from the token so i put @Html.Raw(Model.Prices.SitePrice.Text.Replace("$", ""))

This all works fine, The issue is when I apply a special /promotion to that product, it changes the token to display:

$9.99 $7.99 it should display 7.99 once working.

I want the <stike>$##.## removed using a wildcard to deal with any number between the strike.

What would be the best way of writing the .replace() for this this text? (has to be inline for google schema data)

Ive tried:

@Html.Raw(Model.Prices.SitePrice.Text.Replace("$", "").Replace("[\r\n]+ ", ""))

@Html.Raw(Model.Prices.SitePrice.Text.Replace("$", "").Replace("(.*) ", ""))

7 different vaules?

$9.99 $7.99 it should display 7.99

$10.99 $8.99 it should display 8.99

$199.00 $188.00 it should display 188.00

$20.00 $18.50 it should display 18.50

$4.20 $2.20 it should display 2.20

$12345.00 $12225.00 it should display 12225.00

Body: @Html.Raw(Regex.Replace(Model.Prices.SitePrice.Text, @"<strike>[\s\S]*</strike>", "").Trim().TrimStart('$'))


问:
http to https redirect
I try to achieve the following behavior with .htaccess:

Redirect http://www.mydomain.tld -> https://mydomain.tld

Also redirect my old links like:

http://www.mydomain.tld/news/mynews should be redirected to https://mydomain.tld/news/mynews

The page should now only be available over https without the leading "www".

I have this rule to redirect from http://www.mydomain.tld to http://mydomain.tld:

```<code><IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
</code>```

Force https

```<code><IfModule mod_headers.c>
   Header set Strict-Transport-Security max-age=16070400;
</IfModule>
</code>```

But I have problems to figure out how to correctly write the conditions so that I'm not losing my build up link power (Redirect 301 is important).

Hopefully anyone can help me!
Thank you!

答:
I redirect everything to https://example.com without www.

This is what I use:

```<code>#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</code>```

Never had a problem with it like this.

Title: http to https redirect

Body:
I try to achieve the following behavior with .htaccess:

Redirect http://www.mydomain.tld -> https://mydomain.tld

Also redirect my old links like:

http://www.mydomain.tld/news/mynews should be redirected to https://mydomain.tld/news/mynews

The page should now only be available over https without the leading "www".

I have this rule to redirect from http://www.mydomain.tld to http://mydomain.tld:

<IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

Force https

<IfModule mod_headers.c>
   Header set Strict-Transport-Security max-age=16070400;
</IfModule>

But I have problems to figure out how to correctly write the conditions so that I'm not losing my build up link power (Redirect 301 is important).

Hopefully anyone can help me!
Thank you!

Body:
I redirect everything to https://example.com without www.

This is what I use:

#Redirect www and http
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Never had a problem with it like this.


问:
How can I hover over a image where it uses Gradient
I place some communication icons on my website. One of them is the Instagram icon where I got it from Font Awesome and I gave approximately of the same color as is the logo of Instagram using Gradient. The problem is now that If i want to :hover it not working. I do not know how I can fix it.

footer {
  background-color: black;
  height: 120px;
}

footer a {
  display: flex;
  justify-content: center;
  font-size: 70px;
  padding: 20px;
  text-decoration: none !important;
}

.fa-instagram {
  background: #f09433;
  background: -moz-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: -webkit-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.fa-instagram:hover {
  color: hsla(181, 6%, 67%, 0.5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<html>

<head>
  <link rel="stylesheet" type="text/css" href="main.css">

  <title>Website Title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</head>

<body>
  <footer>

      <i class="fab fa-instagram"></i>

  </footer>
</body>

</html></code>```

答:
after doing trial and error I've come up with this.
I use background instead of color in your .fa-instagram:hover

And then I added -webkit-background-clip: text; and -webkit-text-fill-color: transparent;
 and I added a transition:2s but still you can delete it if you don't want.

    footer {
        background-color: black;
        height: 120px;
    }

    footer a {
        display: flex;
        justify-content: center;
        font-size: 70px;
        padding: 20px;
        text-decoration: none !important;
    }

    .fa-instagram {
        background: #f09433;
        background: -moz-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
        background: -webkit-linear-gradient(45deg, #f09433 0%,#e6683c 25%,#dc2743 50%,#cc2366 75%,#bc1888 100%);
        background: linear-gradient(45deg, #f09433 0%,#e6683c 25%,#dc2743 50%,#cc2366 75%,#bc1888 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .fa-instagram:hover {
        background: hsla(181, 6%, 67%, 0.5);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        transition:2s;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <head>
            <link rel="stylesheet" type="text/css" href="main.css">
            <title>Website Title</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
            <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

  </head>
        <footer>

                    <i class="fab fa-instagram" ></i>

        </footer>    </code>```

Body:
I place some communication icons on my website. One of them is the Instagram icon where I got it from Font Awesome and I gave approximately of the same color as is the logo of Instagram using Gradient. The problem is now that If i want to :hover it not working. I do not know how I can fix it.

footer {
  background-color: black;
  height: 120px;
}

footer a {
  display: flex;
  justify-content: center;
  font-size: 70px;
  padding: 20px;
  text-decoration: none !important;
}

.fa-instagram {
  background: #f09433;
  background: -moz-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: -webkit-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  background: linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.fa-instagram:hover {
  color: hsla(181, 6%, 67%, 0.5);
}

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="main.css">

  <title>Website Title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">

Body:
after doing trial and error I've come up with this.
I use background instead of color in your .fa-instagram:hover

And then I added -webkit-background-clip: text; and -webkit-text-fill-color: transparent;
 and I added a transition:2s but still you can delete it if you don't want.

    footer {
        background-color: black;
        height: 120px;
    }

    footer a {
        display: flex;
        justify-content: center;
        font-size: 70px;
        padding: 20px;
        text-decoration: none !important;
    }

    .fa-instagram {
        background: #f09433;
        background: -moz-linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
        background: -webkit-linear-gradient(45deg, #f09433 0%,#e6683c 25%,#dc2743 50%,#cc2366 75%,#bc1888 100%);
        background: linear-gradient(45deg, #f09433 0%,#e6683c 25%,#dc2743 50%,#cc2366 75%,#bc1888 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .fa-instagram:hover {
        background: hsla(181, 6%, 67%, 0.5);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        transition:2s;
    }

 <head>
            <link rel="stylesheet" type="text/css" href="main.css">
            <title>Website Title</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
            <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

  </head>
        <footer>
               <a href="#" target="_blank"id="instagram">
                    <i class="fab fa-instagram" ></i>
               </a>
        </footer>


问:
How To Make This Carousel Slider Automatically sliding?
I have this slider done but not automatically sliding, what code should I add to make this automatic sliding? And where should I place that code in this?

I've tried to put setinterval for the goNext function but still not working

```<code>class Slider {
    constructor(props) {
        this.rootElement = props.element;
        this.slides = Array.from(
            this.rootElement.querySelectorAll(".slider-list__item")
        );
        this.slidesLength = this.slides.length;
        this.current = 0;
        this.isAnimating = false;
        this.direction = 1; // -1

        this.navBar = this.rootElement.querySelector(".slider__nav-bar");
        this.thumbs = Array.from(this.rootElement.querySelectorAll(".nav-control"));
        this.prevButton = this.rootElement.querySelector(".slider__arrow_prev");
        this.nextButton = this.rootElement.querySelector(".slider__arrow_next");

        this.slides[this.current].classList.add("slider-list__item_active");
        this.thumbs[this.current].classList.add("nav-control_active");

        this._bindEvents();
    }

    goTo(index, dir) {
        if (this.isAnimating) return;
        var self = this;
        let prevSlide = this.slides[this.current];
        let nextSlide = this.slides[index];

         self.isAnimating = true;
         self.current = index;
         nextSlide.classList.add("slider-list__item_active");

         goStep(dir) {
             let index = this.current + dir;
             let len = this.slidesLength;
             let currentIndex = (index + len) % len;
             this.goTo(currentIndex, dir);
         }

         goNext() {
             this.goStep(1);
         }

         goPrev() {
             this.goStep(-1);
         }

         _navClickHandler(e) {
             var self = this;
             if (self.isAnimating) return;
             let target = e.target.closest(".nav-control");
             if (!target) return;
             let index = self.thumbs.indexOf(target);
             if (index === self.current) return;
             let direction = index > self.current ? 1 : -1;
             self.goTo(index, direction);
         }

         _bindEvents() {
             var self = this;
             ["goNext", "goPrev", "_navClickHandler"].forEach(method => {
                  self[method] = self[method].bind(self);
             });
             self.nextButton.addEventListener("click", self.goNext);
             self.prevButton.addEventListener("click", self.goPrev);
             self.navBar.addEventListener("click", self._navClickHandler);
         }
    }

    // ===== init ======
    let slider = new Slider({
        element: document.querySelector(".slider")
    });
</code>```

So please if anyone could tell me how to make this carousel slider automatically sliding, I will really really appreciate that.

答:
Just call the next function</p>

```<code>setInterval(function()
{
slider.goNext();
}, 1000);
</code>```

Body:
I have this slider done but not automatically sliding, what code should I add to make this automatic sliding? And where should I place that code in this?

I've tried to put setinterval for the goNext function but still not working

class Slider {
    constructor(props) {
        this.rootElement = props.element;
        this.slides = Array.from(
            this.rootElement.querySelectorAll(".slider-list__item")
        );
        this.slidesLength = this.slides.length;
        this.current = 0;
        this.isAnimating = false;
        this.direction = 1; // -1

        this.navBar = this.rootElement.querySelector(".slider__nav-bar");
        this.thumbs = Array.from(this.rootElement.querySelectorAll(".nav-control"));
        this.prevButton = this.rootElement.querySelector(".slider__arrow_prev");
        this.nextButton = this.rootElement.querySelector(".slider__arrow_next");

        this.slides[this.current].classList.add("slider-list__item_active");
        this.thumbs[this.current].classList.add("nav-control_active");

        this._bindEvents();
    }

    goTo(index, dir) {
        if (this.isAnimating) return;
        var self = this;
        let prevSlide = this.slides[this.current];
        let nextSlide = this.slides[index];

         self.isAnimating = true;
         self.current = index;
         nextSlide.classList.add("slider-list__item_active");

         goStep(dir) {
             let index = this.current + dir;
             let len = this.slidesLength;
             let currentIndex = (index + len) % len;
             this.goTo(currentIndex, dir);
         }

         goNext() {
             this.goStep(1);
         }

         goPrev() {
             this.goStep(-1);
         }

         _navClickHandler(e) {
             var self = this;
             if (self.isAnimating) return;
             let target = e.target.closest(".nav-control");
             if (!target) return;
             let index = self.thumbs.indexOf(target);
             if (index === self.current) return;
             let direction = index > self.current ? 1 : -1;
             self.goTo(index, direction);
         }

         _bindEvents() {
             var self = this;
             ["goNext", "goPrev", "_navClickHandler"].forEach(method => {
                  self[method] = self[method].bind(self);
             });
             self.nextButton.addEventListener("click", self.goNext);
             self.prevButton.addEventListener("click", self.goPrev);
             self.navBar.addEventListener("click", self._navClickHandler);
         }
    }

    // ===== init ======
    let slider = new Slider({
        element: document.querySelector(".slider")
    });

So please if anyone could tell me how to make this carousel slider automatically sliding, I will really really appreciate that.

Body:
Just call the next function

setInterval(function()
{
slider.goNext();
}, 1000);


问:
PHPBB3 How to display Last Post Title in index
I am using the prosilver theme in phpbb3. In the file forumlist_body.html there is a part that looks like this:

```<code><dd class="lastpost"><span>
<!-- IF forumrow.LAST_POST_TIME -->
<dfn>{L_LAST_POST}</dfn> {L_POST_BY_AUTHOR} {forumrow.LAST_POSTER_FULL}
  <!-- IF not S_IS_BOT -->
  <a href="{forumrow.U_LAST_POST}">{LAST_POST_IMG}</a>
  <!-- ENDIF -->
<br />
{forumrow.LAST_POST_TIME}
<!-- ELSE -->{L_NO_POSTS}<br />
<!-- ENDIF -->
</span></dd>
</code>```

How would I get that to show the last post title as well. I tried {forumrow.LAST_POST_TITLE} but it didn't work.

答:
its simple ,,

i have made those modifications ,,

here is the code just replace :

```<code><dd class="lastpost"><span>
                    <!-- IF forumrow.U_UNAPPROVED_TOPICS --><a href="{forumrow.U_UNAPPROVED_TOPICS}">{UNAPPROVED_IMG}</a><!-- ENDIF -->
                     <!-- IF forumrow.LAST_POST_TIME -->{forumrow.LAST_POST_SUBJECT}   {L_POST_BY_AUTHOR} {forumrow.LAST_POSTER_FULL}
                    <!-- IF not S_IS_BOT --><a href="{forumrow.U_LAST_POST}">{LAST_POST_IMG}</a> <!-- ENDIF --><br />{forumrow.LAST_POST_TIME}<!-- ELSE -->{L_NO_POSTS}<br /> <!-- ENDIF --></span>
                </dd>
                <dd class="topics">{forumrow.TOPICS}<br /><span>{L_TOPICS}</span><dfn>{L_TOPICS}</dfn></dd>
                <dd class="posts">{forumrow.POSTS}<br /><span>{L_POSTS}</span><dfn>{L_POSTS}</dfn></dd>
</code>```

OwnerDisplayName: Mike Stanford

ContentLicense: CC BY-SA 2.5

Body:
I am using the prosilver theme in phpbb3. In the file forumlist_body.html there is a part that looks like this:

<dfn>{L_LAST_POST}</dfn> {L_POST_BY_AUTHOR} {forumrow.LAST_POSTER_FULL}

  {LAST_POST_IMG}

{forumrow.LAST_POST_TIME}
{L_NO_POSTS}

How would I get that to show the last post title as well. I tried {forumrow.LAST_POST_TITLE} but it didn't work.

Body:
its simple ,,

i have made those modifications ,,

here is the code just replace :

<dd class="lastpost"><span>
                    <!-- IF forumrow.U_UNAPPROVED_TOPICS --><a href="{forumrow.U_UNAPPROVED_TOPICS}">{UNAPPROVED_IMG}</a><!-- ENDIF -->
                     <!-- IF forumrow.LAST_POST_TIME -->{forumrow.LAST_POST_SUBJECT}&nbsp;&nbsp; {L_POST_BY_AUTHOR} {forumrow.LAST_POSTER_FULL}
                    <!-- IF not S_IS_BOT --><a href="{forumrow.U_LAST_POST}">{LAST_POST_IMG}</a> <!-- ENDIF --><br />{forumrow.LAST_POST_TIME}<!-- ELSE -->{L_NO_POSTS}<br />&nbsp;<!-- ENDIF --></span>
                </dd>
                <dd class="topics">{forumrow.TOPICS}<br /><span>{L_TOPICS}</span><dfn>{L_TOPICS}</dfn></dd>
                <dd class="posts">{forumrow.POSTS}<br /><span>{L_POSTS}</span><dfn>{L_POSTS}</dfn></dd>


问:
Tombstone scanning in system.log
I have a cassandra cluster with less delete use case. I found in my system.log "Read 10 live and 5645464 tombstones cells in keyspace.table" What does it mean? please help to understand.

Thanks.

答:
One more important thing to keep in mind when working with Cassandra is that tombstones cells do not directly correlate to deletes.

When you insert null value to an attribute when performing your insert, Cassandra internally marks that attribute/cell as a tombstone. So, even if you don't have a lot of deletes happening, you could end up with an enormous number of tombstones. Easy and simple solution is to not insert null values for an attribute while inserting.

As per this statement Read 10 live and 5645464 tombstones cells in keyspace.table goes, there might be a table scan for a query happening that is scanning 10 cells and 5645464 number of tombstones (cells with null value) while doing so is what I am guessing. Need to understand what type of queries are being executed to gain more insight into that.

Title: Tombstone scanning in system.log


问:
Tensorflow 2.0 Input being creating with first shape element as None
I'm trying to create an Input in the following way:

    Tx = 318
    n_freq = 101
    input_anchor = Input(shape=(n_freq,Tx), name='input_anchor')
```

<p>When I run:</p>

<pre class="lang-py prettyprint-override"><code>    input_anchor.shape
</code>```

I get:

    TensorShape([None, 101, 318])
```

<p>Later when I try to use that input in my model I get the following error:</p>

<pre class="lang-py prettyprint-override"><code>    TypeError: Cannot iterate over a tensor with unknown first dimension.
</code>```

In Tensor flow's opy.py I found this code block which is most likely where my code is failing:

     def __iter__(self):
        if not context.executing_eagerly():
          raise TypeError(
              "Tensor objects are only iterable when eager execution is "
              "enabled. To iterate over this tensor use tf.map_fn.")
        shape = self._shape_tuple()
        if shape is None:
          raise TypeError("Cannot iterate over a tensor with unknown shape.")
        if not shape:
          raise TypeError("Cannot iterate over a scalar tensor.")
        if shape[0] is None:
          raise TypeError(
              "Cannot iterate over a tensor with unknown first dimension.")
        for i in xrange(shape[0]):
          yield self[i]

```

<p>If you want to see my whole model implementation here it is:</p>

<pre class="lang-py prettyprint-override"><code>    def base_model(input_shape):

        X_input = Input(shape = input_shape)

        # Step 1: CONV layer (≈4 lines)
        X = Conv1D(196,kernel_size = 15, strides = 4)(X_input)                                 # CONV1D
        X = BatchNormalization()(X)                                 # Batch normalization
        X = Activation('relu')(X)                                 # ReLu activation
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)

        # Step 2: First GRU Layer (≈4 lines)
        X = LSTM(units = 128, return_sequences = True)(X_input)                                 # GRU (use 128 units and return the sequences)
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)
        X = BatchNormalization()(X)                                 # Batch normalization

        # Step 3: Second GRU Layer (≈4 lines)
        X = LSTM(units = 128, return_sequences = True)(X)                                 # GRU (use 128 units and return the sequences)
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)
        X = BatchNormalization()(X)                                 # Batch normalization
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)

        # Step 4: Third GRU Layer (≈4 lines)
        X = LSTM(units = 128)(X)                                 # GRU (use 128 units and return the sequences)
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)
        X = BatchNormalization()(X)                                 # Batch normalization
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)

        X = Dense(64)(X)

        base_model = Model(inputs = X_input, outputs = X)

        return base_model

    def speech_model(input_shape, base_model):

        #get triplets vectors
        input_anchor = Input(shape=input_shape, name='input_anchor')
        input_positive = Input(shape=input_shape, name='input_positive')
        input_negative = Input(shape=input_shape, name='input_negative')

        vec_anchor = base_model(input_anchor)
        vec_positive = base_model(input_positive)
        vec_negative = base_model(input_negative)

        #Concatenate vectors vec_positive, vec_negative
        concat_layer = concatenate([vec_anchor,vec_positive,vec_negative], axis = -1, name='concat_layer')

        model = Model(inputs = [input_anchor,input_positive,input_negative], outputs = concat_layer, name = 'speech_to_vec')
        #model = Model(inputs = [input_anchor,input_positive,input_negative], outputs = [vec_anchor,vec_positive,vec_negative], name = 'speech_to_vec')
        #model = Model(inputs = [input_anchor,input_positiv], outputs=vec_anchor)

        return model
</code>```

And the line that breaks it all and generates the error mentioned before

    speech_model = speech_model(input_shape = (n_freq, Tx), base_model = base_model)
```

Thanks a lot for reading, any kind of help towards solving this is much appreciated.

答:
Your base_model(input_shape) function requires you to pass in tuple, but you pass Input Layer to it.

```<code># change
vec_anchor = base_model(input_anchor)
vec_positive = base_model(input_positive)
vec_negative = base_model(input_negative)
# to
vec_anchor = base_model(input_shape)
vec_positive = base_model(input_shape)
vec_negative = base_model(input_shape)
</code>```

In addition, you need to correct the input and output of the final model since concatenate can't concat multiple model type.

```<code>concat_layer = concatenate([vec_anchor.output,vec_positive.output,vec_negative.output], axis = -1, name='concat_layer')

model = Model(inputs = [vec_anchor.input,vec_positive.input,vec_negative.input], outputs = concat_layer, name = 'speech_to_vec')
</code>```

Body:
I'm trying to create an Input in the following way:

    Tx = 318
    n_freq = 101
    input_anchor = Input(shape=(n_freq,Tx), name='input_anchor')

When I run:

    input_anchor.shape

I get:

    TensorShape([None, 101, 318])

Later when I try to use that input in my model I get the following error:

    TypeError: Cannot iterate over a tensor with unknown first dimension.

In Tensor flow's opy.py I found this code block which is most likely where my code is failing:

     def __iter__(self):
        if not context.executing_eagerly():
          raise TypeError(
              "Tensor objects are only iterable when eager execution is "
              "enabled. To iterate over this tensor use tf.map_fn.")
        shape = self._shape_tuple()
        if shape is None:
          raise TypeError("Cannot iterate over a tensor with unknown shape.")
        if not shape:
          raise TypeError("Cannot iterate over a scalar tensor.")
        if shape[0] is None:
          raise TypeError(
              "Cannot iterate over a tensor with unknown first dimension.")
        for i in xrange(shape[0]):
          yield self[i]

If you want to see my whole model implementation here it is:

    def base_model(input_shape):

        X_input = Input(shape = input_shape)

        # Step 1: CONV layer (≈4 lines)
        X = Conv1D(196,kernel_size = 15, strides = 4)(X_input)                                 # CONV1D
        X = BatchNormalization()(X)                                 # Batch normalization
        X = Activation('relu')(X)                                 # ReLu activation
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)

        # Step 2: First GRU Layer (≈4 lines)
        X = LSTM(units = 128, return_sequences = True)(X_input)                                 # GRU (use 128 units and return the sequences)
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)
        X = BatchNormalization()(X)                                 # Batch normalization

        # Step 3: Second GRU Layer (≈4 lines)
        X = LSTM(units = 128, return_sequences = True)(X)                                 # GRU (use 128 units and return the sequences)
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)
        X = BatchNormalization()(X)                                 # Batch normalization
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)

        # Step 4: Third GRU Layer (≈4 lines)
        X = LSTM(units = 128)(X)                                 # GRU (use 128 units and return the sequences)
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)
        X = BatchNormalization()(X)                                 # Batch normalization
        X = Dropout(rate = 0.2)(X)                                 # dropout (use 0.8)

        X = Dense(64)(X)

        base_model = Model(inputs = X_input, outputs = X)

        return base_model

    def speech_model(input_shape, base_model):

        #get triplets vectors
        input_anchor = Input(shape=input_shape, name='input_anchor')
        input_positive = Input(shape=input_shape, name='input_positive')
        input_negative = Input(shape=input_shape, name='input_negative')

        vec_anchor = base_model(input_anchor)
        vec_positive = base_model(input_positive)
        vec_negative = base_model(input_negative)

        #Concatenate vectors vec_positive, vec_negative
        concat_layer = concatenate([vec_anchor,vec_positive,vec_negative], axis = -1, name='concat_layer')

        model = Model(inputs = [input_anchor,input_positive,input_negative], outputs = concat_layer, name = 'speech_to_vec')
        #model = Model(inputs = [input_anchor,input_positive,input_negative], outputs = [vec_anchor,vec_positive,vec_negative], name = 'speech_to_vec')
        #model = Model(inputs = [input_anchor,input_positiv], outputs=vec_anchor)

        return model

And the line that breaks it all and generates the error mentioned before

    speech_model = speech_model(input_shape = (n_freq, Tx), base_model = base_model)

Thanks a lot for reading, any kind of help towards solving this is much appreciated.

Body:
Your base_model(input_shape) function requires you to pass in tuple, but you pass Input Layer to it.

# change
vec_anchor = base_model(input_anchor)
vec_positive = base_model(input_positive)
vec_negative = base_model(input_negative)
# to
vec_anchor = base_model(input_shape)
vec_positive = base_model(input_shape)
vec_negative = base_model(input_shape)

In addition, you need to correct the input and output of the final model since concatenate can't concat multiple model type.

concat_layer = concatenate([vec_anchor.output,vec_positive.output,vec_negative.output], axis = -1, name='concat_layer')

model = Model(inputs = [vec_anchor.input,vec_positive.input,vec_negative.input], outputs = concat_layer, name = 'speech_to_vec')


问:
PrimeNG TurboTable | Dynamic Columns | Export What is Displayed/Formatted Not actual Model Values
Facing issues with date. Showing date after formatting on UI and want the same to be exported.

```<code><ng-template pTemplate="body" let-rowData let-columns="columns">
            <tr>
                <td *ngFor="let col of columns">
                    <span *ngIf="col.field !=='startDate' && col.field !=='endDate'
                     && col.field !=='when'; else datefield">
                        {{rowData[col.field]}}
                    </span>
                    <ng-template #datefield>
                        <span *ngIf="col.field !=='when'">{{rowData[col.field] | date:'dd-MMM-yyyy'}}</span>
                        <span *ngIf="col.field ==='when'">{{rowData[col.field] | datex:'DD-MMM-YYYY HH:mm:ss.SSS A'}}</span>
                    </ng-template>
                </td>
            </tr>
</ng-template>
</code>```

Any help will be appriciated !

答: I wanted the same thing on one of my projects, but sadly the export feature only sends the raw data to CSV. You can see how it works on their github. If you want formatted data, you'll have to find another library or roll your own. A great solution would use the same Angular pipe transform() method directly.</p>

Body:
Facing issues with date. Showing date after formatting on UI and want the same to be exported.

<ng-template pTemplate="body" let-rowData let-columns="columns">

                        {{rowData[col.field]}}

                    <ng-template #datefield>
                        {{rowData[col.field] | date:'dd-MMM-yyyy'}}
                        {{rowData[col.field] | datex:'DD-MMM-YYYY HH:mm:ss.SSS A'}}
                    </ng-template>

</ng-template>

Any help will be appriciated !


问:
Getting rid of "jumps" between facet grids
I am using facet_grid in order to have two labels for the x-axis.

My data looks like this:

```<code>library(dplyr)
library(tidyverse)
library(ggplot2)
set.seed(22)
df <- c(1:1260)
df <- as_tibble(c(1:1260))
colnames(df)[1] <- "price"
df$price[1] <- 100
for (i in seq(2,1260)){df$price[i]<- df$price[i-1]*0.8 + rlnorm(1, 2, 2)}
df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
                  "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)
</code>```

Using this code by user M-M:

```<code>df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
                  "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

#solution:
month_lab <- rep(unique(df$month), length(unique(df$year)))

year_lab <- unique(df$year)

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = year)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = month_lab, expand = c(0,0)) +
  facet_grid(~year, space="free_x", scales="free_x", switch="x") +
  theme(strip.placement = "outside",
        strip.background = element_rect(fill=NA,colour="grey50"),
        panel.spacing=unit(0,"cm"))
</code>```

I get almost exactly what I strive for except for the jumps the line makes between years as marked in the picure:

Is there a way to make the line continious?

答:
My understanding of this is there is no clean way to do this with facets as ggplot will not join the dots. One way to get around this may be to add an extra data point at the end of each year group that is equal to the start of each year group,

```<code>df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  split(.$year) %>%
  lapply(., function(x) bind_rows(x, data.frame(price = NA, month = "Dez", year = unique(x$year)[[1]], stringsAsFactors = FALSE))) %>%
  bind_rows() %>%
  mutate(price = ifelse(is.na(price), lead(price), price)) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = year)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = month_lab, expand = c(0,0)) +
  facet_grid(~year,space="free_x", scales="free_x", switch="x") +
  theme(strip.placement = "outside",
        strip.background = element_rect(fill=NA,colour="grey50"),
        panel.spacing=unit(0,"cm"))
</code>```

Why not just use a normal axis with date labels Month-Year like (Jan-2001)? this can be done nicely and prettily using other formats outline here, you can rotate the labels for neatness etc.

An alternative would be to create normal Date labels, put it all on the same plot and simply format the dates to be a little more pleasing to the eye in the form of Mon Year using format(). I find this to be more correct and also simpler to formulate. Using plotly you can do this type of thing using groups and subgroups as shown in an example here.

```<code># Change to Numeric month
df$month <- rep(c("01", "02", "03", "04", "05", "06",
                  "07", "08", "09", "10", "11", "12"), 5, each=21)

# Choose real time window in years I chose 2000-2004
df$year <- rep(c("2000", "2001", "2002", "2003", "2004" ), 1, each=252)
month_lab <- rep(unique(df$month), length(unique(df$year)))

# Construct a date label not just a month
year_lab <- rep(unique(df$year), 12)
Date_lab <- sort(as.Date(paste0(year_lab, month_lab, "01"), "%Y%m%d"))

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = 1)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = format(Date_lab, "%b %Y"), expand = c(0,0)) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1),
        strip.background = element_rect(fill=NA,colour="grey50"))
</code>```

In response to Comment, you can do this by taking the sorted Date_lab variable and replacing the years withyou required string. A quick way might be with gsub but then you also run into the problem with Year 0 but that can just be changed however you see fit. Once the labels are sorted in the correct order, you can do whatever you want with them, just remove the call to format in the ggplot section. ie

```<code>Date_lab <-
  gsub("(200)", "Year ", format(sort(as.Date(paste0(year_lab, month_lab, "01"), "%Y%m%d")), "%Y %b"))

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = 1)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = Date_lab, expand = c(0,0)) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1),
        strip.background = element_rect(fill=NA,colour="grey50"))
</code>```

Body:
I am using facet_grid in order to have two labels for the x-axis.

My data looks like this:

library(dplyr)
library(tidyverse)
library(ggplot2)
set.seed(22)
df <- c(1:1260)
df <- as_tibble(c(1:1260))
colnames(df)[1] <- "price"
df$price[1] <- 100
for (i in seq(2,1260)){df$price[i]<- df$price[i-1]*0.8 + rlnorm(1, 2, 2)}
df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
                  "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

Using this code by user M-M:

df$month <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
                  "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5, each=21)

df$year <- rep(c("Year 1", "Year 2", "Year 3", "Year 4", "Year 5" ), 1, each=252)

#solution:
month_lab <- rep(unique(df$month), length(unique(df$year)))

year_lab <- unique(df$year)

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = year)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = month_lab, expand = c(0,0)) +
  facet_grid(~year, space="free_x", scales="free_x", switch="x") +
  theme(strip.placement = "outside",
        strip.background = element_rect(fill=NA,colour="grey50"),
        panel.spacing=unit(0,"cm"))

I get almost exactly what I strive for except for the jumps the line makes between years as marked in the picure:

Is there a way to make the line continious?

Body:
My understanding of this is there is no clean way to do this with facets as ggplot will not join the dots. One way to get around this may be to add an extra data point at the end of each year group that is equal to the start of each year group,

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  split(.$year) %>%
  lapply(., function(x) bind_rows(x, data.frame(price = NA, month = "Dez", year = unique(x$year)[[1]], stringsAsFactors = FALSE))) %>%
  bind_rows() %>%
  mutate(price = ifelse(is.na(price), lead(price), price)) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = year)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = month_lab, expand = c(0,0)) +
  facet_grid(~year,space="free_x", scales="free_x", switch="x") +
  theme(strip.placement = "outside",
        strip.background = element_rect(fill=NA,colour="grey50"),
        panel.spacing=unit(0,"cm"))

Why not just use a normal axis with date labels Month-Year like (Jan-2001)? this can be done nicely and prettily using other formats outline here, you can rotate the labels for neatness etc.

An alternative would be to create normal Date labels, put it all on the same plot and simply format the dates to be a little more pleasing to the eye in the form of Mon Year using format(). I find this to be more correct and also simpler to formulate. Using plotly you can do this type of thing using groups and subgroups as shown in an example here.

# Change to Numeric month
df$month <- rep(c("01", "02", "03", "04", "05", "06",
                  "07", "08", "09", "10", "11", "12"), 5, each=21)

# Choose real time window in years I chose 2000-2004
df$year <- rep(c("2000", "2001", "2002", "2003", "2004" ), 1, each=252)
month_lab <- rep(unique(df$month), length(unique(df$year)))

# Construct a date label not just a month
year_lab <- rep(unique(df$year), 12)
Date_lab <- sort(as.Date(paste0(year_lab, month_lab, "01"), "%Y%m%d"))

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = 1)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = format(Date_lab, "%b %Y"), expand = c(0,0)) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1),
        strip.background = element_rect(fill=NA,colour="grey50"))

In response to Comment, you can do this by taking the sorted Date_lab variable and replacing the years withyou required string. A quick way might be with gsub but then you also run into the problem with Year 0 but that can just be changed however you see fit. Once the labels are sorted in the correct order, you can do whatever you want with them, just remove the call to format in the ggplot section. ie

Date_lab <-
  gsub("(200)", "Year ", format(sort(as.Date(paste0(year_lab, month_lab, "01"), "%Y%m%d")), "%Y %b"))

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames), y = price,
             group = 1)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21),
                     labels = Date_lab, expand = c(0,0)) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1),
        strip.background = element_rect(fill=NA,colour="grey50"))


问:
Migrated Web Forms Application .NET 2.0 -> 3.5, new infrastructure - Images Not Caching in IE 6
I have been migrating a .NET 2.0 web forms application to use .NET 3.5 and a new infrastructure. There is a GridView inside an UpdatePanel, with an Actions column which contains icons to perform an action for that row. A problem that I am having in IE 6 is that images are not caching. This is particularly noticeable on the Actions column because there are 9 icons x 100 rows = 900 icons to load. Internet Explorer counts down these images from 900 until they are all loaded.

This problem does not appear to be limited to the images inside the GridView which is inside an UpdatePanel because I can see header images being reloaded each time there is a page refresh.

I have done my research:

Anyone have ideas for solving the "n items remaining" problem on Internet Explorer? - this is a different problem.

Dear IE6: Please Cache my Images. - I did think that this would solve all of the problems, but no. I have tried setting the image as a background image inside a div but no success. I also tried putting all icons inside a User Control and including this before the GridView is loaded.

I have an old infrastructure (where this problem did not exist) to compare IIS configurations and they are exactly the same.

Using Fiddler I can frustratingly see each image being requested. The Cache Header is Cache-Control: private. Just noticed Date: Tue, 29 Mar 2011 07:35:53 GMT (which is an hour ago) in this Cache Header. Does that have anything to do with it?

This caching problem appears to be intermittent. I will load the page up for the first time and no images will be cached so ~1000 images will be independently loaded. I may refresh the page and images will be cached. If I delete all temporary files/offline content then the images will be loaded independently again.

At first I thought this only occurred when deploying the application to the new infrastructure (requests being made cross-forest) but it does happen on my local machine too when all images are local.

This is only a problem in IE 6!!!

Please let me know if I can provide other information.

UPDATE 1

Workarounds which have already been attempted with no success:

The handler solution proposed by @Afshin Gh. UPDATE 2 The code in the answer actually works. A different version must have been attempted previously.

The hidden images solution proposed by @Blue Steel.

UPDATE 2

Some of the other solutions may have worked here but I have gone with the code provided by @Afshin Gh.

答:
I suggest to set this cache parameters on header.

```<code>Response.Cache.AppendCacheExtension("post-check=900, pre-check=3600");
</code>```

You can read more about here http://www.rdlt.com/cache-control-post-check-pre-check.html or google it.

Check it out and tell me if this solve your issue.

Body:
I suggest to set this cache parameters on header.

Response.Cache.AppendCacheExtension("post-check=900, pre-check=3600");

You can read more about here http://www.rdlt.com/cache-control-post-check-pre-check.html or google it.

Check it out and tell me if this solve your issue.


问:
How to use Koin in multiple module?
There are two modules in my android project, app module and lib module.

Both these two modules need Koin for D.I., so I call startKoin in MyApplication class in app module, and IninKointContentProvider in lib module as below.

```<code>// app module
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin(this, modules1)
    }
}

// lib module
class InitKoinContentProvider : ContentProvider() {
    override fun onCreate(): Boolean {
        startKoin(context.applicationContext, modules2)
        return true
    }
}
</code>```

Then app crashed and shown this message

```<code>Caused by: org.koin.error.BeanOverrideException: Try to override definition with Single [class='android.content.Context'], but override is not allowed. Use 'override' option in your definition or module.
</code>```

I guess startKoin can be called only one time.

The solution I found is merging two koin modules then calling startKoin in MyApplication, but I don't like it. Lib module may be imported by other android project which doesn't use koin, in that case, I think calling startKoin in InitKoinContentProvider is better.

Any solution for this problem?? Thanks!

答:
I found the best solution inspired by @laalto's answer, thanks!

Upgrade to koin 2.0, then use KoinApplication and customized KoinComponent to create a isolated koin context, it can let lib module using koin without any initializing call by app module, still start koin in ContentProvider. The whole code may like below.

```<code>// app module
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin {
            androidContext(this@MyApplication)
            modules(module{
                viewModel { MainViewModel() }
            })
        }
    }
}

class MainActivity: AppCompactActivity() {
    private val viewModel: MainViewModel by viewModel()
}

// lib module
internal object MyKoinContext {
    lateinit var koinApplication: KoinApplication
}

interface MyKoinComponent : KoinComponent {
    override fun getKoin(): Koin {
        return MyKoinContext.koinApplication.koin
    }
}

class InitKoinContentProvider : ContentProvider() {
    override fun onCreate(): Boolean {
        MyKoinContext.koinApplication = koinApplication {
            androidContext(context.applicationContext)
            modules(module{
                viewModel { FooViewModel() }
            })
        }
        return true
    }
}

class FooActivity: AppCompactActivity(), MyKoinComponent {
    private val viewModel: FooViewModel by viewModel()
}
</code>```

Ref:
https://insert-koin.io/docs/2.0/documentation/reference/index.html#_koin_context_isolation

Title: How to use Koin in multiple module?

Body:
There are two modules in my android project, app module and lib module.

Both these two modules need Koin for D.I., so I call startKoin in MyApplication class in app module, and IninKointContentProvider in lib module as below.

// app module
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin(this, modules1)
    }
}

// lib module
class InitKoinContentProvider : ContentProvider() {
    override fun onCreate(): Boolean {
        startKoin(context.applicationContext, modules2)
        return true
    }
}

Then app crashed and shown this message

Caused by: org.koin.error.BeanOverrideException: Try to override definition with Single [class='android.content.Context'], but override is not allowed. Use 'override' option in your definition or module.

I guess startKoin can be called only one time.

The solution I found is merging two koin modules then calling startKoin in MyApplication, but I don't like it. Lib module may be imported by other android project which doesn't use koin, in that case, I think calling startKoin in InitKoinContentProvider is better.

Any solution for this problem?? Thanks!

Body:
I found the best solution inspired by @laalto's answer, thanks!

Upgrade to koin 2.0, then use KoinApplication and customized KoinComponent to create a isolated koin context, it can let lib module using koin without any initializing call by app module, still start koin in ContentProvider. The whole code may like below.

// app module
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin {
            androidContext(this@MyApplication)
            modules(module{
                viewModel { MainViewModel() }
            })
        }
    }
}

class MainActivity: AppCompactActivity() {
    private val viewModel: MainViewModel by viewModel()
}

// lib module
internal object MyKoinContext {
    lateinit var koinApplication: KoinApplication
}

interface MyKoinComponent : KoinComponent {
    override fun getKoin(): Koin {
        return MyKoinContext.koinApplication.koin
    }
}

class InitKoinContentProvider : ContentProvider() {
    override fun onCreate(): Boolean {
        MyKoinContext.koinApplication = koinApplication {
            androidContext(context.applicationContext)
            modules(module{
                viewModel { FooViewModel() }
            })
        }
        return true
    }
}

class FooActivity: AppCompactActivity(), MyKoinComponent {
    private val viewModel: FooViewModel by viewModel()
}

Ref:
https://insert-koin.io/docs/2.0/documentation/reference/index.html#_koin_context_isolation


问:
Postgres ORDER BY twice DESC then ASC
I have a recursive query

```<code>With RECURSIVE tree AS
 (
 SELECT * FROM comments WHERE id = 83
 UNION
 SELECT t.*
      From comments t
 JOIN tree rt ON rt.parent_id = t.id

 )
 SELECT * from tree ORDER BY id DESC LIMIT 5
</code>```

How would I order it one more time by ASC?

Edit1: tried this solution:
Get the last N rows in the database in order?

```<code>With RECURSIVE tree AS
 (
 SELECT * FROM comments WHERE id = 83
 UNION
 SELECT t.*
      From comments t
 JOIN tree rt ON rt.parent_id = t.id

 )
 select * from (SELECT * from tree ORDER BY id DESC LIMIT 5) order by id
</code>```

Gives me an error:

```<code>ERROR:  subquery in FROM must have an alias
</code>```

答:
In PostgreSQL all table expressions (the selects right after FROM) need to be named. That is, they need to have an alias. Just add any alias. For example I added x, as in:

```<code>With RECURSIVE tree AS
 (
 SELECT * FROM comments WHERE id = 83
 UNION
 SELECT t.*
      From comments t
 JOIN tree rt ON rt.parent_id = t.id

 )
 select * from (SELECT * from tree ORDER BY id DESC LIMIT 5) x order by id
</code>```

Did you spot it?

Title: Postgres ORDER BY twice DESC then ASC

Body:
I have a recursive query

With RECURSIVE tree AS
 (
 SELECT * FROM comments WHERE id = 83
 UNION
 SELECT t.*
      From comments t
 JOIN tree rt ON rt.parent_id = t.id

 )
 SELECT * from tree ORDER BY id DESC LIMIT 5

How would I order it one more time by ASC?

Edit1: tried this solution:
Get the last N rows in the database in order?

With RECURSIVE tree AS
 (
 SELECT * FROM comments WHERE id = 83
 UNION
 SELECT t.*
      From comments t
 JOIN tree rt ON rt.parent_id = t.id

 )
 select * from (SELECT * from tree ORDER BY id DESC LIMIT 5) order by id

Gives me an error:

ERROR:  subquery in FROM must have an alias

Body:
In PostgreSQL all table expressions (the selects right after FROM) need to be named. That is, they need to have an alias. Just add any alias. For example I added x, as in:

With RECURSIVE tree AS
 (
 SELECT * FROM comments WHERE id = 83
 UNION
 SELECT t.*
      From comments t
 JOIN tree rt ON rt.parent_id = t.id

 )
 select * from (SELECT * from tree ORDER BY id DESC LIMIT 5) x order by id

Did you spot it?


问:
Word2Vec with POS not producing expected results?
I am trying to gauge the impact of part of speech information with Word2Vec embeddings but am not obtaining expected results.

I expected POS included word2vec embeddings to perform better in a machine translation task but it is actually performing worse.

I am creating two sets of embedding off of the same corpus using Gensim, one is normal Word2Vec, the other, I am changing tokens to "[WORD]__[POS]".

I am gauging differences in performance by using the embeddings in a Seq2Seq machine translation task. I am evaluating the two approaches with BLEU

This is how I am training the word2vec + POS embeddings with SpaCy:

```<code>sentences = []
    for sent in doc.sents:
        tokens = []
        for t in sent:
            tokens += ["{}__{}".format(t.text, t.pos_)]
        sentences += tokens
    pos_train += [sentences]
</code>```

This is my benchmark machine translation model with Keras + Tensorflow:

```<code>encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(LATENT_DIM, return_state=True)
_, state_h, state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]

decoder_inputs = Input(shape=(None, num_decoder_tokens))
decoder_lstm = LSTM(LATENT_DIM, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
</code>```

With BLEU, the Word2Vec+POS approach consistently scores the same as Word2Vec or 0.01-0.02 points below the normal Word2Vec embeddings.

Does anyone know why this might be happening? Is there a gap in my reasoning or expectations?

答:
I, too, would have expected accurate part-of-speech info to improve translation – but I don't know if others have reported such an improvement. Some (uninformed) conjectures as to why it might not:

maybe the POS tagging isn't very accurate with regard to one of the languages, or there are some other anomalous challenges specific to your data

maybe the method of creating composite tokens, with the internal __, is in a few corner cases interfering with evaluation – for example, if the original corpus retains any tokens which already had __ in them

maybe for certain cases of insufficient data, the collision of similar-meaning homographs of different parts-of-speech actually helps thicken the vaguer meaning-to-meaning translation. (For example, maybe given the semantic relatedness of shop_NOUN and shop_VERB, it's better to have 100 colliding examples of shop than 50 of each.)

Some debugging ideas (in addition to the obvious "double-check everything"):

look closely at exactly those test cases where the plain-vs-POS approaches differ in their scoring; see if there are any patterns – like strange tokens/punctuation, nonstandard grammar, etc – giving clues to where the __POS decorations hurt

try other language pairs, and other (private or public) concordance datasets, to see if elsewhere (or in general) the POS-tagging does help, and there's something extra-challenging about your particular dataset/language-pair

consider that the multiplication-of-tokens (by splitting homographs into POS-specific variants) has changed the model size & word-distributions, in ways that might interact with other limits (like min_count, max_vocab_size, etc) in ways that modify training. In particular, perhaps the larger-vocabulary POS model should get more training epochs, or a larger word-vector dimensionality, to reflect its larger vocabulary with a lower average number of word-occurrences.

Good luck!

Body:
I am trying to gauge the impact of part of speech information with Word2Vec embeddings but am not obtaining expected results.

I expected POS included word2vec embeddings to perform better in a machine translation task but it is actually performing worse.

I am creating two sets of embedding off of the same corpus using Gensim, one is normal Word2Vec, the other, I am changing tokens to "[WORD]__[POS]".

I am gauging differences in performance by using the embeddings in a Seq2Seq machine translation task. I am evaluating the two approaches with BLEU

This is how I am training the word2vec + POS embeddings with SpaCy:

sentences = []
    for sent in doc.sents:
        tokens = []
        for t in sent:
            tokens += ["{}__{}".format(t.text, t.pos_)]
        sentences += tokens
    pos_train += [sentences]

This is my benchmark machine translation model with Keras + Tensorflow:

encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(LATENT_DIM, return_state=True)
_, state_h, state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]

decoder_inputs = Input(shape=(None, num_decoder_tokens))
decoder_lstm = LSTM(LATENT_DIM, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

model = Model([encoder_inputs, decoder_inputs], decoder_outputs)

With BLEU, the Word2Vec+POS approach consistently scores the same as Word2Vec or 0.01-0.02 points below the normal Word2Vec embeddings.

Does anyone know why this might be happening? Is there a gap in my reasoning or expectations?