问:
How can I sync Folders from a Serverfile to a client computer with powershell?
I have some issue with Sync center on my computer since I upgrade it to W10, so I try to write an alternative script that compare the sync folders/files on a desktop and our ServerFiles and copy the latest version of each folders/files on the user computer.

Thanks to the community I found some code, but it's doesnt work well for me

Help1 Help2

I'm a newbie on scripting with powershell 5.1. Im working with a WS2008 and the desktop on W10.

```<code>$SourceFolder = Get-ChildItem -Recurse "\\Srvfiles\USERS\user1\"
#"user1" contains 2 folders and each one have subfolders/files

$TargetFolder = Get-ChildItem "D:\Doc_Sync"

$Result = Compare-Object $SourceFolder $TargetFolder -Property Name, Length

foreach ($folder in $Result) {
        if ($folder.SideIndicator -eq "<=") {
            $FullSourceObject = $folder.InputObject.FullName
            $FullTargetObject = $folder.InputObject.FullName.Replace($SourceFolder, $TargetFolder)

            Copy-Item "\\Srvfiles\USERS\user1\$($_.name)" -Destination $Get-ChildItem "D:\Doc_Sync" -Recurse -Force
            }
        }
</code>```

The good new is it working  for somes folders, on D:/Doc_Sync it paste most of the files but(bad new), for the rest of them , I got many error :

```<code>Cannot bind argument to parameter « DifferenceObject » because it is null.
At line:5 char:40
+ $Result = Compare-Object $SourceFolder $TargetFolder -Property Name,  ...
+                                        ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData : (:) [Compare-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CompareObjectCommand

You cannot call a method on a null-valued expression.
At line:10 char:13
+             $FullTargetObject = $folder.InputObject.FullName.Replace( ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
</code>```

Thanks for your futur help

答:
I found what's wrong with the first error, thanks to the breakpoints. I changed the $TargetFolder like this :

```<code>$TargetFolder = @(Get-ChildItem -Recurse "D:\Doc_Sync")
</code>```

But I still have the second error with the "$FullTargetObject". Idk what's wrong with that line... I'll work on it this weekend.

Body:
I have some issue with Sync center on my computer since I upgrade it to W10, so I try to write an alternative script that compare the sync folders/files on a desktop and our ServerFiles and copy the latest version of each folders/files on the user computer.

Thanks to the community I found some code, but it's doesnt work well for me

Help1 Help2

I'm a newbie on scripting with powershell 5.1. Im working with a WS2008 and the desktop on W10.

$SourceFolder = Get-ChildItem -Recurse "\\Srvfiles\USERS\user1\"
#"user1" contains 2 folders and each one have subfolders/files

$TargetFolder = Get-ChildItem "D:\Doc_Sync"

$Result = Compare-Object $SourceFolder $TargetFolder -Property Name, Length

foreach ($folder in $Result) {
        if ($folder.SideIndicator -eq "<=") {
            $FullSourceObject = $folder.InputObject.FullName
            $FullTargetObject = $folder.InputObject.FullName.Replace($SourceFolder, $TargetFolder)

            Copy-Item "\\Srvfiles\USERS\user1\$($_.name)" -Destination $Get-ChildItem "D:\Doc_Sync" -Recurse -Force
            }
        }

The good new is it working  for somes folders, on D:/Doc_Sync it paste most of the files but(bad new), for the rest of them , I got many error :

Cannot bind argument to parameter « DifferenceObject » because it is null.
At line:5 char:40
+ $Result = Compare-Object $SourceFolder $TargetFolder -Property Name,  ...
+                                        ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData : (:) [Compare-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CompareObjectCommand

You cannot call a method on a null-valued expression.
At line:10 char:13
+             $FullTargetObject = $folder.InputObject.FullName.Replace( ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Thanks for your futur help

Body:
I found what's wrong with the first error, thanks to the breakpoints. I changed the $TargetFolder like this :

$TargetFolder = @(Get-ChildItem -Recurse "D:\Doc_Sync")

But I still have the second error with the "$FullTargetObject". Idk what's wrong with that line... I'll work on it this weekend.


来源: stackexchange

问:
How can I delete the elements of array on MATLAB?
The following code is executed but I have no idea to delete the elements of array on MATLAB.

And therefore, Array1 and Array2 are written out with the former data.

MATLAB version R2017b

```<code>global Array1
global Array2
filename = 'data.xlsx';
for i = 1:3
    sheet = i
    for j = (1:2)-1
        one = [1];
        two = [2];
        Array1 = [Array1; one]
        Array2 = [Array2; two]
    end
    xlswrite(filename, Array1, sheet, 'A1');
    xlswrite(filename, Array2, sheet, 'B1');
    %here I would like to delete the elements of Array1 and Array2global
    %Array1 = [];
    %Array2 = [];
end
</code>```

答:
You can overwrite Array1 with an empty array to remove all its elements: Array1 = []. You would do this either at the top or the bottom of your outer loop:

```<code>filename = 'data.xlsx';
for sheet = 1:3
    Array1 = [];
    Array2 = [];
    for j = 0:1
        one = 1;
        two = 2;
        Array1(end+1) = one;
        Array2(end+1) = two;
    end
    xlswrite(filename, Array1, sheet, 'A1');
    xlswrite(filename, Array2, sheet, 'B1');
end
</code>```

I have also changed your code a bit for best practices. Some of these are recommended also by the MATLAB editor (look for the red underlines, and hover your mouse over them to get tips). I recommend you look at the differences with your code. Notably, try to avoid global variables!

But because you know how many elements the Array1 will have in this case, it is much better (faster) to preallocate, rather than assigning an empty array and then adding elements at the end. For example:

```<code>Array1 = zeros(N,1);
for j = 1:N
   Array1(j) = j-1;
end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The following code is executed but I have no idea to delete the elements of array on MATLAB.

And therefore, Array1 and Array2 are written out with the former data.

MATLAB version R2017b

global Array1
global Array2
filename = 'data.xlsx';
for i = 1:3
    sheet = i
    for j = (1:2)-1
        one = [1];
        two = [2];
        Array1 = [Array1; one]
        Array2 = [Array2; two]
    end
    xlswrite(filename, Array1, sheet, 'A1');
    xlswrite(filename, Array2, sheet, 'B1');
    %here I would like to delete the elements of Array1 and Array2global
    %Array1 = [];
    %Array2 = [];
end

Body:
You can overwrite Array1 with an empty array to remove all its elements: Array1 = []. You would do this either at the top or the bottom of your outer loop:

filename = 'data.xlsx';
for sheet = 1:3
    Array1 = [];
    Array2 = [];
    for j = 0:1
        one = 1;
        two = 2;
        Array1(end+1) = one;
        Array2(end+1) = two;
    end
    xlswrite(filename, Array1, sheet, 'A1');
    xlswrite(filename, Array2, sheet, 'B1');
end

I have also changed your code a bit for best practices. Some of these are recommended also by the MATLAB editor (look for the red underlines, and hover your mouse over them to get tips). I recommend you look at the differences with your code. Notably, try to avoid global variables!

But because you know how many elements the Array1 will have in this case, it is much better (faster) to preallocate, rather than assigning an empty array and then adding elements at the end. For example:

Array1 = zeros(N,1);
for j = 1:N
   Array1(j) = j-1;
end


问:
How to make the result displayed in minutes?
I have a code that takes the data from the dictionary and writes it into a label, but in which they are. And I need to do so that it is recorded in the format of minutes, that is:

minutes: seconds

mm: ss

Here is the code that performs the mapping to the label:

```<code>private void updateRatingLabels2()
    {
        var tops = AllNames2()
          .OrderBy(pair => pair.Value)
          .ThenBy(pair => pair.Key, StringComparer.Ordinal)
          .Take(5)
          .ToArray();

        for (int i = 23; i <= 27; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 33; i <= 37; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 23}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 33}", true).First().Text = tops[i].Value.ToString();
        }
    }
