答:
I was fiddling around the other day and discovered I made a solution to this once.

Node.prototype.fitText = function(maxSize) {
  maxSize = maxSize || 500;
  this.style.whiteSpace = "nowrap";
  this.style.overflow = "scroll";
  this.style.fontSize = maxSize + "px";

  while (this.scrollWidth > this.clientWidth) {
    this.style.fontSize = --maxSize + "px";
  }
}

document.querySelector('.container').fitText();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  Text To Fit
</div></code>```

Title: How to change font-size dynamically so that it always fits into its parent container

Body:
I was fiddling around the other day and discovered I made a solution to this once.

Node.prototype.fitText = function(maxSize) {
  maxSize = maxSize || 500;
  this.style.whiteSpace = "nowrap";
  this.style.overflow = "scroll";
  this.style.fontSize = maxSize + "px";

  while (this.scrollWidth > this.clientWidth) {
    this.style.fontSize = --maxSize + "px";
  }
}

document.querySelector('.container').fitText();

<div class="container">
  Text To Fit
</div>


来源: stackexchange

问:
Setting the viewWindow min max in hours of a Google Chart in Razor
I have an Google chart with the following options for the hAxis. But I cannot get the viewWindow to work

This Razor code:

```<code>    hAxis: {
            format: 'HH:mm',
            showTextEvery: 2,
            gridlines: {
                count: -1,
                units: {hours: {format:['HH:mm']}}
            },
            viewWindow: {
                min: new Date(@Model.SelectedDate.Year, @Model.SelectedDate.Month-1, @Model.SelectedDate.Day, 0),
                max: new Date(@Model.SelectedDate.Year, @Model.SelectedDate.Month-1, @Model.SelectedDate.Day, 23, 59)
            }
        },
</code>```

Produces the following html

```<code>    hAxis:{
            format: 'HH:mm',
            showTextEvery: 2,
    viewWindow: {
                min: new Date(2017, 7-1, 6, 0),
                max: new Date(2017, 7-1, 6, 23, 59)
            },
            gridlines: {
                count: -1,
                units: {hours: {format:['HH:mm']}}
            },

        },