</code>```

答:
If the value within the dictionary is a string of datetime you could try using DateTime.Parse like this: </p>

```<code>var val = tops[i].Value.ToString();
 Controls.Find($"label{i + 33}", true).First().Text = DateTime.Parse(val).ToString("mm:ss") ;
</code>```

Body:
I have a code that takes the data from the dictionary and writes it into a label, but in which they are. And I need to do so that it is recorded in the format of minutes, that is:

minutes: seconds

mm: ss

Here is the code that performs the mapping to the label:

private void updateRatingLabels2()
    {
        var tops = AllNames2()
          .OrderBy(pair => pair.Value)
          .ThenBy(pair => pair.Key, StringComparer.Ordinal)
          .Take(5)
          .ToArray();

        for (int i = 23; i <= 27; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 33; i <= 37; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 23}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 33}", true).First().Text = tops[i].Value.ToString();
        }
    }

Body:
If the value within the dictionary is a string of datetime you could try using DateTime.Parse like this:

var val = tops[i].Value.ToString();
 Controls.Find($"label{i + 33}", true).First().Text = DateTime.Parse(val).ToString("mm:ss") ;


问:
How to set color of existing css class, from props of a react component
I am trying to modify the styling (colors) of existing class from the videojs Library.

I found that we can modify from css file. But I need to modify from the colour we get from react props, which is dynamic each time.

So, we have a class called vjs-control-bar coming from the videojs library to which we need to apply a color property with the value coming from react-props for eg. this.props.color. How we can achieve this ?

```<code><div data-vjs-player>
  <video ref={node => (this.videoNode = node)} className="video-js" />
</div>
</code>```

The vjs-control-bar class wasn't here as it is coming from the video-js library

答:
The right approach here would be to use one of those CSSinJS libraries and add rules that target the DOM elements that are rendered by the VideoJS library you are using.

Another alternative is to simply render a  tag in the component where you render the <video> component using the dangerouslySetInnerHTML prop.

Here is an example of how this might work:

function InnerComponent() {
  return
Text Color
;
}

function App(props) {
  return (

Body:
I am trying to modify the styling (colors) of existing class from the videojs Library.

I found that we can modify from css file. But I need to modify from the colour we get from react props, which is dynamic each time.

So, we have a class called vjs-control-bar coming from the videojs library to which we need to apply a color property with the value coming from react-props for eg. this.props.color. How we can achieve this ?

  <video ref={node => (this.videoNode = node)} className="video-js" />

The vjs-control-bar class wasn't here as it is coming from the video-js library

Body:
The right approach here would be to use one of those CSSinJS libraries and add rules that target the DOM elements that are rendered by the VideoJS library you are using.

Another alternative is to simply render a <style></style> tag in the component where you render the <video> component using the dangerouslySetInnerHTML prop.

Here is an example of how this might work:

function InnerComponent() {
  return <h1 class="title">Text Color</h1>;
}

function App(props) {
  return (
    <div className="App">
      <style
        dangerouslySetInnerHTML={{
          __html: `
        .title {
          color: ${props.color};
        }
      `
        }}
      />
      <h1>Hello CodeSandbox</h1>
      <InnerComponent />
    </div>
  );
}

Here is sandbox - https://codesandbox.io/embed/white-star-9o897


问:
Google Script to export as xlsx not working
```<code>function exportSpreadsheet() {
  var destination = SpreadsheetApp.create('Temp');
  var dest1 = destination.getActiveSheet().setName('출고입력 거래처정보(상단)');
  var dest2 = destination.insertSheet('출고입력 폼목정보(하단)');
  var source1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('출고입력 거래처정보(상단)').getDataRange();
  var source2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('출고입력 폼목정보(하단)').getDataRange();
  var source1Data = source1.getValues();
  var source2Data = source2.getValues();
  var s1Rows = source1.getNumRows();
  var s1Columns = source1.getNumColumns();
  var s2Rows = source2.getNumRows();
  var s2Columns = source2.getNumColumns();

  // Copy Data to Temp file
  for(var i = 0; i<s1Rows; i++){
  for(var j = 0; j<s1Columns; j++) {
       dest1.getRange(i+1,j+1).setValue(source1Data[i][j]);
    }
  }

  for(var i = 0; i<s2Rows; i++){
    for(var j = 0; j<s2Columns; j++) {
        dest2.getRange(i+1,j+1).setValue(source2Data[i][j]);
    }
  }

  // Export to xlsx
  var ssID = destination.getId();
  var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export"+"?format=xlsx";

  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};

  var response = UrlFetchApp.fetch(url, params).getBlob();
  // Save to drive
  var folder = DriveApp.getFolderById('1vDFMM2EfRe1unR6hJOsKapfJrcwxRkxy');
  folder.createFile(response).setName('출고.xlsx');

  // Delete Temp file
  DriveApp.getFilesByName('Temp').next().setTrashed(true);

}
</code>```

I am trying to export two tabs from my spreadsheet and save it as a xlsx file. In doing so I have copied the two tabs to a new spreadsheet and then exporting to xlsx using the following code. I have read through almost all posts that deal with export to xlsx via Google Script and have concluded they are all variations of the code below. It seems to work but with two issues:

It works but the excel file doesn't contain the data and just empty with two tabs. The URL works fine and the xlsx file contains data when I download it.

The last line that deletes a temp file I created to export doesn't do its job. The file still exists in the drive and nothing has changed.

I have looked everywhere for answers but can't figure this out. Any help will be appreciated.

答:
Try this code</p>

```<code>function exportSpreadsheet() {

  var ssID = "yourID";

  var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export"+
                                                        "?format=xlsx&"+
                                                        "size=0&"+
                                                        "fzr=true&"+
                                                        "portrait=false&"+
                                                        "fitw=true&"+
                                                        "gridlines=false&"+
                                                        "printtitle=true&"+
                                                        "sheetnames=true&"+
                                                        "pagenum=CENTER&"+
                                                        "attachment=true";

  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};

  var response = UrlFetchApp.fetch(url, params).getBlob();

  var folder = DriveApp.getFolderById("YourFolder");

  folder.createFile(response);

}
</code>```

Body:
function exportSpreadsheet() {
  var destination = SpreadsheetApp.create('Temp');
  var dest1 = destination.getActiveSheet().setName('출고입력 거래처정보(상단)');
  var dest2 = destination.insertSheet('출고입력 폼목정보(하단)');
  var source1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('출고입력 거래처정보(상단)').getDataRange();
  var source2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('출고입력 폼목정보(하단)').getDataRange();
  var source1Data = source1.getValues();
  var source2Data = source2.getValues();
  var s1Rows = source1.getNumRows();
  var s1Columns = source1.getNumColumns();
  var s2Rows = source2.getNumRows();
  var s2Columns = source2.getNumColumns();

  // Copy Data to Temp file
  for(var i = 0; i<s1Rows; i++){
  for(var j = 0; j<s1Columns; j++) {
       dest1.getRange(i+1,j+1).setValue(source1Data[i][j]);
    }
  }

  for(var i = 0; i<s2Rows; i++){
    for(var j = 0; j<s2Columns; j++) {
        dest2.getRange(i+1,j+1).setValue(source2Data[i][j]);
    }
  }

  // Export to xlsx
  var ssID = destination.getId();
  var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export"+"?format=xlsx";

  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};

  var response = UrlFetchApp.fetch(url, params).getBlob();
  // Save to drive
  var folder = DriveApp.getFolderById('1vDFMM2EfRe1unR6hJOsKapfJrcwxRkxy');
  folder.createFile(response).setName('출고.xlsx');

  // Delete Temp file
  DriveApp.getFilesByName('Temp').next().setTrashed(true);

}

I am trying to export two tabs from my spreadsheet and save it as a xlsx file. In doing so I have copied the two tabs to a new spreadsheet and then exporting to xlsx using the following code. I have read through almost all posts that deal with export to xlsx via Google Script and have concluded they are all variations of the code below. It seems to work but with two issues:

It works but the excel file doesn't contain the data and just empty with two tabs. The URL works fine and the xlsx file contains data when I download it.

The last line that deletes a temp file I created to export doesn't do its job. The file still exists in the drive and nothing has changed.

I have looked everywhere for answers but can't figure this out. Any help will be appreciated.

Body:
Try this code

function exportSpreadsheet() {

  var ssID = "yourID";

  var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export"+
                                                        "?format=xlsx&"+
                                                        "size=0&"+
                                                        "fzr=true&"+
                                                        "portrait=false&"+
                                                        "fitw=true&"+
                                                        "gridlines=false&"+
                                                        "printtitle=true&"+
                                                        "sheetnames=true&"+
                                                        "pagenum=CENTER&"+
                                                        "attachment=true";

  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};

  var response = UrlFetchApp.fetch(url, params).getBlob();

  var folder = DriveApp.getFolderById("YourFolder");

  folder.createFile(response);

}


问:
Is there any reason to use string.Format() with just a string parameter?
I'm currently updating some old code at work. I ran into a number of lines where string.Format() is used for seemingly no reason. I'm wondering if there is some use for using string.Format() without additional parameters, but I can't think of any.

What's the difference between this:

string query = String.Format(@"select type_cd, type_shpmt from codes");
```

<p>and this:</p>

<pre class="lang-cs prettyprint-override"><code>string query = "select type_cd, type_shpmt from codes";
</code>```

I also don't think that the @ is needed since it doesn't need to be a string literal, and it's not a multi-line string.

答:
Cut and paste failures. Someone didn't take the time to cleanup the code. There is no reason to use string.Format. Simply delete it and assign directly.

⚠ Warning ⚠

If the person is using the Format to combine parameters be wary; one should use the SQLCommand and SQLParameter class to avoid sql injection.

Body:
I'm currently updating some old code at work. I ran into a number of lines where string.Format() is used for seemingly no reason. I'm wondering if there is some use for using string.Format() without additional parameters, but I can't think of any.

What's the difference between this:

string query = String.Format(@"select type_cd, type_shpmt from codes");

and this:

string query = "select type_cd, type_shpmt from codes";

I also don't think that the @ is needed since it doesn't need to be a string literal, and it's not a multi-line string.


问:
Django import-export how to add current admin user to model
I am trying to make import-export select current/save user(defined as "author" field in model)

I tried this(save_model)  but it doesn't work(I think because of resource class)

```<code>class KWResource(resources.ModelResource):

    class Meta:

        model = KW
        import_id_fields = ('Keyword',)
        fields = ('Keyword',)

    searchess = fields.Field(attribute='searches', column_name="Avg. Monthly Searches (exact match only)")
    compp = fields.Field(attribute='comp', column_name="Competition")
    cpcc = fields.Field(attribute='cpc', column_name="Suggested bid")

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()
</code>```

How to get id of admin user that initiated import here?

答:
For anyone finding this later, you can access the current django user in a hook on your Resource. There's a 'user' in the **kwargs.

```<code>def before_import_row(self, row, **kwargs):
    row['author'] = kwargs['user'].id
</code>```

More detail here:
django-import-export assign current user

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make import-export select current/save user(defined as "author" field in model)

I tried this(save_model)  but it doesn't work(I think because of resource class)

class KWResource(resources.ModelResource):

    class Meta:

        model = KW
        import_id_fields = ('Keyword',)
        fields = ('Keyword',)

    searchess = fields.Field(attribute='searches', column_name="Avg. Monthly Searches (exact match only)")
    compp = fields.Field(attribute='comp', column_name="Competition")
    cpcc = fields.Field(attribute='cpc', column_name="Suggested bid")

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()

How to get id of admin user that initiated import here?

Body:
For anyone finding this later, you can access the current django user in a hook on your Resource. There's a 'user' in the **kwargs.

def before_import_row(self, row, **kwargs):
    row['author'] = kwargs['user'].id

More detail here:
django-import-export assign current user


问:
how to use pointer change array element
i try use pointer to change array element,but i fail.
it has not changed
how can i do?

i try some example like ** or &*
I am not good at C/C++,i don't know where I am wrong.
This is a matrix
B[0] is x
B[1] is y

#include<cstdio>
#include<cstring>
#include<cstdlib>
int rotate(int A[10][10],int *PointerX,int *PointerY){
    int x = *PointerX;
    int y = *PointerY;
    printf("into rotate\n");
    printf("B:[%d][%d]",x,y);
    int B[10][10];
    initialize(B);
    for(int i=0,m=x-1;i<=x;i++,m--){
        for(int j=0;j<y;j++){
            B[j][m] = A[i][j];
            if(i==x&&j==y-1){
                x = j+2;
                y = i-1;
                printf("\nA:[%d][%d]\n",x,y);
            }
        }
    }
    for(int i=0;i<10;i++){
        for(int j=0;j<10;j++){
            A[i][j] = B[i][j];
        }
    }
    return 0;
}
int ScanData(int A[10][10],int operate[10000],int B[3]){
    printf("DATA:\n");
    scanf("%d%d%d",&B[0],&B[1],&B[2]);
    for(int i=0;i<B[0];i++){
        for(int j=0;j<B[1];j++){
            scanf("%d",&A[i][j]);
        }
    }
    for(int i = 0;i<B[2];i++){
        scanf("%d",&operate[i]);
    }
    return B[2];
}
int main(){
    int A[10][10];
    initialize(A);
    int operate[10000];
    int B[3];
    int operating = ScanData(A,operate,B);
    for(int i=0;i<operating;i++){
        if(operate[i]==0){
            rotate(A,&B[0],&B[1]);
        }else if(operate[i]==1){
            flip(A,B[0],B[1]);
        }
    }
    return 0;
}
```

i hope function rotate can change B[0] and B[1]
but isn't

答:
When you do this:

```<code>int x = *PointerX;
int y = *PointerY;
</code>```

The variables x and y contain the current value of B[0] and B[1].  They are not pointers, so when you later assign to x and y you're only assigning to the copies.

Remove x and y and replace them with *PointerX and *PointerY.

```<code>for(int i=0,m=*PointerX-1;i<=*PointerX;i++,m--){
    for(int j=0;j<*PointerY;j++){
        B[j][m] = A[i][j];
        if(i==*PointerX&&j==*PointerY-1){
            *PointerX = j+2;
            *PointerY = i-1;
            printf("\nA:[%d][%d]\n",*PointerX,*PointerY);
        }
    }
}
</code>```

Title: how to use pointer change array element

Body:
i try use pointer to change array element,but i fail.
it has not changed
how can i do?

i try some example like ** or &*
I am not good at C/C++,i don't know where I am wrong.
This is a matrix
B[0] is x
B[1] is y