</code>```

This code gives an error: getTime is not a function

How do I change the razor code so it will take my date in the javascript part for the chart.

When I remove the lines of the viewWindow part then my chart is working. So I don't think my Data is the problem.

And some of my data

```<code>    data.addColumn('datetime', 'Tijdstip');
    data.addColumn('number', 'gemeten temperatuur');
        data.addRows([
                [new Date(2017, 2-1, 22, 0, 0, 34), -16.56200000],
                [new Date(2017, 2-1, 22, 0, 1, 38), -16.44000000],
                [new Date(2017, 2-1, 22, 0, 2, 39), -16.27600000],
                [new Date(2017, 2-1, 22, 0, 3, 44), -15.78500000],
                [new Date(2017, 2-1, 22, 0, 4, 47), -15.74400000],
                [new Date(2017, 2-1, 22, 0, 5, 52), -15.41700000],
                [new Date(2017, 2-1, 22, 0, 6, 52), -15.17100000],
                [new Date(2017, 2-1, 22, 0, 7, 57), -14.88500000],
                [new Date(2017, 2-1, 22, 0, 8, 58), -14.35300000],
</code>```

tia Ronald

答:
the values used for viewWindow are valid, don't believe that is the problem

see following working snippet using the posted options...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    [new Date(2017, 6, 6, 1), 1000],
    [new Date(2017, 6, 6, 2), 2000],
    [new Date(2017, 6, 6, 3), 3000],
    [new Date(2017, 6, 6, 4), 4000],
    [new Date(2017, 6, 6, 5), 5000],
    [new Date(2017, 6, 6, 6), 6000]
  ]);

  var options = {
    hAxis:{
      format: 'HH:mm',
      showTextEvery: 2,
      viewWindow: {
        min: new Date(2017, 7-1, 6, 0),
        max: new Date(2017, 7-1, 6, 23, 59)
      },
      gridlines: {
        count: -1,
        units: {hours: {format:['HH:mm']}}
      },
    },
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an Google chart with the following options for the hAxis. But I cannot get the viewWindow to work

This Razor code:

    hAxis: {
            format: 'HH:mm',
            showTextEvery: 2,
            gridlines: {
                count: -1,
                units: {hours: {format:['HH:mm']}}
            },
            viewWindow: {
                min: new Date(@Model.SelectedDate.Year, @Model.SelectedDate.Month-1, @Model.SelectedDate.Day, 0),
                max: new Date(@Model.SelectedDate.Year, @Model.SelectedDate.Month-1, @Model.SelectedDate.Day, 23, 59)
            }
        },

Produces the following html

    hAxis:{
            format: 'HH:mm',
            showTextEvery: 2,
    viewWindow: {
                min: new Date(2017, 7-1, 6, 0),
                max: new Date(2017, 7-1, 6, 23, 59)
            },
            gridlines: {
                count: -1,
                units: {hours: {format:['HH:mm']}}
            },

        },

This code gives an error: getTime is not a function

How do I change the razor code so it will take my date in the javascript part for the chart.

When I remove the lines of the viewWindow part then my chart is working. So I don't think my Data is the problem.

And some of my data

    data.addColumn('datetime', 'Tijdstip');
    data.addColumn('number', 'gemeten temperatuur');
        data.addRows([
                [new Date(2017, 2-1, 22, 0, 0, 34), -16.56200000],
                [new Date(2017, 2-1, 22, 0, 1, 38), -16.44000000],
                [new Date(2017, 2-1, 22, 0, 2, 39), -16.27600000],
                [new Date(2017, 2-1, 22, 0, 3, 44), -15.78500000],
                [new Date(2017, 2-1, 22, 0, 4, 47), -15.74400000],
                [new Date(2017, 2-1, 22, 0, 5, 52), -15.41700000],
                [new Date(2017, 2-1, 22, 0, 6, 52), -15.17100000],
                [new Date(2017, 2-1, 22, 0, 7, 57), -14.88500000],
                [new Date(2017, 2-1, 22, 0, 8, 58), -14.35300000],

tia Ronald

Body:
the values used for viewWindow are valid, don't believe that is the problem

see following working snippet using the posted options...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    [new Date(2017, 6, 6, 1), 1000],
    [new Date(2017, 6, 6, 2), 2000],
    [new Date(2017, 6, 6, 3), 3000],
    [new Date(2017, 6, 6, 4), 4000],
    [new Date(2017, 6, 6, 5), 5000],
    [new Date(2017, 6, 6, 6), 6000]
  ]);

  var options = {
    hAxis:{
      format: 'HH:mm',
      showTextEvery: 2,
      viewWindow: {
        min: new Date(2017, 7-1, 6, 0),
        max: new Date(2017, 7-1, 6, 23, 59)
      },
      gridlines: {
        count: -1,
        units: {hours: {format:['HH:mm']}}
      },
    },
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


问:
Resize DIV from either side, not just the corner
I want to resize a DIV, from anywhere, and not just from the corners.

I used css code:

```<code>resize: horizontal;
</code>```

My div, look like this

But I want something, Like this (resize like sulime text)

Is there any way to do this, like some javascript function?

答:
Try the following

```<code>resize: both;
overflow: auto;
</code>```

It will let you resize the div both horizontally and  Vertically from Bottom Right Corner.

Hope this might help to some extent.

Body:
I want to resize a DIV, from anywhere, and not just from the corners.

I used css code:

resize: horizontal;

My div, look like this

But I want something, Like this (resize like sulime text)

Is there any way to do this, like some javascript function?

Body:
Try the following

resize: both;
overflow: auto;

It will let you resize the div both horizontally and  Vertically from Bottom Right Corner.

Hope this might help to some extent.


问:
How can I save setting of my menu_toggle using cookie?
I want to toggle my menu and save its settings in the cookie. Here is my Jquery code for toggle button:

My HTML

```<code>  <div class="nav toggle">
  <a id="menu_toggle"><i class="fa fa-bars"></i></a>
  </div>
</code>```

My Code

```<code> var $MENU_TOGGLE = $('#menu_toggle')
 $MENU_TOGGLE.on('click', function() {
    console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
        $SIDEBAR_MENU.find('li.active ul').hide();
        $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
        $SIDEBAR_MENU.find('li.active-sm ul').show();
        $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

$BODY.toggleClass('nav-md nav-sm');

setContentHeight();
 });
</code>```

答:
I just wrote this earlier today for a website that I am building. My preferred method was to add a cookie check to the head. This adds a class to the html that you can attach styling to.

```<code><script type="text/javascript">
  if (document.cookie.replace(/(?:(?:^|.*;\s*)hasClosedMenu\s*\=\s*([^;]*).*$)|^.*$/, "$1") == false) {
    document.documentElement.className += " menu-open "
  }
</script>
</code>```

Below you will find the function that sets the cookie determining whether the menu is open or not.

```<code>$('.menu-toggle').on('click',function(){
  $('html').toggleClass('open-menu');
  if ($('html').hasClass('open-menu')){
    document.cookie = "hasClosedMenu=; max-age=0; domain="+window.location.hostname+"; path=/; ";
  } else {
    document.cookie = "hasClosedMenu=true; max-age=864000; domain="+window.location.hostname+"; path=/; ";
  }
});
</code>```

I hope this helps.

Body:
I want to toggle my menu and save its settings in the cookie. Here is my Jquery code for toggle button:

My HTML

My Code

 var $MENU_TOGGLE = $('#menu_toggle')
 $MENU_TOGGLE.on('click', function() {
    console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
        $SIDEBAR_MENU.find('li.active ul').hide();
        $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
        $SIDEBAR_MENU.find('li.active-sm ul').show();
        $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

$BODY.toggleClass('nav-md nav-sm');

setContentHeight();
 });

Body:
I just wrote this earlier today for a website that I am building. My preferred method was to add a cookie check to the head. This adds a class to the html that you can attach styling to.

<script type="text/javascript">
  if (document.cookie.replace(/(?:(?:^|.*;\s*)hasClosedMenu\s*\=\s*([^;]*).*$)|^.*$/, "$1") == false) {
    document.documentElement.className += " menu-open "
  }
</script>

Below you will find the function that sets the cookie determining whether the menu is open or not.

$('.menu-toggle').on('click',function(){
  $('html').toggleClass('open-menu');
  if ($('html').hasClass('open-menu')){
    document.cookie = "hasClosedMenu=; max-age=0; domain="+window.location.hostname+"; path=/; ";
  } else {
    document.cookie = "hasClosedMenu=true; max-age=864000; domain="+window.location.hostname+"; path=/; ";
  }
});

I hope this helps.


问:
Outlook Addin VSTO - On demand expand folders
I have developed VSTO Addin using c#. In my application, I am creating PST data file.
In PST file, there is some big folder structures.so, it takes too much time. so, i want to make this structure on demand.

I done some R&D on Folder expand event. but i did not get any thing. Please help me.

if anyone of you having idea about outlook folder expand event then please do comment. otherwise please suggest how to achieve this functionality in other ways.

答:
You can  select a subfolder of the folder in question to make sure the parent folder is expanded:</p>

```<code>Application.ActiveExplorer.CurrentFolder = YourSubFolder
</code>```

Body:
You can  select a subfolder of the folder in question to make sure the parent folder is expanded:

Application.ActiveExplorer.CurrentFolder = YourSubFolder


问:
How do I get child elements from class list object?
think I have some class of same content

```<code> <div class="parentclass">

         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
    </div>

  <div class="parentclass">

         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
    </div>
</code>```

I can get all the parent class object in an array by

```<code>var pClassList= document.getElementsByClassName("parentclass");
</code>```

My question is how can I access the child classes "childClass" from pClassList array calling it index like

```<code>var childClassList1= pClassList[0].getElementsByClassName("childClass");
var childClassList2= pClassList[1].getElementsByClassName("childClass");
</code>```

答:
An alternative I think is you select as you want childClass is like :

var childClassList1= document.querySelector('.childClass:nth-child(2)');```

Body:
think I have some class of same content

I can get all the parent class object in an array by

var pClassList= document.getElementsByClassName("parentclass");

My question is how can I access the child classes "childClass" from pClassList array calling it index like

var childClassList1= pClassList[0].getElementsByClassName("childClass");
var childClassList2= pClassList[1].getElementsByClassName("childClass");


问:
how to update Android app in background service with no history(empty stack)?
I have an Android application(3rd party, not in google play) which checks for newer version once a day. The process of checking for newer version and downloading it, took place in a Service. Because i didn't want to halt user(specially when Internet has a low speed) from navigating/using other part of application, i used a service.

I implement a BroadcastReceiver to be notified when download completes(ACTION_DOWNLOAD_COMPLETE). I want to install new version by starting its activity with an empty stack. I do as follows:

```<code>installIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(installIntent);
</code>```

but i got this error in log:

```<code>Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
</code>```

and starting intent with Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY flag, won't clear the activities stack.

Notice: if user click on back button or cancel, navigates to activity of my app but in such case i wanted app to close without "not responding" message.

Question: Is it possible to run activity(installer one) with empty activity stack in a service? Is there any other way to do this work? If yes how?

By the way, my intention from all these is to force user to install updates.
Thanks.

答:
There are a few ways to do this. Here is one example:

Create an "installer" Activity, which just launches the Android installer and then calls finish() in onCreate().

From your BroadcastReceiver you can cause your application to exit and launch the installer by doing this:

```<code>Intent intent = new Intent(context, MyInstallerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
</code>```

This will clear any activities in your application that may be running and run MyInstallerActivity. In MyInstallerActivity.onCreate() you should just launch the Android installer (as you are already doing) and call finish(). If the user cancels the installation, your app will no longer be running.

Body:
I have an Android application(3rd party, not in google play) which checks for newer version once a day. The process of checking for newer version and downloading it, took place in a Service. Because i didn't want to halt user(specially when Internet has a low speed) from navigating/using other part of application, i used a service.

I implement a BroadcastReceiver to be notified when download completes(ACTION_DOWNLOAD_COMPLETE). I want to install new version by starting its activity with an empty stack. I do as follows:

installIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(installIntent);

but i got this error in log:

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

and starting intent with Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY flag, won't clear the activities stack.

Notice: if user click on back button or cancel, navigates to activity of my app but in such case i wanted app to close without "not responding" message.

Question: Is it possible to run activity(installer one) with empty activity stack in a service? Is there any other way to do this work? If yes how?

By the way, my intention from all these is to force user to install updates.
Thanks.

Body:
There are a few ways to do this. Here is one example:

Create an "installer" Activity, which just launches the Android installer and then calls finish() in onCreate().

From your BroadcastReceiver you can cause your application to exit and launch the installer by doing this:

Intent intent = new Intent(context, MyInstallerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

This will clear any activities in your application that may be running and run MyInstallerActivity. In MyInstallerActivity.onCreate() you should just launch the Android installer (as you are already doing) and call finish(). If the user cancels the installation, your app will no longer be running.


问:
Ho to store results of loop in .csv ? (Python)
I'm running tweepy and I don't know how to store tweets in a csv file

```<code>for tweet in tweepy.Cursor(api.search,q=search+
    lang="en").items(num_tweets):

    data = tweet.text
    print (tweet.text)

import csv
c = csv.writer(open("file.csv", "w"))
c.writerow(data)
</code>```

csv.Error: iterable expected, not float

I'l also tried float(data) but it's not working.

My goal is to store these tweets in csv file to have the format required by cool.api

```<code># batch example
cool.api([
    "I love Stack Overflow!",
    "Barack Obama is better at Twitter than Donald Trump."
])
</code>```

答:
Simple fix. The argument passed to writer must be an iterable (list, tuple, etc.) so that it can write each thing in the utterable to the cvs file. So all you need to do is put data in a list:

```<code>c.writerow([data])
</code>```

You probably want to make a list and add tweets to it as you go through your for loop, or write a new row each time.

```<code>import csv
f = open("file.csv", "w")
c = csv.writer(f)
for tweet in tweepy.Cursor(api.search,q=search+
    lang="en").items(num_tweets):
    c.writerow([tweet.txt])
f.close()
</code>```

Body:
I'm running tweepy and I don't know how to store tweets in a csv file

for tweet in tweepy.Cursor(api.search,q=search+
    lang="en").items(num_tweets):

    data = tweet.text
    print (tweet.text)

import csv
c = csv.writer(open("file.csv", "w"))
c.writerow(data)

csv.Error: iterable expected, not float

I'l also tried float(data) but it's not working.

My goal is to store these tweets in csv file to have the format required by cool.api

# batch example
cool.api([
    "I love Stack Overflow!",
    "Barack Obama is better at Twitter than Donald Trump."
])

Body:
Simple fix. The argument passed to writer must be an iterable (list, tuple, etc.) so that it can write each thing in the utterable to the cvs file. So all you need to do is put data in a list:

c.writerow([data])

You probably want to make a list and add tweets to it as you go through your for loop, or write a new row each time.

import csv
f = open("file.csv", "w")
c = csv.writer(f)
for tweet in tweepy.Cursor(api.search,q=search+
    lang="en").items(num_tweets):
    c.writerow([tweet.txt])
f.close()


问:
All cells in autofill range being set to nothing Excel
So I am trying to use the autofill method in vba right now over a range that is set to a variable. I know that the range of cells you are autofilling from must be included in the destination. So, I do just that. However, and much to my surprise, all the cells in the range are being set to nothing.

Here is the code:

```<code>          Dim table2Range As Range
          Dim table2Range2 As Range
          Dim table2Range3 As Range
          Dim tableholder As Range

          Set table2Range2 = Range("Y54").End(xlToRight).Offset(0, 1)
          Set table2Range3 = Range("Y77").End(xlToRight).Offset(0, 1)
          Set table2Range = Range(table2Range2, table2Range3)
          Set tableholder = Range("y54", table2Range3)
          tableholder.Select

             table2Range.AutoFill Destination:=Selection    'This is setting all my cells to nothing for some reason
</code>```

Here is the before & after screenshots:Before, After

Any help is hugely appreciated!

答:
Your AutoFill line of code should be:

```<code>SourceRange.AutoFill Destination:FillRange
</code>```

It seems like your "table2Range " is the source, which overlap with your Fill Range. I.e:

 .End(xlToRight).Offset(0, 1) will set range from Y54 to the rightmost cell of the same row.

You can edit the source range with hardcode first (i.e. Range("Y54:Z77") and see if that works for you, then work from there

For example (try on a new workbook):

```<code>Sub example()
Set SourceRange = Worksheets("Sheet1").Range("A1:B1")
Set fillRange = Worksheets("Sheet1").Range("A1:G1")
SourceRange.AutoFill Destination:=fillRange
End Sub
</code>```

Enter "1" in cell(A1) and "2" in Cell(B1) and run the code.

Body:
So I am trying to use the autofill method in vba right now over a range that is set to a variable. I know that the range of cells you are autofilling from must be included in the destination. So, I do just that. However, and much to my surprise, all the cells in the range are being set to nothing.

Here is the code:

          Dim table2Range As Range
          Dim table2Range2 As Range
          Dim table2Range3 As Range
          Dim tableholder As Range

          Set table2Range2 = Range("Y54").End(xlToRight).Offset(0, 1)
          Set table2Range3 = Range("Y77").End(xlToRight).Offset(0, 1)
          Set table2Range = Range(table2Range2, table2Range3)
          Set tableholder = Range("y54", table2Range3)
          tableholder.Select

             table2Range.AutoFill Destination:=Selection    'This is setting all my cells to nothing for some reason

Here is the before & after screenshots:Before, After

Any help is hugely appreciated!

Body:
Your AutoFill line of code should be:

SourceRange.AutoFill Destination:FillRange

It seems like your "table2Range " is the source, which overlap with your Fill Range. I.e:

 .End(xlToRight).Offset(0, 1) will set range from Y54 to the rightmost cell of the same row.

You can edit the source range with hardcode first (i.e. Range("Y54:Z77") and see if that works for you, then work from there

For example (try on a new workbook):

Sub example()
Set SourceRange = Worksheets("Sheet1").Range("A1:B1")
Set fillRange = Worksheets("Sheet1").Range("A1:G1")
SourceRange.AutoFill Destination:=fillRange
End Sub

Enter "1" in cell(A1) and "2" in Cell(B1) and run the code.


问:
A sort-of reversed cascaded delete 1-many
I've had a search and didn't find quite what I was looking for so apologies if this has already been asked...

I'm using a combo of PHP and MYSQL.

I have a table 'member' with a foreign key to an 'address' table.

The member table:

```<code>CREATE TABLE __JEH_MEMBER (" .
    "id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " .
    "title VARCHAR(". self::TITLE_MAX_STRLEN ."), " .
    "forename VARCHAR(". self::NAME_MAX_STRLEN .") NOT NULL, " .
    "surname VARCHAR(". self::NAME_MAX_STRLEN .") NOT NULL, " .
    "addr_id INT NOT NULL, " .
    "bday DATE, " .
    "FOREIGN KEY(addr_id) REFERENCES __JEH_ADDRESS(id)" .
    // Note: No cascade spec here deliberately for now..
") ENGINE=InnoDB;";
</code>```

The address table:

```<code>"CREATE TABLE __JEH_ADDRESS(" .
    "id       INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " .
    "street1  VARCHAR(120) NOT NULL, " .
    "street2  VARCHAR(120), " .
    "street3  VARCHAR(120), " .
    "street4  VARCHAR(120), " .
    "city     VARCHAR(50) NOT NULL, " .
    "state    VARCHAR(50) NOT NULL, " .
    "country  VARCHAR(50) NOT NULL, " .
    "postcode VARCHAR(16) NOT NULL" .
") ENGINE=InnoDB;";
</code>```

If I delete a user, I want to delete the address only if no other user also lives at that address.

So, my question is, is there some clever reverse of a cascaded delete where the database would know how to do this or do I need to stick with my existing method of locking both tables, checking the condition, and then only deleting the address if no one else references it?

答:
I know this is an old question, but an even simpler answer is:

Set up your foreign key constraints as you have them

Find the addr_id that you want to maybe delete: select addr_id into @addr_id from __JEH_MEMBER where ...

Remove the current reference to that address: delete from __JEH_MEMBER where ...

Try and remove the address: delete from __JEH_ADDRESS where id = @addr_id

Note that due to the PRIMARY KEY constraints, step 4 will fail if there are any references to it still outstanding, but succeed if you just removed the last reference.

Body:
I've had a search and didn't find quite what I was looking for so apologies if this has already been asked...

I'm using a combo of PHP and MYSQL.

I have a table 'member' with a foreign key to an 'address' table.

The member table:

CREATE TABLE __JEH_MEMBER (" .
    "id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " .
    "title VARCHAR(". self::TITLE_MAX_STRLEN ."), " .
    "forename VARCHAR(". self::NAME_MAX_STRLEN .") NOT NULL, " .
    "surname VARCHAR(". self::NAME_MAX_STRLEN .") NOT NULL, " .
    "addr_id INT NOT NULL, " .
    "bday DATE, " .
    "FOREIGN KEY(addr_id) REFERENCES __JEH_ADDRESS(id)" .
    // Note: No cascade spec here deliberately for now..
") ENGINE=InnoDB;";

The address table:

"CREATE TABLE __JEH_ADDRESS(" .
    "id       INT NOT NULL PRIMARY KEY AUTO_INCREMENT, " .
    "street1  VARCHAR(120) NOT NULL, " .
    "street2  VARCHAR(120), " .
    "street3  VARCHAR(120), " .
    "street4  VARCHAR(120), " .
    "city     VARCHAR(50) NOT NULL, " .
    "state    VARCHAR(50) NOT NULL, " .
    "country  VARCHAR(50) NOT NULL, " .
    "postcode VARCHAR(16) NOT NULL" .
") ENGINE=InnoDB;";

If I delete a user, I want to delete the address only if no other user also lives at that address.

So, my question is, is there some clever reverse of a cascaded delete where the database would know how to do this or do I need to stick with my existing method of locking both tables, checking the condition, and then only deleting the address if no one else references it?


问:
Local preprocessing with Gulp, Stylus, and Browser-sync
I'm trying to setup CSS preprocessing and browser-sync for a client on windows. Prepros seems to be junk, and he can't use codeKit because it's Mac only.

I gave him these resources: https://webdesign.tutsplus.com/tutorials/supercharge-your-local-wordpress-development--cms-28303 and https://browsersync.io/docs/gulp

The preprocessing works great, but the browser has to be manually refreshed to see the CSS changes.

Can you spot what is incorrect in this code? MAMP is also involved... so it could be something else. I'm trying out different configurations to trouble-shoot.

```<code>// gulpfile.js
var gulp = require('gulp');
var browserSync = require('browser-sync');
var stylus = require('gulp-stylus');

gulp.task('setup-server', function() {
  var files = [
    './style.css',
    './*.php',
  ];
  browserSync.init(files, {
    proxy: 'https://website-name.dev',
  });
});

gulp.task('compile-stylus', function () {
  return gulp.src('stylus/*.styl')
    .pipe( stylus({
      // options
    }))
    .pipe( gulp.dest('./') ) // root of theme
    .pipe( browserSync.stream() )
  ;
});

gulp.task('default', ['setup-server', 'compile-stylus'], function() {
  gulp.watch('stylus/**/*.styl', ['compile-stylus']);
});
</code>```

file structure

```
project-root
  gulpfile.js
  /stylus
    /partials
    style.styl
```

答:
Try these changes:

```<code>var browserSync = require("browser-sync").create();
var reload = browserSync.reload;
</code>```

and the following change at the end of the task:

```<code>gulp.task('compile-stylus', function () {
  return gulp.src('stylus/*.styl')
    .pipe( stylus({
      // options
    }))
    .pipe( gulp.dest('./') ) // root of theme
    .pipe( browserSync.reload({stream: true}));
});
</code>```

And I assume you meant gulpfile.js not gruntfile.js in your folder structure.

Body:
I'm trying to setup CSS preprocessing and browser-sync for a client on windows. Prepros seems to be junk, and he can't use codeKit because it's Mac only.

I gave him these resources: https://webdesign.tutsplus.com/tutorials/supercharge-your-local-wordpress-development--cms-28303 and https://browsersync.io/docs/gulp

The preprocessing works great, but the browser has to be manually refreshed to see the CSS changes.

Can you spot what is incorrect in this code? MAMP is also involved... so it could be something else. I'm trying out different configurations to trouble-shoot.

// gulpfile.js
var gulp = require('gulp');
var browserSync = require('browser-sync');
var stylus = require('gulp-stylus');

gulp.task('setup-server', function() {
  var files = [
    './style.css',
    './*.php',
  ];
  browserSync.init(files, {
    proxy: 'https://website-name.dev',
  });
});

gulp.task('compile-stylus', function () {
  return gulp.src('stylus/*.styl')
    .pipe( stylus({
      // options
    }))
    .pipe( gulp.dest('./') ) // root of theme
    .pipe( browserSync.stream() )
  ;
});

gulp.task('default', ['setup-server', 'compile-stylus'], function() {
  gulp.watch('stylus/**/*.styl', ['compile-stylus']);
});

file structure

project-root
  gulpfile.js
  /stylus
    /partials
    style.styl

Body:
Try these changes:

var browserSync = require("browser-sync").create();
var reload = browserSync.reload;

and the following change at the end of the task:

gulp.task('compile-stylus', function () {
  return gulp.src('stylus/*.styl')
    .pipe( stylus({
      // options
    }))
    .pipe( gulp.dest('./') ) // root of theme
    .pipe( browserSync.reload({stream: true}));
});

And I assume you meant gulpfile.js not gruntfile.js in your folder structure.


问:
Distinguish sender from receiver with Socket.io
I have built a web application using JavaScript stack (MongoDB, ExpressJS, AngularJS, NodeJS). The registration works, the authentication works, the chat is which is using Socket.io works but I need a way of distinguishing which client is sending and which client is receiving the message in order to perform further functions with the user's data.

P.S. Since this is a project that I can not publish there are no code snippets in my post, hopefully it is alright

答:
I think a fine way to handle the clients is creating a Handler class, a Client object and create a clientList in the handler, this way is easier to distinguish the clients. Some months ago I built a simple open source one-to-one random chat using socket.io, and here are the handler and the client class.

I hope this example can help you.


问:
Kivy Animation Class to Animate Kivy Images
Python 3.4
Kivy 1.10.0

I am attempting to use Kivy Animation class to animate my an Image class. This is so because I want to modify the anim_delay and position values for each image separately.

I want to modify the 'source' property of an image class. Although it recognizes the 'source' property, it attempts to multiply the filename string file.

How can I modify the image file names?

Working Example:

```<code>from kivy.app import App
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.image import Image

class Test(App):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)

        self.content = BoxLayout()
        self.content.orientation = 'vertical'
        self.anim_image = Image(source = 'image1.png')
        self.anim_button = Button(on_press=self.animate_image)
        self.content.add_widget(self.anim_image)
        self.content.add_widget(self.anim_button)

    def build(self):
        return self.content

    def animate_image(self, *args, **kwargs):
        image_animate = Animation()
        for i in range(4):
            image_animate += Animation(x = (i + 10), source = 'image' + str(i) + '.png', duration=(0.10 * i))
        image_animate.start(self.anim_image)

if __name__ == '__main__':
    Test().run()
</code>```

Error Log:

```<code>[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "C:\Python34x86\projects\rogue_like_app\repeatable issues\animation_image_source.py", line 31, in <module>
     Test().run()
   File "C:\Python34x86\lib\site-packages\kivy\app.py", line 828, in run
     runTouchApp()
   File "C:\Python34x86\lib\site-packages\kivy\base.py", line 504, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Python34x86\lib\site-packages\kivy\core\window\window_sdl2.py", line 663, in mainloop
     self._mainloop()
   File "C:\Python34x86\lib\site-packages\kivy\core\window\window_sdl2.py", line 405, in _mainloop
     EventLoop.idle()
   File "C:\Python34x86\lib\site-packages\kivy\base.py", line 339, in idle
     Clock.tick()
   File "C:\Python34x86\lib\site-packages\kivy\clock.py", line 581, in tick
     self._process_events()
   File "kivy\_clock.pyx", line 367, in kivy._clock.CyClockBase._process_events (kivy\_clock.c:7700)
   File "kivy\_clock.pyx", line 397, in kivy._clock.CyClockBase._process_events (kivy\_clock.c:7577)
   File "kivy\_clock.pyx", line 395, in kivy._clock.CyClockBase._process_events (kivy\_clock.c:7498)
   File "kivy\_clock.pyx", line 167, in kivy._clock.ClockEvent.tick (kivy\_clock.c:3490)
   File "C:\Python34x86\lib\site-packages\kivy\animation.py", line 345, in _update
     value = calculate(a, b, t)
   File "C:\Python34x86\lib\site-packages\kivy\animation.py", line 376, in _calculate
     return (a * (1. - t)) + (b * t)
 TypeError: can't multiply sequence by non-int of type 'float'
</code>```

Looking into animation.py from Kivy Code I see that the values that return an error from above are:

```<code>a = image2.png
b = image1.png
t = 0.0
</code>```

Does this mean this doing an animation like I was planning to in not inherent in the Kivy code? Or, how do I fix this issue so that the animation will loop correctly?

答:
The error occurs because the Animation cannot do a transition from an str object to an str object "image0.png" -> "image1.png" !?

One way to work around this is to use the on_complete callback

```<code>def animate_image(self, *args, **kwargs):
    image_animate = Animation()

    def f(i, w):
        w.source = 'image%d.jpg' % i

    for i in range(4):

        a = Animation(x = (i + 10), duration=(0.10 * i),
                      )
        a.on_complete = functools.partial(f, i)

        image_animate += a

    image_animate.start(self.anim_image)
</code>```

Another option is to have a image_num property on the image and bind it so it will change the image accordingly ...

for example in the KV file:

```<code><MyImage>:
    image_num: 0
    source: "image%d.png" % int(self.image_num)
</code>```

and in the .py file:

```<code>image_animate += Animation(x = (i + 10), image_num=i, duration=(0.10 * i))
</code>```

Body:
Python 3.4
Kivy 1.10.0

I am attempting to use Kivy Animation class to animate my an Image class. This is so because I want to modify the anim_delay and position values for each image separately.

I want to modify the 'source' property of an image class. Although it recognizes the 'source' property, it attempts to multiply the filename string file.

How can I modify the image file names?

Working Example:

from kivy.app import App
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.image import Image

class Test(App):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)

        self.content = BoxLayout()
        self.content.orientation = 'vertical'
        self.anim_image = Image(source = 'image1.png')
        self.anim_button = Button(on_press=self.animate_image)
        self.content.add_widget(self.anim_image)
        self.content.add_widget(self.anim_button)

    def build(self):
        return self.content

    def animate_image(self, *args, **kwargs):
        image_animate = Animation()
        for i in range(4):
            image_animate += Animation(x = (i + 10), source = 'image' + str(i) + '.png', duration=(0.10 * i))
        image_animate.start(self.anim_image)

if __name__ == '__main__':
    Test().run()

Error Log:

[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "C:\Python34x86\projects\rogue_like_app\repeatable issues\animation_image_source.py", line 31, in <module>
     Test().run()
   File "C:\Python34x86\lib\site-packages\kivy\app.py", line 828, in run
     runTouchApp()
   File "C:\Python34x86\lib\site-packages\kivy\base.py", line 504, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Python34x86\lib\site-packages\kivy\core\window\window_sdl2.py", line 663, in mainloop
     self._mainloop()
   File "C:\Python34x86\lib\site-packages\kivy\core\window\window_sdl2.py", line 405, in _mainloop
     EventLoop.idle()
   File "C:\Python34x86\lib\site-packages\kivy\base.py", line 339, in idle
     Clock.tick()
   File "C:\Python34x86\lib\site-packages\kivy\clock.py", line 581, in tick
     self._process_events()
   File "kivy\_clock.pyx", line 367, in kivy._clock.CyClockBase._process_events (kivy\_clock.c:7700)
   File "kivy\_clock.pyx", line 397, in kivy._clock.CyClockBase._process_events (kivy\_clock.c:7577)
   File "kivy\_clock.pyx", line 395, in kivy._clock.CyClockBase._process_events (kivy\_clock.c:7498)
   File "kivy\_clock.pyx", line 167, in kivy._clock.ClockEvent.tick (kivy\_clock.c:3490)
   File "C:\Python34x86\lib\site-packages\kivy\animation.py", line 345, in _update
     value = calculate(a, b, t)
   File "C:\Python34x86\lib\site-packages\kivy\animation.py", line 376, in _calculate
     return (a * (1. - t)) + (b * t)
 TypeError: can't multiply sequence by non-int of type 'float'

Looking into animation.py from Kivy Code I see that the values that return an error from above are:

a = image2.png
b = image1.png
t = 0.0

Does this mean this doing an animation like I was planning to in not inherent in the Kivy code? Or, how do I fix this issue so that the animation will loop correctly?

Body:
The error occurs because the Animation cannot do a transition from an str object to an str object "image0.png" -> "image1.png" !?

One way to work around this is to use the on_complete callback

def animate_image(self, *args, **kwargs):
    image_animate = Animation()

    def f(i, w):
        w.source = 'image%d.jpg' % i

    for i in range(4):

        a = Animation(x = (i + 10), duration=(0.10 * i),
                      )
        a.on_complete = functools.partial(f, i)

        image_animate += a

    image_animate.start(self.anim_image)

Another option is to have a image_num property on the image and bind it so it will change the image accordingly ...

for example in the KV file:

<MyImage>:
    image_num: 0
    source: "image%d.png" % int(self.image_num)

and in the .py file:

image_animate += Animation(x = (i + 10), image_num=i, duration=(0.10 * i))


问:
Count cells greater than 0 by group
I am trying to count the number of cells greater than 0 by group, and I need help as to how to approach this.

My data looks like this:

```<code>Group   Number of Shoes
    1                 0
    1                 1
    1                 2
    2                 0
    2                NA
    2                 1
    3                 1
    3                 2
    3                 2
</code>```

And I want this:

```<code>Group       Shoe owners
    1                 2
    2                 1
    3                 3
</code>```

答:
You can do this simply with:

```<code>aggregate(Number.of.Shoes ~ Group, df, function(x) sum(x > 0, na.rm = TRUE))
</code>```

The result:

```<code>  Group Number.of.Shoes
1     1               2
2     2               1
3     3               3
</code>```

This can also be done with dplyr package:

```<code>library(dplyr)
df %>%
  group_by(Group) %>%
  summarise(counts = sum(Number.of.Shoes > 0, na.rm = TRUE))
</code>```

Title: Count cells greater than 0 by group

Body:
I am trying to count the number of cells greater than 0 by group, and I need help as to how to approach this.

My data looks like this:

Group   Number of Shoes
    1                 0
    1                 1
    1                 2
    2                 0
    2                NA
    2                 1
    3                 1
    3                 2
    3                 2

And I want this:

Group       Shoe owners
    1                 2
    2                 1
    3                 3

Body:
You can do this simply with:

aggregate(Number.of.Shoes ~ Group, df, function(x) sum(x > 0, na.rm = TRUE))

The result:

  Group Number.of.Shoes
1     1               2
2     2               1
3     3               3

This can also be done with dplyr package:

library(dplyr)
df %>%
  group_by(Group) %>%
  summarise(counts = sum(Number.of.Shoes > 0, na.rm = TRUE))


问:
Why did boost regex run out of stack space?
```<code>#include <boost/regex.hpp>
#include <string>
#include <iostream>

using namespace boost;
static const regex regexp(
        "std::vector<"
            "(std::map<"
                   "(std::pair<((\\w+)(::)?)+, (\\w+)>,?)+"
             ">,?)+"
        ">");

std::string errorMsg =
"std::vector<"
        "std::map<"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>"
        ">,"
        "std::map<"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>"
        ">"
">";
int main()
{
    smatch result;
    if(regex_match(errorMsg, result, regexp))
    {
        for (unsigned i = 0; i < result.size(); ++i)
        {
            std::cout << result[i] << std::endl;
        }
    }

//    std::cout << errorMsg << std::endl;

    return 0;
}
</code>```

this produces:

```<code>terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::runtime_error>
>'   what():  Ran out of stack space trying to match the regular expression.
</code>```

compiled with

```<code>g++ regex.cc -lboost_regex
</code>```

EDIT

my platform:

```<code>g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
libboost-regex1.42
Intel(R) Core(TM)2 Quad CPU Q9400 @ 2.66GHz
So the latest Ubuntu 64 bit
</code>```

答:
((\\w+)(::)?)+ is one of the so called "pathological" regular expressions -- it's going to take exponential time, because you have two expressions which are dependent upon each other one right after the other. That is, it fails due to catastrophic backtracking.

Consider if we follow the example of the link, and reduce "something more complicated" to "x". Let's do that with \\w:

((x+)(::)?)+

Let's also assume that our input is never going to have ::. Having this actually makes the regex more complex, so if we throw out complexity then we really should be making things simpler if nothing else:

(x+)+

Now you've got a textbook nested quantifier problem like that detailed in the link above.

There are a few ways to fix this but the simplest way is probably to just disallow backtracking on the inner match using the atomic group modifier "(?>":

((?>\\w+)(::)?)+

Body:
#include <boost/regex.hpp>
#include <string>
#include <iostream>

using namespace boost;
static const regex regexp(
        "std::vector<"
            "(std::map<"
                   "(std::pair<((\\w+)(::)?)+, (\\w+)>,?)+"
             ">,?)+"
        ">");

std::string errorMsg =
"std::vector<"
        "std::map<"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>"
        ">,"
        "std::map<"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>,"
                "std::pair<Test::Test, int>"
        ">"
">";
int main()
{
    smatch result;
    if(regex_match(errorMsg, result, regexp))
    {
        for (unsigned i = 0; i < result.size(); ++i)
        {
            std::cout << result[i] << std::endl;
        }
    }

//    std::cout << errorMsg << std::endl;

    return 0;
}

this produces:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::runtime_error>
>'   what():  Ran out of stack space trying to match the regular expression.

compiled with

g++ regex.cc -lboost_regex

EDIT

my platform:

g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
libboost-regex1.42
Intel(R) Core(TM)2 Quad CPU Q9400 @ 2.66GHz
So the latest Ubuntu 64 bit


问:
How can I create User Defined Functions in Cassandra with Custom Java Class?
I couldn't find this anywhere online. How can I create a custom user defined function in cassandra?.

For Ex :

```<code>CREATE OR REPLACE FUNCTION customfunc(custommap map<text, int>)
CALLED ON NULL INPUT
RETURNS map<int,bigint>
LANGUAGE java AS 'return MyClass.mymethod(custommap);';
</code>```

Where "MyClass" is a class that I can register in the Classpath?

答:
Just adding my 2 cents to this thread as I tried building an external class method to support something similar.   After trying for hours with Datastax Sandbox 5.1 I could not get this to work as it couldn't seem to find my class and kept raising type errors.

My guess is that external JAR-based code for UDFs is not supported (see http://koff.io/posts/hll-in-cassandra/ and https://issues.apache.org/jira/browse/CASSANDRA-9892).   Support for "TRUSTED" JARs is in planning stages for Cassandra 4.   It might work in earlier versions pre 3.0 but I'm using the latest version from Datastax.

To work around this issue, I had to fallback to using a Javascript version instead (I was trying to convert a JSON string into a Map object).

While I realize Java UDFs perform better, the code I was testing was using Java Nashorn javascript support anyway, so using Javascript might not be such a bad thing.   It does end up with a simpler one-liner UDF.

Body:
I couldn't find this anywhere online. How can I create a custom user defined function in cassandra?.

For Ex :

CREATE OR REPLACE FUNCTION customfunc(custommap map<text, int>)
CALLED ON NULL INPUT
RETURNS map<int,bigint>
LANGUAGE java AS 'return MyClass.mymethod(custommap);';

Where "MyClass" is a class that I can register in the Classpath?


问:
Update Pivot Data Range String or Range
I'm working on a code that I've pieced together, but what I'm finding is that after the "used" range is found (I'm trying not to use .usedrange due to reliability) is that the SourceData:= is expecting a string (I think).

Is there a way to pass through the range from the Data sheet to the pivot table data range? I tried appending RealUsedRange.Address, but that was no luck either.

```<code>Sub UpdatePivotRange()

    Dim Rng1        As Range
    Dim oWB         As Workbook
    Dim oWS         As Worksheet
    Dim DataSheet   As Worksheet
    Dim oPT         As PivotTable

    Set oWB = ThisWorkbook
    Set DataSheet = oWB.Sheets("Data")
    Set Rng1 = RealUsedRange

    If Rng1 Is Nothing Then
        MsgBox "There is no used range, the worksheet is empty."
    Else
        For Each oWS In oWB.Worksheets
            For Each oPT In oWS.PivotTables
            'ERRROR BEGINS HERE #####
                oPT.ChangePivotCache _
                    oWB.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng1)
            'ERROR ENDS HERE #####
            Next oPT
        Next oWS
    End If

End Sub

Public Function RealUsedRange() As Range

    Dim FirstRow        As Long
    Dim LastRow         As Long
    Dim FirstColumn     As Integer
    Dim LastColumn      As Integer
    Dim DataSheet       As Worksheet
    Dim oWB             As Workbook

    On Error Resume Next
    Set oWB = ThisWorkbook
    Set DataSheet = oWB.Sheets("Data")
        With DataSheet

             FirstRow = DataSheet.Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _
             xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row

             FirstColumn = DataSheet.Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _
             xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column

             LastRow = DataSheet.Cells(.Rows.Count, "A").End(xlUp).Row

             LastColumn = DataSheet.Cells(1, Columns.Count).End(xlToLeft).Column

             Set RealUsedRange = Range(Cells(FirstRow, FirstColumn), Cells(LastRow, LastColumn))

         End With
    MsgBox "The range is" & RealUsedRange.Address
    On Error GoTo 0

End Function
</code>```

答:
I was able to amend the errored line by adding:

```<code>oPT.ChangePivotCache _
                    oWB.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Data!" & Rng1.Address(ReferenceStyle:=xlR1C1))
</code>```

Hope this helps anyone looking in the future.

Title: Update Pivot Data Range String or Range

Body:
I'm working on a code that I've pieced together, but what I'm finding is that after the "used" range is found (I'm trying not to use .usedrange due to reliability) is that the SourceData:= is expecting a string (I think).

Is there a way to pass through the range from the Data sheet to the pivot table data range? I tried appending RealUsedRange.Address, but that was no luck either.

Sub UpdatePivotRange()

    Dim Rng1        As Range
    Dim oWB         As Workbook
    Dim oWS         As Worksheet
    Dim DataSheet   As Worksheet
    Dim oPT         As PivotTable

    Set oWB = ThisWorkbook
    Set DataSheet = oWB.Sheets("Data")
    Set Rng1 = RealUsedRange

    If Rng1 Is Nothing Then
        MsgBox "There is no used range, the worksheet is empty."
    Else
        For Each oWS In oWB.Worksheets
            For Each oPT In oWS.PivotTables
            'ERRROR BEGINS HERE #####
                oPT.ChangePivotCache _
                    oWB.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng1)
            'ERROR ENDS HERE #####
            Next oPT
        Next oWS
    End If

End Sub

Public Function RealUsedRange() As Range

    Dim FirstRow        As Long
    Dim LastRow         As Long
    Dim FirstColumn     As Integer
    Dim LastColumn      As Integer
    Dim DataSheet       As Worksheet
    Dim oWB             As Workbook

    On Error Resume Next
    Set oWB = ThisWorkbook
    Set DataSheet = oWB.Sheets("Data")
        With DataSheet

             FirstRow = DataSheet.Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _
             xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row

             FirstColumn = DataSheet.Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _
             xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column

             LastRow = DataSheet.Cells(.Rows.Count, "A").End(xlUp).Row

             LastColumn = DataSheet.Cells(1, Columns.Count).End(xlToLeft).Column

             Set RealUsedRange = Range(Cells(FirstRow, FirstColumn), Cells(LastRow, LastColumn))

         End With
    MsgBox "The range is" & RealUsedRange.Address
    On Error GoTo 0

End Function

Body:
I was able to amend the errored line by adding:

oPT.ChangePivotCache _
                    oWB.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Data!" & Rng1.Address(ReferenceStyle:=xlR1C1))

Hope this helps anyone looking in the future.


问:
Maintaining data class when using zoo package function na.locf to fill values
I am using the zoo package to fill NA values with previous data.  This works great, except that the resulting filled data frame seems to be coerced to characters from dates and numeric.

My question:  Is there a way to maintain the original data class and not have the data coerced into characters?

My reproducible example (simplified version of how I receive my data):

```<code># Packages
library(dplyr)
library(zoo)

# Data
mydates <- as.Date(c("2017-06-28", "2017-06-29", "2017-06-30", "2017-07-01", "2017-07-02", "2017-07-03", "2017-07-04", "2017-07-05"))
item_1  <- c(180.6692, 180.6755, 180.6823, NA, NA, 180.7014, 180.7081, NA)
item_2  <- c(1295.1, 1293.019, 1290.876, NA, NA, 1288.256, NA, NA)
item_3 <-  c(1693.05, 1686.481, 1681.491, NA, NA, 1675.35, NA, NA)

# Data frame
df <- data.frame(mydates, item_1, item_2, item_3)

# Fill NAs with previous value
df_fill <- df %>%
  na.locf()

# Correct data class
str(df)

# Incorrect data class from filling NA values
str(df_fill)
</code>```

答:
Here are some alternative solutions. (1) and its variations perform na.locf on each column separately whereas (2) and its variation converts the data frame to zoo, applies na.locf and converts back.  (If you knew that there were no leading NAs in any column then na.rm = FALSE could optionally be omitted in these solutions.)

1) Perform na.locf on each column separately.  Only zoo is needed. It modifies df in place.  All othre solutions give output answer without modifying the inputs.

```<code>df[] <- lapply(df, na.locf, na.rm = FALSE)
</code>```

1a) Similar except it does not modify df

```<code>replace(df, TRUE, lapply(df, na.locf, na.rm = FALSE))
</code>```

1b)  Similar but uses %>% from magrittr or dplyr:

```<code>df %>% replace(., TRUE, lapply(., na.locf, na.rm = FALSE))
</code>```

2) convert to zoo, apply na.locf and convert back to data frame.  Only zoo is needed.