#include<cstdio>
#include<cstring>
#include<cstdlib>
int rotate(int A[10][10],int *PointerX,int *PointerY){
    int x = *PointerX;
    int y = *PointerY;
    printf("into rotate\n");
    printf("B:[%d][%d]",x,y);
    int B[10][10];
    initialize(B);
    for(int i=0,m=x-1;i<=x;i++,m--){
        for(int j=0;j<y;j++){
            B[j][m] = A[i][j];
            if(i==x&&j==y-1){
                x = j+2;
                y = i-1;
                printf("\nA:[%d][%d]\n",x,y);
            }
        }
    }
    for(int i=0;i<10;i++){
        for(int j=0;j<10;j++){
            A[i][j] = B[i][j];
        }
    }
    return 0;
}
int ScanData(int A[10][10],int operate[10000],int B[3]){
    printf("DATA:\n");
    scanf("%d%d%d",&B[0],&B[1],&B[2]);
    for(int i=0;i<B[0];i++){
        for(int j=0;j<B[1];j++){
            scanf("%d",&A[i][j]);
        }
    }
    for(int i = 0;i<B[2];i++){
        scanf("%d",&operate[i]);
    }
    return B[2];
}
int main(){
    int A[10][10];
    initialize(A);
    int operate[10000];
    int B[3];
    int operating = ScanData(A,operate,B);
    for(int i=0;i<operating;i++){
        if(operate[i]==0){
            rotate(A,&B[0],&B[1]);
        }else if(operate[i]==1){
            flip(A,B[0],B[1]);
        }
    }
    return 0;
}

i hope function rotate can change B[0] and B[1]
but isn't

Body:
When you do this:

int x = *PointerX;
int y = *PointerY;

The variables x and y contain the current value of B[0] and B[1].  They are not pointers, so when you later assign to x and y you're only assigning to the copies.

Remove x and y and replace them with *PointerX and *PointerY.

for(int i=0,m=*PointerX-1;i<=*PointerX;i++,m--){
    for(int j=0;j<*PointerY;j++){
        B[j][m] = A[i][j];
        if(i==*PointerX&&j==*PointerY-1){
            *PointerX = j+2;
            *PointerY = i-1;
            printf("\nA:[%d][%d]\n",*PointerX,*PointerY);
        }
    }
}


问:
How to make Amazon In-App Purchasing (IAP) 2.0 work with Android R8
It took a while after significant revenue loss to find out that Android R8 code shrinker prevents Amazon In-App Purchasing (IAP) 2.0 from working.  Android Studio uses R8 by default now.  Fortunately, the following in gradle.properties seems to be able to stop R8:

```<code>android.enableR8=false
</code>```

I fear R8 will be mandated in the future, and it will be a disaster. I am trying to find a way to make them compatible.
Someone posted a similar question on Amazon's forum that is supposed to be the best place for such questions, but I have a feeling that Amazon has stopped supporting the forum because my recent two questions there have received no response from Amazon.

I have the following in proguard-project.txt that is used by R8

```<code>#amazon
-dontwarn com.amazon.**
-keep class com.amazon.** {*;}
-keepattributes *Annotation*
-optimizations !code/allocation/variable
-optimizationpasses 1
</code>```

As my understanding, R8 ignores optimizationpasses. I suspect that is the cause.

Edit(2019-05-30)
The aforementioned script for proguard-project.txt is from Amazon's document for In-App Purchasing
The app's build.gradle has the following:

```<code>release {
    minifyEnabled true
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
    signingConfig signingConfigs.Release

}
</code>```

答:
proguard-android.txt uses -dontoptimize, so it shouldn't be optimizing at all with ProGuard or R8, regardless of the number of -optimizationpasses specified. If you are interested, you can see the available default ProGuard files under build/intermediates/proguard-files/. proguard-android-optimize.txt is the one that would allow optimization.

At this point, given that R8's optimization doesn't seem to be on, I'm not sure if there's much of a workaround. I'd recommend that you file an issue with Google's Issue Tracker, giving as much detail as you can to help them reproduce the issue. They are generally pretty responsive to issues like this.

Body:
It took a while after significant revenue loss to find out that Android R8 code shrinker prevents Amazon In-App Purchasing (IAP) 2.0 from working.  Android Studio uses R8 by default now.  Fortunately, the following in gradle.properties seems to be able to stop R8:

android.enableR8=false

I fear R8 will be mandated in the future, and it will be a disaster. I am trying to find a way to make them compatible.
Someone posted a similar question on Amazon's forum that is supposed to be the best place for such questions, but I have a feeling that Amazon has stopped supporting the forum because my recent two questions there have received no response from Amazon.

I have the following in proguard-project.txt that is used by R8

#amazon
-dontwarn com.amazon.**
-keep class com.amazon.** {*;}
-keepattributes *Annotation*
-optimizations !code/allocation/variable
-optimizationpasses 1

As my understanding, R8 ignores optimizationpasses. I suspect that is the cause.

Edit(2019-05-30)
The aforementioned script for proguard-project.txt is from Amazon's document for In-App Purchasing
The app's build.gradle has the following:

release {
    minifyEnabled true
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
    signingConfig signingConfigs.Release

}


问:
CSS media query styles won't apply when viewport size changes
Media queries for a responsive menu aren't working. The original menu is a horizontal, equally-divided set of tabs. I need to show a stack/burger icon in the top-left corner when viewing on a mobile device (< 600px in the below code) which shows as a full page centered menu over the entire page... such as full screen div on a 2 for z-index.

I have tried changing the min & max-widths, and tried to view this on actual devices as well as browser-built-in developer tools/simulators... no change, a stack icon that will display the menu over the whole page on mobile devices doesn't show... instead the original (horizontal, full-width) menu stays visible (which is #menu_row & .menu_row).

@media screen and (min-width: 0px) and (max-width: 600px) {
    #small_menu_row.small_menu_row {
        //responsive menu
        display: block;
        z-index: 2;
        text-align: center;
    }
    #menu_row.menu_row {
        //regular menu
        display: none;
        z-index: 2;
        text-align: center;
    }
}