```<code>fortify.zoo(na.locf(read.zoo(df), na.rm = FALSE))
</code>```

2a) Similar but uses magrittr or dplyr

```<code>df %>% read.zoo %>% na.locf(na.rm = FALSE) %>% fortify.zoo
</code>```

Body:
I am using the zoo package to fill NA values with previous data.  This works great, except that the resulting filled data frame seems to be coerced to characters from dates and numeric.

My question:  Is there a way to maintain the original data class and not have the data coerced into characters?

My reproducible example (simplified version of how I receive my data):

# Packages
library(dplyr)
library(zoo)

# Data
mydates <- as.Date(c("2017-06-28", "2017-06-29", "2017-06-30", "2017-07-01", "2017-07-02", "2017-07-03", "2017-07-04", "2017-07-05"))
item_1  <- c(180.6692, 180.6755, 180.6823, NA, NA, 180.7014, 180.7081, NA)
item_2  <- c(1295.1, 1293.019, 1290.876, NA, NA, 1288.256, NA, NA)
item_3 <-  c(1693.05, 1686.481, 1681.491, NA, NA, 1675.35, NA, NA)

# Data frame
df <- data.frame(mydates, item_1, item_2, item_3)

# Fill NAs with previous value
df_fill <- df %>%
  na.locf()

# Correct data class
str(df)

# Incorrect data class from filling NA values
str(df_fill)

Body:
Here are some alternative solutions. (1) and its variations perform na.locf on each column separately whereas (2) and its variation converts the data frame to zoo, applies na.locf and converts back.  (If you knew that there were no leading NAs in any column then na.rm = FALSE could optionally be omitted in these solutions.)

1) Perform na.locf on each column separately.  Only zoo is needed. It modifies df in place.  All othre solutions give output answer without modifying the inputs.

df[] <- lapply(df, na.locf, na.rm = FALSE)

1a) Similar except it does not modify df

replace(df, TRUE, lapply(df, na.locf, na.rm = FALSE))

1b)  Similar but uses %>% from magrittr or dplyr:

df %>% replace(., TRUE, lapply(., na.locf, na.rm = FALSE))

2) convert to zoo, apply na.locf and convert back to data frame.  Only zoo is needed.

fortify.zoo(na.locf(read.zoo(df), na.rm = FALSE))

2a) Similar but uses magrittr or dplyr

df %>% read.zoo %>% na.locf(na.rm = FALSE) %>% fortify.zoo


问:
C# SmtpClient.Send() is slow because of BCC
I'm using "System.Net.Mail" for send email on our Intranet system in C#

The Send() method was very slow and I did not understand why.