@media screen and (min-width: 601px){
  #small_menu_row.small_menu_row{        //responsive menu
  display:none;
  z-index:2;
  text-align:center;
 }
 #menu_row.menu_row{       //regular menu
  display:block;
  z-index:2;
  text-align:center;
 }
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="container-fluid" id="outer_most">
    <div class="row blank_row">
        <div class="col">

        </div>
    </div>
    <div class="row small_menu_row" id="small_menu_row">
        <nav class="navbar navbar-inverse">
            <div class="container-fluid">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                    <img src="<?php echo wp_get_upload_dir()['baseurl'];?>/stack.png">
                    </button>

                </div>
                <div class="collapse navbar-collapse" id="myNavbar">
                    <ul class="nav navbar-nav">
                        <li class="nav-item">
                            /home">HOME
                        </li>
                        <li class="nav-item">
                            /trafat">A SAMPLE TITLE
                        </li>
                        <li class="nav-item">
                            /estore">e-STORE
                        </li>
                        <li class="nav-item">
                            /works">
                                <div class="dropdown">
                                    WORKS
                                    <!--div class="dropdown-content">
                                        <?php /*
                                            $args = array("child_of"=>9, "sort_column"=>"menu_order", "sort_order"=>"ASC");
                                            $pages = get_pages($args);
                                            $count=0;
                                            foreach($pages as $page){
                                             echo "post_name."\" class=\"book_row\" \">"
                                             .$page->post_title.
                                             "";
                                            $count++;
                                            }
                                            */ ?>
                                        </div-->
                                    <div class="dropdown-content">
                            /archives/aotr" class="book_row">
                            A SAMPLE TITLE

                            /archives/a_v" class="book_row">
                            A SAMPLE TITLE

                            <span <!--href="<?php echo get_site_url()?>/archives/gallery"--> class="book_row">
                            A SAMPLE TITLE
                            </span>
                            <span <!--href="<?php echo get_site_url()?>/archives/performances"--> class="book_row">
                            A SAMPLE TITLE
                            </span>
                            </div>
                            </div>

                        </li>
                        <li class="nav-item">
                            /archives">
                                <div class="dropdown">
                                    ARCHIVES
                                    <div class="dropdown-content">
                            /archives/aotr" class="book_row">
                            ARTICLES

                            /archives/a_v" class="book_row">
                            AUDIO / VISUAL

                            /archives/gallery" class="book_row">
                            IMAGE GALLERY

                            /archives/performances" class="book_row">
                            PERFORMANCES

                            /archives/events" class="book_row">
                            EVENTS

                            </div>
                            </div>

                        </li>
                        <!--li class="nav-item">
                            /forum">FORUM
                            </li-->
                        <li class="nav-item">
                            /about">ABOUT US
                        </li>
                        <li class="nav-item">
                            /contact">CONTACT
                        </li>
                    </ul>
                    <!--ul class="nav navbar-nav navbar-right">
                        <li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
                        <li><span class="glyphicon glyphicon-log-in"></span> Login</li>
                        </ul-->
                </div>
            </div>
        </nav>
    </div>
    <div class="row logo_row" id="logo_row">
        <img src="<?php echo wp_upload_dir()['baseurl']; ?>/t2.png" id="img_2">
    </div>
    <div class="row blank_row">
        <div class="col">
            <br>
            <br>
        </div>
    </div>
    <div class="row menu_row" id="menu_row">
        <div class="col col-xl-2 col-lg-2 col-md-1 col-sm-1">
        </div>
        <div class="col col-xl-8 col-lg-8 col-md-10 col-sm-10" id="act_menu">
            <ul class="nav justify-content-between">
                <li class="nav-item">
                    /home">HOME
                </li>
                <li class="nav-item">
                    /trafat">A SAMPLE TITLE
                </li>
                <li class="nav-item">
                    /works">
                        <div class="dropdown">
                            WORKS
                            <!--div class="dropdown-content">
                                <?php /*
                                    $args = array("child_of"=>9, "sort_column"=>"menu_order", "sort_order"=>"ASC");
                                    $pages = get_pages($args);
                                    $count=0;
                                    foreach($pages as $page){
                                     echo "post_name."\" class=\"book_row\" \">"
                                     .$page->post_title.
                                     "";
                                    $count++;
                                    }
                                    */ ?>
                                </div-->
                            <div class="dropdown-content">
                    /works/SAMPLETITLE" class="book_row">
                    A SAMPLE TITLE

                    /works/SAMPLETITLE" class="book_row">
                    A SAMPLE TITLE

                    A SAMPLE TITLE

                    A SAMPLE TITLE

                    </div>
                    </div>

                </li>
                <li class="nav-item">
                    /archives">
                        <div class="dropdown">
                            ARCHIVES
                            <div class="dropdown-content">
                    /archives/aotr" class="book_row">
                    ARTICLES

                    /archives/a_v" class="book_row">
                    AUDIO / VIDEO

                    /archives/gallery" class="book_row">
                    IMAGE GALLERY

                    /archives/performances" class="book_row">
                    PERFORMANCES

                    /archives/events" class="book_row">
                    EVENTS

                    </div>
                    </div>

                </li>
                <li class="nav-item">
                    /estore">e-STORE
                </li>
                <!--li class="nav-item">
                    /forum">FORUM
                    </li-->
                <li class="nav-item">
                    /about">ABOUT US
                </li>
                <li class="nav-item">
                    /contact">CONTACT
                </li>
            </ul>
        </div>
        <div class="col col-xl-2 col-lg-2 col-md-1 col-sm-1">
        </div>
    </div></code>```

Here's the same code on JSFiddle: http://jsfiddle.net/zL9cfoj7

Expected results: Regular menu would hide and stack icon would appear when viewing on mobile (or a width < 600px)

Actual result: literally nothing happens!

答:
It looks like you're using Bootstrap - why don't you use the built-in display classes to handle the hiding/showing?

...

...

```

Body:
Media queries for a responsive menu aren't working. The original menu is a horizontal, equally-divided set of tabs. I need to show a stack/burger icon in the top-left corner when viewing on a mobile device (< 600px in the below code) which shows as a full page centered menu over the entire page... such as full screen div on a 2 for z-index.

I have tried changing the min & max-widths, and tried to view this on actual devices as well as browser-built-in developer tools/simulators... no change, a stack icon that will display the menu over the whole page on mobile devices doesn't show... instead the original (horizontal, full-width) menu stays visible (which is #menu_row & .menu_row).

@media screen and (min-width: 0px) and (max-width: 600px) {
    #small_menu_row.small_menu_row {
        //responsive menu
        display: block;
        z-index: 2;
        text-align: center;
    }
    #menu_row.menu_row {
        //regular menu
        display: none;
        z-index: 2;
        text-align: center;
    }
}

@media screen and (min-width: 601px){
  #small_menu_row.small_menu_row{        //responsive menu
  display:none;
  z-index:2;
  text-align:center;
 }
 #menu_row.menu_row{       //regular menu
  display:block;
  z-index:2;
  text-align:center;
 }
}

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                    <img src="<?php echo wp_get_upload_dir()['baseurl'];?>/stack.png">
                    </button>

                            <a class="nav-link menu-link" href="<?php echo get_site_url()?>/home">HOME

                            <a class="nav-link menu-link" href="<?php echo get_site_url()?>/trafat">A SAMPLE TITLE

                            <a class="nav-link menu-link" href="<?php echo get_site_url()?>/estore">e-STORE

                            <a class="nav-link menu-link" href="<?php echo get_site_url()?>/works">

                                    WORKS

                            <a href="<?php echo get_site_url()?>/archives/aotr" class="book_row">
                            A SAMPLE TITLE

                            <a href="<?php echo get_site_url()?>/archives/a_v" class="book_row">
                            A SAMPLE TITLE

                            A SAMPLE TITLE

                            A SAMPLE TITLE

                            <a class="nav-link menu-link" href="<?php echo get_site_url()?>/archives">

                                    ARCHIVES

                            <a href="<?php echo get_site_url()?>/archives/aotr" class="book_row">
                            ARTICLES

                            <a href="<?php echo get_site_url()?>/archives/a_v" class="book_row">
                            AUDIO / VISUAL

                            <a href="<?php echo get_site_url()?>/archives/gallery" class="book_row">
                            IMAGE GALLERY

                            <a href="<?php echo get_site_url()?>/archives/performances" class="book_row">
                            PERFORMANCES

                            <a href="<?php echo get_site_url()?>/archives/events" class="book_row">
                            EVENTS

                            <a class="nav-link menu-link" href="<?php echo get_site_url()?>/about">ABOUT US

                            <a class="nav-link menu-link" href="<?php echo get_site_url()?>/contact">CONTACT

        <img src="<?php echo wp_upload_dir()['baseurl']; ?>/t2.png" id="img_2">

                    <a class="nav-link menu-link" href="<?php echo get_site_url()?>/home">HOME

                    <a class="nav-link menu-link" href="<?php echo get_site_url()?>/trafat">A SAMPLE TITLE

                    <a class="nav-link menu-link" href="<?php echo get_site_url()?>/works">

                            WORKS

                    <a href="<?php echo get_site_url()?>/works/SAMPLETITLE" class="book_row">
                    A SAMPLE TITLE

                    <a href="<?php echo get_site_url()?>/works/SAMPLETITLE" class="book_row">
                    A SAMPLE TITLE

                    A SAMPLE TITLE

                    A SAMPLE TITLE

                    <a class="nav-link menu-link" href="<?php echo get_site_url()?>/archives">

                            ARCHIVES

                    <a href="<?php echo get_site_url()?>/archives/aotr" class="book_row">
                    ARTICLES

                    <a href="<?php echo get_site_url()?>/archives/a_v" class="book_row">
                    AUDIO / VIDEO

                    <a href="<?php echo get_site_url()?>/archives/gallery" class="book_row">
                    IMAGE GALLERY

                    <a href="<?php echo get_site_url()?>/archives/performances" class="book_row">
                    PERFORMANCES

                    <a href="<?php echo get_site_url()?>/archives/events" class="book_row">
                    EVENTS

                    <a class="nav-link menu-link" href="<?php echo get_site_url()?>/estore">e-STORE

                    <a class="nav-link menu-link" href="<?php echo get_site_url()?>/about">ABOUT US

                    <a class="nav-link menu-link" href="<?php echo get_site_url()?>/contact">CONTACT