After debugging, I've remove the BCC call : (MM is a MailMessage() and Item, a string email address) :

```<code>MM.Bcc.Add(new MailAddress(Item));
</code>```

Before I comment this line, an email was taking about 30 or 40 seconds. Now, it's about 2 seconds. Why?

Is there an explication about this? I can add "To" and "CC" with no problem of performance. But not "BCC".

答:
I had a similar problem and this drove me crazy trying to figure out what made some emails slow and others quick.

The first email sent after creating SmtpClient takes 5 seconds.  After that, reusing the same SmtpClient, it's about 0.4 seconds if done within 60 seconds of the previous one.  After that I think it releases it's connection to the pool.

However adding a CC that is a duplicate of the To address will always add an additional 5 seconds. Adding a duplicate CC twice will add 10 seconds.

I didn't check, but I assume the same would be true if duplicates are in the "TO" or "BCC" lists.

Here's the code to remove duplicates:

```<code>// check and remove duplicates
for (int x = 0; x < message.To.Count; x++)
{
    for (int y = message.To.Count - 1; y > x; y--)
    {
        if (message.To[y].Address == message.To[x].Address)
            message.To.RemoveAt(y);
    }
    for (int y = message.CC.Count - 1; y >= 0; y--)
    {
        if (message.CC[y].Address == message.To[x].Address)
            message.CC.RemoveAt(y);
    }
    for (int y = message.Bcc.Count - 1; y >= 0; y--)
    {
        if (message.Bcc[y].Address == message.To[x].Address)
            message.Bcc.RemoveAt(y);
    }
}
for (int x = 0; x < message.CC.Count; x++)
{
    for (int y = message.CC.Count - 1; y > x; y--)
    {
        if (message.CC[y].Address == message.CC[x].Address)
            message.CC.RemoveAt(y);
    }
    for (int y = message.Bcc.Count - 1; y >= 0; y--)
    {
        if (message.Bcc[y].Address == message.CC[x].Address)
            message.Bcc.RemoveAt(y);
    }
}
for (int x = 0; x < message.Bcc.Count; x++)
{
    for (int y = message.Bcc.Count - 1; y > x; y--)
    {
        if (message.Bcc[y].Address == message.Bcc[x].Address)
            message.Bcc.RemoveAt(y);
    }
}
</code>```

Body:
I'm using "System.Net.Mail" for send email on our Intranet system in C#

The Send() method was very slow and I did not understand why.

After debugging, I've remove the BCC call : (MM is a MailMessage() and Item, a string email address) :

MM.Bcc.Add(new MailAddress(Item));

Before I comment this line, an email was taking about 30 or 40 seconds. Now, it's about 2 seconds. Why?

Is there an explication about this? I can add "To" and "CC" with no problem of performance. But not "BCC".

Body:
I had a similar problem and this drove me crazy trying to figure out what made some emails slow and others quick.

The first email sent after creating SmtpClient takes 5 seconds.  After that, reusing the same SmtpClient, it's about 0.4 seconds if done within 60 seconds of the previous one.  After that I think it releases it's connection to the pool.

However adding a CC that is a duplicate of the To address will always add an additional 5 seconds. Adding a duplicate CC twice will add 10 seconds.

I didn't check, but I assume the same would be true if duplicates are in the "TO" or "BCC" lists.

Here's the code to remove duplicates:

// check and remove duplicates
for (int x = 0; x < message.To.Count; x++)
{
    for (int y = message.To.Count - 1; y > x; y--)
    {
        if (message.To[y].Address == message.To[x].Address)
            message.To.RemoveAt(y);
    }
    for (int y = message.CC.Count - 1; y >= 0; y--)
    {
        if (message.CC[y].Address == message.To[x].Address)
            message.CC.RemoveAt(y);
    }
    for (int y = message.Bcc.Count - 1; y >= 0; y--)
    {
        if (message.Bcc[y].Address == message.To[x].Address)
            message.Bcc.RemoveAt(y);
    }
}
for (int x = 0; x < message.CC.Count; x++)
{
    for (int y = message.CC.Count - 1; y > x; y--)
    {
        if (message.CC[y].Address == message.CC[x].Address)
            message.CC.RemoveAt(y);
    }
    for (int y = message.Bcc.Count - 1; y >= 0; y--)
    {
        if (message.Bcc[y].Address == message.CC[x].Address)
            message.Bcc.RemoveAt(y);
    }
}
for (int x = 0; x < message.Bcc.Count; x++)
{
    for (int y = message.Bcc.Count - 1; y > x; y--)
    {
        if (message.Bcc[y].Address == message.Bcc[x].Address)
            message.Bcc.RemoveAt(y);
    }
}


问:
Filetype Naming Convention for Angular Classes
Angular's Style Guide lists naming conventions for common file types, such as heroes.component.ts, or heroes.service.ts, etc. But what about classes that have no decorator symbols? For example, the Heroes tutorial creates a Hero class:

```<code>export class Hero {
  id: number;
  name: string;
}
</code>```

It then names this file hero.ts. A naming convention like this seems prone to chaos in the app directory. It seems logical to create a folder named classes (in the app directory), and then add a class.ts suffix to each file, such as hero.class.ts.

However, I have not seen anyone using this convention. I've seen people use a model.ts suffix, but it's unclear whether or not this is a best practice, and it is not mentioned in the Angular Style Guide.

Can anyone shed some light on this topic? Sorry if I've missed anything. Thank you advance.

答:
There are two ways of creating packages (folders) in your application:

package by layer

package by feature

Angular prefers "package by feature" and that's why hero class remains within hero component which it belongs to. Good post about why "package by feature" is preferred way is here.

As for classes/services which are used for several components - Angular StyleGuide suggests to use core package. If it's a component which is shared - then a shared package.

Body:
Angular's Style Guide lists naming conventions for common file types, such as heroes.component.ts, or heroes.service.ts, etc. But what about classes that have no decorator symbols? For example, the Heroes tutorial creates a Hero class:

export class Hero {
  id: number;
  name: string;
}

It then names this file hero.ts. A naming convention like this seems prone to chaos in the app directory. It seems logical to create a folder named classes (in the app directory), and then add a class.ts suffix to each file, such as hero.class.ts.

However, I have not seen anyone using this convention. I've seen people use a model.ts suffix, but it's unclear whether or not this is a best practice, and it is not mentioned in the Angular Style Guide.

Can anyone shed some light on this topic? Sorry if I've missed anything. Thank you advance.


问:
date pipe angular 4 custom format with timezone (short)
I need to print timestamp custom format with timezone (short format):

```<code>{{ '2017-06-29 09:55:01.956-0400' | date:'MMM dd, y hh:mm a' }}
</code>```

Output:

Jun 29, 2017 07:25 PM

But I need to append with timezone, for example:

Jun 29, 2017 07:25 PM IST

Angular provides timezone option with 'z' and 'Z' but none gave the expected result:

```<code>'MMM dd, y hh:mm a  z' ==> Jun 29, 2017 07:25 PM India Standard Time
'MMM dd, y hh:mm a  Z' ==> Jun 29, 2017 07:25 PM GMT+5:30
</code>```

I want Jul 7, 2017, 12:27:01 AM IST.

答:
The DatePipe uses Intl to format dates. So, it's up to the system where your site is open to decide in what format the current timezone should be returned. To achieve the required behavior, I suggest you create a custom DatePipe that will return the required timezoe abbreviation. For example:

```<code>import { Pipe } from "@angular/core";
import { DatePipe } from "@angular/common";

@Pipe({
    name: "myDate",
    pure: true
})
export class MyDatePipe extends DatePipe {
    transform(value: any, pattern: string = "mediumDate"): string|null {
        let result = super.transform(value, pattern);
        result += " " + this.map[Intl.DateTimeFormat().resolvedOptions().timeZone];
        return result;
    }
    map = {
        "Asia/Calcutta": "IST"
    };
}
</code>```

But, you will need to add each possible timezone to the map object. See the Plunker sample that illustrates this approach.

Body:
I need to print timestamp custom format with timezone (short format):

{{ '2017-06-29 09:55:01.956-0400' | date:'MMM dd, y hh:mm a' }}

Output:

Jun 29, 2017 07:25 PM

But I need to append with timezone, for example:

Jun 29, 2017 07:25 PM IST

Angular provides timezone option with 'z' and 'Z' but none gave the expected result:

'MMM dd, y hh:mm a  z' ==> Jun 29, 2017 07:25 PM India Standard Time
'MMM dd, y hh:mm a  Z' ==> Jun 29, 2017 07:25 PM GMT+5:30

I want Jul 7, 2017, 12:27:01 AM IST.

Body:
The DatePipe uses Intl to format dates. So, it's up to the system where your site is open to decide in what format the current timezone should be returned. To achieve the required behavior, I suggest you create a custom DatePipe that will return the required timezoe abbreviation. For example:

import { Pipe } from "@angular/core";
import { DatePipe } from "@angular/common";

@Pipe({
    name: "myDate",
    pure: true
})
export class MyDatePipe extends DatePipe {
    transform(value: any, pattern: string = "mediumDate"): string|null {
        let result = super.transform(value, pattern);
        result += " " + this.map[Intl.DateTimeFormat().resolvedOptions().timeZone];
        return result;
    }
    map = {
        "Asia/Calcutta": "IST"
    };
}

But, you will need to add each possible timezone to the map object. See the Plunker sample that illustrates this approach.


问:
How to have Common button in 2 different activities?
I have a Button which I want to show in 2 different activities. The button action does same thing for both activities like toggling on/off feature.

Is there any good way to get same button in both activities without copying and pasting code in both activities?

答:
Delegate the action to perform into a third object</p>

```<code>public class Activity1 extends AppCompatActivity {

    private Delegate delegate = new Delegate();

    public void onCreate(...) {
        ....
        button.setOnClickListener(v -> delegate.doSomething());
    }
}

public class Activity2 extends AppCompatActivity {

    private Delegate delegate = new Delegate();

    public void onCreate(...) {
        ....
        otherButton.setOnClickListener(v -> delegate.doSomething());
    }
}

public class Delegate {

    public void doSomething() {
        ...
    }

}
</code>```

Body:
Delegate the action to perform into a third object

public class Activity1 extends AppCompatActivity {

    private Delegate delegate = new Delegate();

    public void onCreate(...) {
        ....
        button.setOnClickListener(v -> delegate.doSomething());
    }
}

public class Activity2 extends AppCompatActivity {

    private Delegate delegate = new Delegate();

    public void onCreate(...) {
        ....
        otherButton.setOnClickListener(v -> delegate.doSomething());
    }
}

public class Delegate {

    public void doSomething() {
        ...
    }

}


问:
Can not import scrypt from hashlib
I try to use import scrypt from the standard libary.

Both on my local machine (ubuntu 16.04) and the server (heroku/heroku stack) the import fails.

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'scrypt'
</code>```

On both systems openssl 1.0.2g is installed. Is this a know problem or how can I fix it?

答:
As far as I understand it, a requirement to use scrypt is that you have OpenSSL 1.1+ installed. If you have a look at the hashlib.py:

```<code>try:
    # OpenSSL's scrypt requires OpenSSL 1.1+
    from _hashlib import scrypt
except ImportError:
    pass
</code>```

you see that the import to make scrypt available for you just passes without any message if you don't have OpenSSL in the right version installed and of course you can't use it if that happens. Maybe the scrypt package from pypi (https://pypi.python.org/pypi/scrypt/) is an alternative for you?

Title: Can not import scrypt from hashlib

Body:
I try to use import scrypt from the standard libary.

Both on my local machine (ubuntu 16.04) and the server (heroku/heroku stack) the import fails.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'scrypt'

On both systems openssl 1.0.2g is installed. Is this a know problem or how can I fix it?

Body:
As far as I understand it, a requirement to use scrypt is that you have OpenSSL 1.1+ installed. If you have a look at the hashlib.py:

try:
    # OpenSSL's scrypt requires OpenSSL 1.1+
    from _hashlib import scrypt
except ImportError:
    pass

you see that the import to make scrypt available for you just passes without any message if you don't have OpenSSL in the right version installed and of course you can't use it if that happens. Maybe the scrypt package from pypi (https://pypi.python.org/pypi/scrypt/) is an alternative for you?


问:
swift 3 ViewController to TableViewController
I'm building a todo list app. So far I have a tableViewController in which i have the list of todo created and when I click on it a viewcontroller opens with the content inside. I have a navigationController linked to the tableviewcontroller, and tableviewcontroller linked to viewcontroller.
What I want to do now is create a new viewcontroller with an input inside, you insert your name and after clicking on a button it opens the tableviewcontroller with the list inside.
Is is the same way as linking tableviewcontroller to viewcontroller or is there a difference ?

[EDIT]

Here's what I've got so far :

答:
Say you want a new view controller to pop up when clicking on create button. drop another view controller on your storyboard. Connect your button to that view controller using segue and set type as Present Modally. Now when you click on the button, the new view controller will show up.

Now add a button on the new view controller, connect to code using an IBAction. In the action, call self.dismiss(animated: true, completion: nil) Now when you click on this button, your new view controller will be dismissed.

Finally, add your create new use stuff on your new view controller, and pass data back to your table view using unwind segue, which you can search on Google.

Your story board will look something like this


问:
Dividing large numbers in postgresql
I am working with numbers of 18 decimals, I have decided to save the number as a "NUMERIC (36)" in database

Now I want to present it by doing the following division

```<code>select (5032345678912345678::decimal  / power(10, 18)::decimal )::decimal(36,18)
</code>```

result
5.032345678912345700

expected result
5.032345678912345678

It works if I use a precision of 16 decimals

```<code>select (50323456789123456::decimal  / power(10, 16)::decimal )::decimal(36,16)
</code>```

result 5.0323456789123456

Any idea how to work with 18 decimals without losing information?

答:
Use a constant typed as decimal(38,18):

```<code>select 5032345678912345678::decimal / 1000000000000000000::decimal(38,18);

       ?column?
----------------------
 5.032345678912345678
(1 row)
</code>```

A constant should be a bit faster. However the same cast should work for power(10,18) as well.

Title: Dividing large numbers in postgresql

Body:
I am working with numbers of 18 decimals, I have decided to save the number as a "NUMERIC (36)" in database

Now I want to present it by doing the following division

select (5032345678912345678::decimal  / power(10, 18)::decimal )::decimal(36,18)

result
5.032345678912345700

expected result
5.032345678912345678

It works if I use a precision of 16 decimals

select (50323456789123456::decimal  / power(10, 16)::decimal )::decimal(36,16)

result 5.0323456789123456

Any idea how to work with 18 decimals without losing information?

Body:
Use a constant typed as decimal(38,18):

select 5032345678912345678::decimal / 1000000000000000000::decimal(38,18);

       ?column?
----------------------
 5.032345678912345678
(1 row)

A constant should be a bit faster. However the same cast should work for power(10,18) as well.


问:
How to write "in" query for Erlang mnesia?
I have a mnesia table, lets say employee. I need to find all employee records whose name is in EmployeeNameList = ["Erlich", "Richard", "Gilfoyle", "Dinesh"]. Is there a way to do this using mnesia:select or other function?

答:
Following the documentation of Mnesia
It can be done as follows: </p>

```<code>get_employees_by_name(NameList) ->
  MatchHead = #employee{name = '$1', _ = '_'},
  Result = '$_'
  MatchSpec = [ { MatchHead, [{'=:=', '$1', Name}], [Result]} || Name <- NameList ],
  F = fun() ->
     mnesia:select(employee, MatchSpec)
  end,
  {atomic, Result} = mnesia:transaction(F),
  Result.