Here's the same code on JSFiddle: http://jsfiddle.net/zL9cfoj7

Expected results: Regular menu would hide and stack icon would appear when viewing on mobile (or a width < 600px)

Actual result: literally nothing happens!

Body:
It looks like you're using Bootstrap - why don't you use the built-in display classes to handle the hiding/showing?

<!-- visible only on screen size < 576px -->
<div class="row small_menu_row d-block d-sm-none" id="small_menu_row">
...
</div>

<!-- hidden on screen size < 576px, otherwise visible -->
<div class="row menu_row d-none d-sm-block" id="menu_row">
...
</div>


问:
How to show error message using IValidatableObject in WPF?
I'm using IValidatableObject to validate my template in wpf. However, the error message is not returned to the interface. However, it is worth clarifying that validation works. The only problem is that the message is not displayed in the interface.

```<code>public string Host
{
   get => _host;
   set
   {
       _host = value;
       OnPropertyChanged();
    }
}

public string Port
{
   get => _port;
   set
   {
     _port = value;
     OnPropertyChanged();
   }
}

public string User
{
    get => _user;
    set
    {
      _user = value;
      OnPropertyChanged();
     }
}

public bool IsEmptyOrNull(string value) => string.IsNullOrWhiteSpace(value);

public IEnumerable<ValidationResult> Validate()
{
   var results = new List<ValidationResult>();
   var context = new ValidationContext(this);
   Validator.TryValidateObject(this, context, results, true);
   return results;
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
  if (IsEmptyOrNull(Host))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Host) });
  }
  if (IsEmptyOrNull(Port))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Port) });
  }
  if (IsEmptyOrNull(User))
  {
     yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(User) });
  }
  if (IsEmptyOrNull(Password))
  {
     yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Password) });
  }
  if (IsEmptyOrNull(DataBase))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(DataBase) });
  }
}
</code>```

Here interface XML

```<code> <TextBox x:Name="HostTextBox" Text="{Binding AppSetting.Host,UpdateSourceTrigger=LostFocus, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}"  Validation.ErrorTemplate="{StaticResource ErrorTemplate}" HorizontalAlignment="Left" Width="200" Margin="5,0,0,0" BorderBrush="#FF5774CB" mah:TextBoxHelper.Watermark="Localhost" TabIndex="1" FontSize="14"/>
</code>```

```<code><ControlTemplate x:Key="ErrorTemplate">
     <Border BorderBrush="OrangeRed" BorderThickness="2">
         <Grid>
            <AdornedElementPlaceholder/>
            <TextBlock Text="{Binding [0].ErrorContent}" Foreground="OrangeRed" VerticalAlignment="Center" HorizontalAlignment="Right"
Margin="0,0,4,0"/>
        </Grid>
    </Border>
</ControlTemplate>
</code>```

How do I display the error message on the interface from this validation?

答:
Your problem is because IValidateObject ONLY returns those validation results.

WPF doesn't care about them.

You need to implement inotifydataerrorinfo or another interface that WPF understands and use those results in that.

You could adapt the code I use in this:

https://gallery.technet.microsoft.com/scriptcenter/WPF-Entity-Framework-MVVM-78cdc204

Take a look at the code in BaseEntity.

Body:
I'm using IValidatableObject to validate my template in wpf. However, the error message is not returned to the interface. However, it is worth clarifying that validation works. The only problem is that the message is not displayed in the interface.

public string Host
{
   get => _host;
   set
   {
       _host = value;
       OnPropertyChanged();
    }
}

public string Port
{
   get => _port;
   set
   {
     _port = value;
     OnPropertyChanged();
   }
}

public string User
{
    get => _user;
    set
    {
      _user = value;
      OnPropertyChanged();
     }
}

public bool IsEmptyOrNull(string value) => string.IsNullOrWhiteSpace(value);

public IEnumerable<ValidationResult> Validate()
{
   var results = new List<ValidationResult>();
   var context = new ValidationContext(this);
   Validator.TryValidateObject(this, context, results, true);
   return results;
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
  if (IsEmptyOrNull(Host))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Host) });
  }
  if (IsEmptyOrNull(Port))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Port) });
  }
  if (IsEmptyOrNull(User))
  {
     yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(User) });
  }
  if (IsEmptyOrNull(Password))
  {
     yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Password) });
  }
  if (IsEmptyOrNull(DataBase))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(DataBase) });
  }
}

Here interface XML

 <TextBox x:Name="HostTextBox" Text="{Binding AppSetting.Host,UpdateSourceTrigger=LostFocus, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}"  Validation.ErrorTemplate="{StaticResource ErrorTemplate}" HorizontalAlignment="Left" Width="200" Margin="5,0,0,0" BorderBrush="#FF5774CB" mah:TextBoxHelper.Watermark="Localhost" TabIndex="1" FontSize="14"/>

<ControlTemplate x:Key="ErrorTemplate">
     <Border BorderBrush="OrangeRed" BorderThickness="2">
         <Grid>
            <AdornedElementPlaceholder/>
            <TextBlock Text="{Binding [0].ErrorContent}" Foreground="OrangeRed" VerticalAlignment="Center" HorizontalAlignment="Right"
Margin="0,0,4,0"/>
        </Grid>
    </Border>
</ControlTemplate>

How do I display the error message on the interface from this validation?


问:
Help with hotel queries
Hello I have a database in Microsoft SQL Server with tables relevant to a reservation system for a hotel/villa and need help creating a few queries to obtain relevant data:

To be able to find out a list of guests checking out on a specific date, grouped by villa type and providing a total number for that day (i.e. a count).

For that query I think I'd have to use 2 relevant tables a guest reservation and reservation table:

```<code>create table guest_reservation(confirm_no int,
agent_id int,
g_name varchar (30),
g_phone varchar (10));

create table reservation(
confirm_no int,
credit_card_no char (16),
res_checkin_date datetime,
res_checkout_date datetime,
default_villa_type char (1),
price_plan char (1));

I thought using a query like this would help, but it didn't seem to:

SELECT g_name, villa_type, COUNT(*)
FROM guest_reservation, reservation
WHERE guest_reservation.confirm_no = reservation.confirm_no
  AND res_checkout_date = ‘insert date for when you would want to check out here’
GROUP BY villa_type;
</code>```

Ideas/help?

EDIT: I think I figured out the 1st question...