</code>```

Body:
Following the documentation of Mnesia
It can be done as follows:

get_employees_by_name(NameList) ->
  MatchHead = #employee{name = '$1', _ = '_'},
  Result = '$_'
  MatchSpec = [ { MatchHead, [{'=:=', '$1', Name}], [Result]} || Name <- NameList ],
  F = fun() ->
     mnesia:select(employee, MatchSpec)
  end,
  {atomic, Result} = mnesia:transaction(F),
  Result.


问:
Google Website Translator Automatic Display Mode
I'm trying to include google website translator on my website. I want to use the automatic thing so the bar shows up if your browser language is different to the page language. Every time I select the automatic Display mode the code it gives me is for 'tabbed'. Can anybody tell me what i'm doing wrong or provide the right code?

Thanks in advance.

EDIT:

```<code><div id="google_translate_element"></div>
<script type="text/javascript">
    function googleTranslateElementInit() {
        new google.translate.TranslateElement({pageLanguage: 'en', layout:     google.translate.TranslateElement.FloatPosition.TOP_LEFT},     'google_translate_element');
    }
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</code>```

答:
```<code><div id="google_translate_element"></div>
<script type="text/javascript">
    function googleTranslateElementInit() {
      new google.translate.TranslateElement({
          pageLanguage: 'es',
          includedLanguages: 'es',
          layout: google.translate.TranslateElement.InlineLayout.SIMPLE
      }, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</code>```


问:
Angular 2 CanActivate is called twice
I am faced with a problem with route guards with Angular.

My CanActivate guard is called twice when navigating to a page that is not permitted because I'm not logged in.

I have 1 root module and provided there my CanActivate guard and other services.

Thank you in advance!

Here is my router:

```<code>const appRoutes: Routes = [
    {
        path: "",
        pathMatch: "full",
        redirectTo: "/meal-list",
    },
    {
        path: "login",
        component: LoginComponent,
    },
    {
        path: "meal-list",
        component: MealListComponent,
        canActivate: [AuthActivateGuard],
    }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});
</code>```

and guard:

```<code>@Injectable()
export class AuthActivateGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) {
    console.log("guard created");
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {
    if (!this.authService.authenticated) {
      return this.authService.checkLogged().map(res => {
        this.authService.authenticated = true;
        return true;
      }).catch(()=> {
        this.authService.authenticated = false;
        this.router.navigate(["login"]);
        return Observable.of(false);
      });
    }
    return true;
  }
}
</code>```

答:
Although this is not a solution, it is an answer:

This happens when using hash routing (useHash: true).

It may be a bug in the Angular router.

I am still investigating to see if there is a solution.

Steve

ContentLicense: CC BY-SA 4.0

Title: Angular 2 CanActivate is called twice

Body:
I am faced with a problem with route guards with Angular.

My CanActivate guard is called twice when navigating to a page that is not permitted because I'm not logged in.

I have 1 root module and provided there my CanActivate guard and other services.

Thank you in advance!

Here is my router:

const appRoutes: Routes = [
    {
        path: "",
        pathMatch: "full",
        redirectTo: "/meal-list",
    },
    {
        path: "login",
        component: LoginComponent,
    },
    {
        path: "meal-list",
        component: MealListComponent,
        canActivate: [AuthActivateGuard],
    }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, {useHash: true});

and guard:

@Injectable()
export class AuthActivateGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) {
    console.log("guard created");
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {
    if (!this.authService.authenticated) {
      return this.authService.checkLogged().map(res => {
        this.authService.authenticated = true;
        return true;
      }).catch(()=> {
        this.authService.authenticated = false;
        this.router.navigate(["login"]);
        return Observable.of(false);
      });
    }
    return true;
  }
}


问:
How to insert multiple records with the same ID into a table using DAO in MS Access
(1) I have 3 tables (A-Sched,B-Trans and C-ItemRecep) with one Lookup table called D-TransDetailRecep. Below is the relationship diagram.

(2) I am inserting values into the table fields from a form through a click button that implements the DAO below:

Public Sub RecpSchedule1()
    'Consultation ONLY
    Dim db As DAO.Database
    Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset
    Dim lngTransId As Long
    Dim lngItemRecepId As Long

```<code>Set db = CurrentDb
Set rs = db.OpenRecordset("Sched")
Set rt = db.OpenRecordset("Trans")
Set ri = db.OpenRecordset("ItemRecep")
Set rd = db.OpenRecordset("TransDetailRecep")
</code>```

lngItemRecepId = Nz(DMax("ID", "ItemRecep"), 0) + 1 'Next ItemRecep ID
   lngTransId = Nz(DMax("ID", "Trans"), 0) + 1 'Next Trans ID

```<code>    With rs
        .AddNew
        !SDate = Me.txtSchedDate
        !PatientName = Me.cmbPatientName
        !RegNo = Me.txtRegNo
        !DateOfBirth = Me.txtAge
        !Gender = Me.txtGender
        !PatientClass = Me.PatientClass
        !RecepSchedule = True
        .Update
    End With

    With rt
        .AddNew
        !ID = lngTransId
        !SchedRegNo = Me.txtRegNo
        ![Total_RecepFee] = Nz((Me.txtConsFee + Me.txtIOPFee + ![Total_RecepFee]), 0)

       .Update
    End With

    With ri
        .AddNew
        !ID = lngItemRecepId
        !ItemName = "ConsFee"
        !Price = Me.txtConsFee.Value
        !Dept = "Reception"
        .Update
    End With

    With rd
        .AddNew
        !TransID = lngTransId
        !TransID = DMax("ID", "Trans")
        !ItemRecepID = DMax("ID", "ItemRecep")
        .Update
    End With

    rs.Close
    rt.Close
    ri.Close
    rd.Close

 Set rs = Nothing
 Set rt = Nothing
 Set rd = Nothing
 Set ri = Nothing
 Set db = Nothing
</code>```

End Sub

Public Sub RecpSchedule2()

```<code>Dim db As DAO.Database
Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset
Dim lngTransId As Long
Dim lngItemRecepId As Long

Set db = CurrentDb
Set rt = db.OpenRecordset("Trans")
Set ri = db.OpenRecordset("ItemRecep")
Set rd = db.OpenRecordset("TransDetailRecep")
</code>```

lngItemRecepId = Nz(DMax("ID", "ItemRecep"), 0) + 1 'Next ItemRecep ID
   lngTransId = Nz(DMax("ID", "Trans"), 0) + 1 'Next Trans ID

```<code>    'With rt
       ' .AddNew
       ' !ID = lngTransId
        '!SchedRegNo = Me.txtRegNo
        '![Total_RecepFee] = Nz((Me.txtIOPFee + ![Total_RecepFee]), 0)
       '.Update
   ' End With

    With ri
        .AddNew
        !ID = lngItemRecepId
        !ItemName = "IOPFee"
        !Price = Me.txtIOPFee.Value
        !Dept = "Reception"
        .Update
    End With

    With rd
        .AddNew
        !TransID = lngTransId
        !TransID = DMax("ID", "Trans")
        !ItemRecepID = DMax("ID", "ItemRecep")
        .Update
    End With

    rt.Close
    ri.Close
    rd.Close

 Set rt = Nothing
 Set rd = Nothing
 Set ri = Nothing
 Set db = Nothing
</code>```

End Sub

(3) My challenge: The field for the Total_RecepFee should show 500 where the Price is 500 and show 1200 where the Price is 1200. (What I have now is that both is showing the sum of the values)

答:
The problem lies here:

```<code>rd!TransID = rt!ID
rd!ItemRecepID = ri!ID
</code>```

The rt.Update and ri.Update methods have not been run to save the recordset. But even so, .AddNew creates a new record therefore rt!ID and ri!ID are both Null.

You could try to save both rt and ri recordsets first and then retrieve the Max(ID) (since this will be the last added ID) through the DMax function. However, if multiple users have access to add data simultaneously, this could be risky (actually it would be very risky).

I would suggest why not scrapping the autonumber ID and handle it manually?

```<code>Dim lngId as Long
    lngId = DMax("ID", "Trans") + 1
    'You can now feed it to both tables
</code>```

Try the updated code below. I haven't been able to test it myself.

```<code>Public Sub RecpSchedule1()

    Dim db As DAO.Database
    Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset

    Set db = CurrentDb
    Set rs = db.OpenRecordset("Sched")
    Set rt = db.OpenRecordset("Trans")
    Set ri = db.OpenRecordset("ItemRecep")
    Set rd = db.OpenRecordset("TransDetailRecep")

        With rs
            .AddNew
            !SDate = Me.txtSchedDate
            !PatientName = Me.cmbPatientName
            !RegNo = Me.txtRegNo
            .Update
        End With

        With rt
            .AddNew
            !SchedRegNo = Me.txtRegNo
            !TDate = Me.txtSchedDate
            .Update
        End With

        With ri
            .AddNew
            !ItemName = "ConsFee"
            !Price = Me.txtConsFee.Value
            !Dept = "Reception"
            .Update
        End With

        With rd
            .AddNew
            !TransID = DMax("ID", "Trans")
            !ItemRecepID = DMax("ID", "ItemRecep")
            .Update
        End With

        rs.Close
        rt.Close
        ri.Close
        rd.Close

     Set rs = Nothing
     Set rt = Nothing
     Set rd = Nothing
     Set ri = Nothing
     Set db = Nothing
End Sub

Public Sub RecpSchedule2()

    Dim db As DAO.Database
    Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset

    Set db = CurrentDb
    Set rt = db.OpenRecordset("Trans")
    Set ri = db.OpenRecordset("ItemRecep")
    Set rd = db.OpenRecordset("TransDetailRecep")

        With ri
            .AddNew
            !ItemName = "IOP"
            !Price = Me.txtIOPFee.Value
            !Dept = "Reception"
            .Update
        End With

        With rd
            .AddNew
            !TransID = DMax("ID", "Trans")
            !ItemRecepID = DMax("ID", "ItemRecep")
            .Update
        End With

        rt.Close
        ri.Close
        rd.Close

     Set rt = Nothing
     Set rd = Nothing
     Set ri = Nothing
     Set db = Nothing
End Sub
</code>```

Update:

In order to handle the IDs manually, you need to determine the next IDs for tables Trans and ItemRecep upon entering data.

```<code>Dim lngTransId as Long
    lngTransId = Nz(DMax("ID", "Trans"),0) + 1 'Next Trans ID

Dim lngItemRecepId as Long
    lngItemRecepId = Nz(DMax("ID", "ItemRecep"),0) + 1 'Next ItemRecep ID