Another query I wanted help on was that if a guest wanted a certain type of room then if that type of room would be available on the dates they wanted to stay on.

I used JUST the Reservation table but I'm not sure if that quite would do what I want, here's what I currently had:

```<code>Select villa_type from reservation
where res_check_in_date not between '2011-10-08' and '2011-10-09'
and res_check_out_date not between '2011-10-08' and '2011-10-09'
</code>```

答:
Due to the nature of time spans, you may find it helpful, nay, necessary, to create a Calendar table which is simply a static list of days in the calendar. These are almost always created in BI projects for data analysis.

What this object allows you to do is join from you Reservation table to the Calendar table, giving you a list of distinctive dates which encompass the time span. Here's a code sample:

```<code>inner join calendar
on calendar.date between reservation.res_checkin_date and reservation.res_checkout_date
</code>```

For example, If I'm checking in today (4/12) and checking out on Thursday (4/14), joining to the calendar table will product 3 distinct rows, one each for 4/12, 4/13, 4/14. In terms of checking availability, this is a much clearer picture of who occupies what, when.

Additionally, there are some code nuances you may want to be aware of, such as using a DATE instead of DATETIME, to eliminate the possibility of times producing unexpected results. If you need a full DATETIME type, there are ways to efficiently query the DATE in a DATETIME.

Title: Help with hotel queries

Body:
Hello I have a database in Microsoft SQL Server with tables relevant to a reservation system for a hotel/villa and need help creating a few queries to obtain relevant data:

To be able to find out a list of guests checking out on a specific date, grouped by villa type and providing a total number for that day (i.e. a count).

For that query I think I'd have to use 2 relevant tables a guest reservation and reservation table:

create table guest_reservation(confirm_no int,
agent_id int,
g_name varchar (30),
g_phone varchar (10));

create table reservation(
confirm_no int,
credit_card_no char (16),
res_checkin_date datetime,
res_checkout_date datetime,
default_villa_type char (1),
price_plan char (1));

I thought using a query like this would help, but it didn't seem to:

SELECT g_name, villa_type, COUNT(*)
FROM guest_reservation, reservation
WHERE guest_reservation.confirm_no = reservation.confirm_no
  AND res_checkout_date = ‘insert date for when you would want to check out here’
GROUP BY villa_type;

Ideas/help?

EDIT: I think I figured out the 1st question...

Another query I wanted help on was that if a guest wanted a certain type of room then if that type of room would be available on the dates they wanted to stay on.

I used JUST the Reservation table but I'm not sure if that quite would do what I want, here's what I currently had:

Select villa_type from reservation
where res_check_in_date not between '2011-10-08' and '2011-10-09'
and res_check_out_date not between '2011-10-08' and '2011-10-09'

Body:
Due to the nature of time spans, you may find it helpful, nay, necessary, to create a Calendar table which is simply a static list of days in the calendar. These are almost always created in BI projects for data analysis.

What this object allows you to do is join from you Reservation table to the Calendar table, giving you a list of distinctive dates which encompass the time span. Here's a code sample:

inner join calendar
on calendar.date between reservation.res_checkin_date and reservation.res_checkout_date

For example, If I'm checking in today (4/12) and checking out on Thursday (4/14), joining to the calendar table will product 3 distinct rows, one each for 4/12, 4/13, 4/14. In terms of checking availability, this is a much clearer picture of who occupies what, when.

Additionally, there are some code nuances you may want to be aware of, such as using a DATE instead of DATETIME, to eliminate the possibility of times producing unexpected results. If you need a full DATETIME type, there are ways to efficiently query the DATE in a DATETIME.


问:
The database for Rumbl.Repo couldn't be created: killed
I created a new project using mix phx.new rumbl which worked fine.
Then I went to the project folder using cd rumbl. After that I tried to run mix ecto.create which resulted in this error message:

```<code>D:\Elixir\Projects\rumbl>mix ecto.create

10:35:16.370 [error] GenServer #PID<0.212.0> terminating
** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused
    (db_connection) lib/db_connection/connection.ex:84: DBConnection.Connection.connect/2
    (connection) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
Last message: nil
State: Postgrex.Protocol
** (Mix) The database for Rumbl.Repo couldn't be created: killed
</code>```

Yesterday mix ecto.create worked, but now it gives this error.
I have installed the dependencies without any problems
Elixir version: 1.8.2
phoenix version: 1.4.6

I have tried reopening the command prompt, restarting my laptop and using a different folder

答:
Your Postgres database is not running or not open on this port.

You should install postgres and start it.

If you don't want to handle with postgres issues or are not familiar with that, take a look on this post about how to have it running on a docker container.

Body:
I created a new project using mix phx.new rumbl which worked fine.
Then I went to the project folder using cd rumbl. After that I tried to run mix ecto.create which resulted in this error message:

D:\Elixir\Projects\rumbl>mix ecto.create

10:35:16.370 [error] GenServer #PID<0.212.0> terminating
** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused
    (db_connection) lib/db_connection/connection.ex:84: DBConnection.Connection.connect/2
    (connection) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
Last message: nil
State: Postgrex.Protocol
** (Mix) The database for Rumbl.Repo couldn't be created: killed

Yesterday mix ecto.create worked, but now it gives this error.
I have installed the dependencies without any problems
Elixir version: 1.8.2
phoenix version: 1.4.6

I have tried reopening the command prompt, restarting my laptop and using a different folder


问:
How to read all characters from file and store it in 2d array without \n?
I am trying to read a file and store each of its character in 2d array(of size 7 by 7) without special characters like '\n' and than print that 2d array.

I write a code but it does not store and print the last line characters in 2d array.

```<code>#include<stdio.h>
#include<stdlib.h>
int main()
{
     char ar[7][7],c;
    int i,j;
    FILE *fp;
    fp=fopen("B11.txt","r");
    if(fp==NULL)
        printf("File not Found");

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {

         fscanf(fp,"%c",&ar[i][j]);
        }

    }

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {
            printf("%c",ar[i][j]);
        }

    }
fclose(fp);
}
</code>```

This the output of the my code:

```<code>abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh
</code>```

But the file contains,

```<code>abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh
comsats
</code>```

Here the file contains the word 'comsats' also, that is not printed. Why this word comsats is not printed?

答:
```<code>    for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {
            fscanf(fp,"%c",&ar[i][j]);
        }
    }
</code>```

ar[i][0] will have \n left out from previous line summing up to 7 \n thus ignoring last line.

change  to

```<code>            fscanf(fp," %c",&ar[i][j]);
</code>```

or

have getchar() after inner for loop.

Body:
I am trying to read a file and store each of its character in 2d array(of size 7 by 7) without special characters like '\n' and than print that 2d array.

I write a code but it does not store and print the last line characters in 2d array.

#include<stdio.h>
#include<stdlib.h>
int main()
{
     char ar[7][7],c;
    int i,j;
    FILE *fp;
    fp=fopen("B11.txt","r");
    if(fp==NULL)
        printf("File not Found");

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {

         fscanf(fp,"%c",&ar[i][j]);
        }

    }

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {
            printf("%c",ar[i][j]);
        }

    }
fclose(fp);
}

This the output of the my code:

abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh

But the file contains,

abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh
comsats

Here the file contains the word 'comsats' also, that is not printed. Why this word comsats is not printed?

Body:
    for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {
            fscanf(fp,"%c",&ar[i][j]);
        }
    }

ar[i][0] will have \n left out from previous line summing up to 7 \n thus ignoring last line.

change  to

            fscanf(fp," %c",&ar[i][j]);

or

have getchar() after inner for loop.


问:
TextInputLayout :How to give padding or margin to hint?
I have to use TextInputLayout of design support library in my project. I want to give space between hint and EditText in TextInputLayout. I set margin and padding in TextInputLayout and even inside EditText but both are not work.So how to solve this issue. Here i attach screen shot and my coding.

```<code>==============================Style=================================

<style name="TextHint" parent="Base.TextAppearance.AppCompat">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/green</item>
</style>

=============================XML===================================
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    app:hintTextAppearance="@style/TextHint"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:layout_height="wrap_content">
<EditText
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/edttxtEmailAddress"
    android:singleLine="true"
    android:hint="@string/enter_valid_email"
    android:paddingLeft="20dp"
    android:textSize="20sp"
    android:background="@drawable/rounded_common"/>
</android.support.design.widget.TextInputLayout>
</code>```

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="10dp"
          android:bottom="5dp">
        <shape>
            <!-- Background Color -->
            <solid android:color="#f1f1f1"/>
            <!-- Round Corners -->
            <corners android:radius="5dp"/>
        </shape>
    </item>
</layer-list>

<style name="text_input_edit_text_without_border_style">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">55dp</item>
    <item name="android:paddingTop">10dp</item>
    <item name="android:paddingBottom">5dp</item>
    <item name="android:gravity">left|center_vertical</item>
    <item name="android:paddingLeft">8dp</item>
    <item name="android:paddingRight">8dp</item>
    <item name="android:maxLines">1</item>
    <item name="android:singleLine">true</item>
    <item name="android:imeOptions">actionNext</item>
    <item name="android:textSize">@dimen/text_size_large</item>
    <item name="android:background">@drawable/bg_without_border_with_padding_top</item>
</style>

<style name="text_input_layout_style">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_marginBottom">@dimen/margin_medium</item>
</style>
</code>```

Body:
I have to use TextInputLayout of design support library in my project. I want to give space between hint and EditText in TextInputLayout. I set margin and padding in TextInputLayout and even inside EditText but both are not work.So how to solve this issue. Here i attach screen shot and my coding.

==============================Style=================================

=============================XML===================================
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    app:hintTextAppearance="@style/TextHint"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:layout_height="wrap_content">
<EditText
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/edttxtEmailAddress"
    android:singleLine="true"
    android:hint="@string/enter_valid_email"
    android:paddingLeft="20dp"
    android:textSize="20sp"
    android:background="@drawable/rounded_common"/>
</android.support.design.widget.TextInputLayout>


问:
Drupal - Full node content not teaser
I'm making a blog, but I don't have a large experience with Drupal (I'm using Drupal 6).

The index page should have a post with full content and the next 10 posts showing the teaser. I want to know how to show the full content of just the first loaded node.

I'm hitting my head against the keyboard for hours, but I can't get a simple solution for it. I've tried to see all defined_vars and all are filled with the teaser, I've tried to use node_view($node->nid) but it seems to enter in a infinite recursion. I've been searching a lot in Google, but nothing seems to satisfy.

I guess that I don't need to use the View module for it, cause I just wanna change the $teaser = true to false when I get loaded a node.

Someone have an idea for it?

Thank you all!

答: I'd recommend using the Views module for that. As you're getting familiar with Drupal, it's important to get familiar with Views because once you do, you'll start finding more and more places to use it.</p>

Title: Drupal - Full node content not teaser


问:
Custom ConstraintViolationException in spring-boot
How I catch exception for this ConstraintViolationException :

```<code>{
    "timestamp": "2019-05-31T07:23:03.419+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "could not execute statement; SQL [n/a]; constraint [fkitcllv8yn2id9lj3rmw3wskhd]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
    "path": "/pelajar"
}
</code>```

This Excaption is happen, when I try to deleting a record. But that record still used as reference by other record in other table.

I Have 2 CustomExceptionHandle :
 the 1st for catch general exception and
 the 2nd for catch ConstraintViolation exception.

But in my program, each time ConstraintViolation trigger-up, the handleAllExceptions will be executed.
My expectation is  handleConstraint function should be executed.

```<code>@ControllerAdvice
@RestController
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public  ResponseEntity<Object> handleConstraint(ConstraintViolationException ex,
            WebRequest request ) {

        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), "Record still have reference from other table",
                request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
    }

    @Order(Ordered.LOWEST_PRECEDENCE)
    @ExceptionHandler(value = {Exception.class})
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage()+" Custom Error",
                request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
</code>```

But, If I remove handleAllExceptions the ConstraintViolationException will be catch by handleConstraint function.

Can anyone give me advice ?

Thank You.

Alt...

答: Seems you have imported javax.validation.ConstraintViolationException instead of org.hibernate.exception.ConstraintViolationException in CustomResponseEntityExceptionHandler. Kindly import org.hibernate.exception.ConstraintViolationException if not imported correctly.

Body:
How I catch exception for this ConstraintViolationException :

{
    "timestamp": "2019-05-31T07:23:03.419+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "could not execute statement; SQL [n/a]; constraint [fkitcllv8yn2id9lj3rmw3wskhd]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
    "path": "/pelajar"
}

This Excaption is happen, when I try to deleting a record. But that record still used as reference by other record in other table.

I Have 2 CustomExceptionHandle :
 the 1st for catch general exception and
 the 2nd for catch ConstraintViolation exception.

But in my program, each time ConstraintViolation trigger-up, the handleAllExceptions will be executed.
My expectation is  handleConstraint function should be executed.

@ControllerAdvice
@RestController
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public  ResponseEntity<Object> handleConstraint(ConstraintViolationException ex,
            WebRequest request ) {

        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), "Record still have reference from other table",
                request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
    }

    @Order(Ordered.LOWEST_PRECEDENCE)
    @ExceptionHandler(value = {Exception.class})
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage()+" Custom Error",
                request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

But, If I remove handleAllExceptions the ConstraintViolationException will be catch by handleConstraint function.

Can anyone give me advice ?

Thank You.

Alt...


问:
Hidden text animation is not working properly
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}</code>```

  <button>
</button>

some text

```

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

答:
You really shouldn't need Javascript to do this.

I'm not really sure what you're looking for, but I'd use a width / opacity transition on the .textContent (when button is hovered) and it achieves very similar results to the page you have linked.

button {
  background-color: red;
  border-radius: 50%;
  border: none;
  width: 10rem;
  height: 10rem;
  transition: all .3s ease 0s;
}

button:hover {
  box-shadow: 0px 3rem 4rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 3rem 4rem -2rem rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent p{
  width:0px;
  opacity:0;
  transition: opacity .3s ease 0s;
}

button:hover + .textcontent p{
  width:200px;
  opacity:1;
  transition: all .3s ease 0s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <button>
</button>
  <div class="textcontent">
    <p>some text</p>
  </div>
</div></code>```

Body:
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}

button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}

  <button>
</button>

some text

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

Body:
You really shouldn't need Javascript to do this.

I'm not really sure what you're looking for, but I'd use a width / opacity transition on the .textContent (when button is hovered) and it achieves very similar results to the page you have linked.

button {
  background-color: red;
  border-radius: 50%;
  border: none;
  width: 10rem;
  height: 10rem;
  transition: all .3s ease 0s;
}

button:hover {
  box-shadow: 0px 3rem 4rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 3rem 4rem -2rem rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent p{
  width:0px;
  opacity:0;
  transition: opacity .3s ease 0s;
}

button:hover + .textcontent p{
  width:200px;
  opacity:1;
  transition: all .3s ease 0s;
}

<div>
  <button>
</button>
  <div class="textcontent">
    <p>some text</p>
  </div>
</div>