With rt
    .AddNew
    !ID = lngTransId
    !SchedRegNo = Me.txtRegNo
    !TDate = Me.txtSchedDate
    .Update
End With

With ri
    .AddNew
    !ID = lngItemRecepId
    !ItemName = "ConsFee"
    !Price = Me.txtConsFee.Value
    !Dept = "Reception"
    .Update
End With

With rd
    .AddNew
    !TransID = lngTransId
    !ItemRecepID = lngItemRecepId
    .Update
End With
</code>```

Body:
(1) I have 3 tables (A-Sched,B-Trans and C-ItemRecep) with one Lookup table called D-TransDetailRecep. Below is the relationship diagram.

(2) I am inserting values into the table fields from a form through a click button that implements the DAO below:

Public Sub RecpSchedule1()
    'Consultation ONLY
    Dim db As DAO.Database
    Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset
    Dim lngTransId As Long
    Dim lngItemRecepId As Long

Set db = CurrentDb
Set rs = db.OpenRecordset("Sched")
Set rt = db.OpenRecordset("Trans")
Set ri = db.OpenRecordset("ItemRecep")
Set rd = db.OpenRecordset("TransDetailRecep")

lngItemRecepId = Nz(DMax("ID", "ItemRecep"), 0) + 1 'Next ItemRecep ID
   lngTransId = Nz(DMax("ID", "Trans"), 0) + 1 'Next Trans ID

    With rs
        .AddNew
        !SDate = Me.txtSchedDate
        !PatientName = Me.cmbPatientName
        !RegNo = Me.txtRegNo
        !DateOfBirth = Me.txtAge
        !Gender = Me.txtGender
        !PatientClass = Me.PatientClass
        !RecepSchedule = True
        .Update
    End With

    With rt
        .AddNew
        !ID = lngTransId
        !SchedRegNo = Me.txtRegNo
        ![Total_RecepFee] = Nz((Me.txtConsFee + Me.txtIOPFee + ![Total_RecepFee]), 0)

       .Update
    End With

    With ri
        .AddNew
        !ID = lngItemRecepId
        !ItemName = "ConsFee"
        !Price = Me.txtConsFee.Value
        !Dept = "Reception"
        .Update
    End With

    With rd
        .AddNew
        !TransID = lngTransId
        !TransID = DMax("ID", "Trans")
        !ItemRecepID = DMax("ID", "ItemRecep")
        .Update
    End With

    rs.Close
    rt.Close
    ri.Close
    rd.Close

 Set rs = Nothing
 Set rt = Nothing
 Set rd = Nothing
 Set ri = Nothing
 Set db = Nothing

End Sub

Public Sub RecpSchedule2()

Dim db As DAO.Database
Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset
Dim lngTransId As Long
Dim lngItemRecepId As Long

Set db = CurrentDb
Set rt = db.OpenRecordset("Trans")
Set ri = db.OpenRecordset("ItemRecep")
Set rd = db.OpenRecordset("TransDetailRecep")

lngItemRecepId = Nz(DMax("ID", "ItemRecep"), 0) + 1 'Next ItemRecep ID
   lngTransId = Nz(DMax("ID", "Trans"), 0) + 1 'Next Trans ID

    'With rt
       ' .AddNew
       ' !ID = lngTransId
        '!SchedRegNo = Me.txtRegNo
        '![Total_RecepFee] = Nz((Me.txtIOPFee + ![Total_RecepFee]), 0)
       '.Update
   ' End With

    With ri
        .AddNew
        !ID = lngItemRecepId
        !ItemName = "IOPFee"
        !Price = Me.txtIOPFee.Value
        !Dept = "Reception"
        .Update
    End With

    With rd
        .AddNew
        !TransID = lngTransId
        !TransID = DMax("ID", "Trans")
        !ItemRecepID = DMax("ID", "ItemRecep")
        .Update
    End With

    rt.Close
    ri.Close
    rd.Close

 Set rt = Nothing
 Set rd = Nothing
 Set ri = Nothing
 Set db = Nothing

End Sub

(3) My challenge: The field for the Total_RecepFee should show 500 where the Price is 500 and show 1200 where the Price is 1200. (What I have now is that both is showing the sum of the values)

Body:
The problem lies here:

rd!TransID = rt!ID
rd!ItemRecepID = ri!ID

The rt.Update and ri.Update methods have not been run to save the recordset. But even so, .AddNew creates a new record therefore rt!ID and ri!ID are both Null.

You could try to save both rt and ri recordsets first and then retrieve the Max(ID) (since this will be the last added ID) through the DMax function. However, if multiple users have access to add data simultaneously, this could be risky (actually it would be very risky).

I would suggest why not scrapping the autonumber ID and handle it manually?

Dim lngId as Long
    lngId = DMax("ID", "Trans") + 1
    'You can now feed it to both tables

Try the updated code below. I haven't been able to test it myself.

Public Sub RecpSchedule1()

    Dim db As DAO.Database
    Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset

    Set db = CurrentDb
    Set rs = db.OpenRecordset("Sched")
    Set rt = db.OpenRecordset("Trans")
    Set ri = db.OpenRecordset("ItemRecep")
    Set rd = db.OpenRecordset("TransDetailRecep")

        With rs
            .AddNew
            !SDate = Me.txtSchedDate
            !PatientName = Me.cmbPatientName
            !RegNo = Me.txtRegNo
            .Update
        End With

        With rt
            .AddNew
            !SchedRegNo = Me.txtRegNo
            !TDate = Me.txtSchedDate
            .Update
        End With

        With ri
            .AddNew
            !ItemName = "ConsFee"
            !Price = Me.txtConsFee.Value
            !Dept = "Reception"
            .Update
        End With

        With rd
            .AddNew
            !TransID = DMax("ID", "Trans")
            !ItemRecepID = DMax("ID", "ItemRecep")
            .Update
        End With

        rs.Close
        rt.Close
        ri.Close
        rd.Close

     Set rs = Nothing
     Set rt = Nothing
     Set rd = Nothing
     Set ri = Nothing
     Set db = Nothing
End Sub

Public Sub RecpSchedule2()

    Dim db As DAO.Database
    Dim rs As DAO.Recordset, rt As DAO.Recordset, rd As DAO.Recordset, ri As DAO.Recordset

    Set db = CurrentDb
    Set rt = db.OpenRecordset("Trans")
    Set ri = db.OpenRecordset("ItemRecep")
    Set rd = db.OpenRecordset("TransDetailRecep")

        With ri
            .AddNew
            !ItemName = "IOP"
            !Price = Me.txtIOPFee.Value
            !Dept = "Reception"
            .Update
        End With

        With rd
            .AddNew
            !TransID = DMax("ID", "Trans")
            !ItemRecepID = DMax("ID", "ItemRecep")
            .Update
        End With

        rt.Close
        ri.Close
        rd.Close

     Set rt = Nothing
     Set rd = Nothing
     Set ri = Nothing
     Set db = Nothing
End Sub

Update:

In order to handle the IDs manually, you need to determine the next IDs for tables Trans and ItemRecep upon entering data.

Dim lngTransId as Long
    lngTransId = Nz(DMax("ID", "Trans"),0) + 1 'Next Trans ID

Dim lngItemRecepId as Long
    lngItemRecepId = Nz(DMax("ID", "ItemRecep"),0) + 1 'Next ItemRecep ID

With rt
    .AddNew
    !ID = lngTransId
    !SchedRegNo = Me.txtRegNo
    !TDate = Me.txtSchedDate
    .Update
End With

With ri
    .AddNew
    !ID = lngItemRecepId
    !ItemName = "ConsFee"
    !Price = Me.txtConsFee.Value
    !Dept = "Reception"
    .Update
End With

With rd
    .AddNew
    !TransID = lngTransId
    !ItemRecepID = lngItemRecepId
    .Update
End With


问:
Debugging bundled and versioned javascript files
I've used Bundleconfig.cs to bundle my javascript files as follows:

```<code>bundles.Add(new ScriptBundle("~/bundles/resultscripts").Include(
             "~/Scripts/spectrum.js",
              "~/Scripts/notify.js",
              "~/Scripts/spin.min.js"));
   BundleTable.EnableOptimizations = true;
</code>```

Then in my .cshtml file, I've got the following:

```<code>@Scripts.Render("~/bundles/resultscripts");
</code>```

This renders in chrome as:

```<code><script src="/bundles/resultscripts?v=3ozhz2yni5K8Is0g9QoONh_MkoivcBzooVIUD-a0Ngw1"></script>
</code>```

Then I have the following under system.web in my Web.config (not sure how much this matters):

```<code><compilation debug="true" targetFramework="4.5.2" />
</code>```

This is good because it allows bundle versioning.  However, some of my javascript doesn't seem to be firing, and when in Chrome, I can now no longer place breakpoints in my individual javascript files.  Or to be more clear, I can't find notify.js for example.  I'm guessing this is because the bundle is being minified.

If I set BundleTable.EnableOptimizations = false; my javascript files render but are no longer versioned.

I was wondering if anyone could point me in the right direction so that I can find the individual files when bundling with versions?

I checked out this: Script bundles not rendering individual files in debug, and am using the same syntax, but my files are not getting rendered individually.

答:
Could you use <code>.*</code> and see any different? </p>

```<code>bundles.Add(new ScriptBundle("~/bundles/resultscripts").Include(
   "~/Scripts/spectrum.*",
   "~/Scripts/notify.*",
   "~/Scripts/spin.*"));

BundleTable.EnableOptimizations = true;
</code>```

Body:
I've used Bundleconfig.cs to bundle my javascript files as follows:

bundles.Add(new ScriptBundle("~/bundles/resultscripts").Include(
             "~/Scripts/spectrum.js",
              "~/Scripts/notify.js",
              "~/Scripts/spin.min.js"));
   BundleTable.EnableOptimizations = true;

Then in my .cshtml file, I've got the following:

@Scripts.Render("~/bundles/resultscripts");

This renders in chrome as:

Then I have the following under system.web in my Web.config (not sure how much this matters):

<compilation debug="true" targetFramework="4.5.2" />

This is good because it allows bundle versioning.  However, some of my javascript doesn't seem to be firing, and when in Chrome, I can now no longer place breakpoints in my individual javascript files.  Or to be more clear, I can't find notify.js for example.  I'm guessing this is because the bundle is being minified.

If I set BundleTable.EnableOptimizations = false; my javascript files render but are no longer versioned.

I was wondering if anyone could point me in the right direction so that I can find the individual files when bundling with versions?

I checked out this: Script bundles not rendering individual files in debug, and am using the same syntax, but my files are not getting rendered individually.

Body:
Could you use .* and see any different?

bundles.Add(new ScriptBundle("~/bundles/resultscripts").Include(
   "~/Scripts/spectrum.*",
   "~/Scripts/notify.*",
   "~/Scripts/spin.*"));

BundleTable.EnableOptimizations = true;


问:
How to delete image from Azure Container Registry
Is there a way to delete specific tags only? I only found a way to delete the whole registry using the REST/cli-acr

Thanks

答:
As an update, today we've released a preview of several features including repository delete, Individual Azure Active Directory Logins and Webhooks.
Steve</p>