问:
Fade effect between two activities on Android
I am trying to add a fade effect when my splash screen activity finishes and/or when my main activity starts (ideally the main activity would fade in after the splash screen finishes but I am trying anything). I have tried many things involving animations and transitions, however none of them has worked so far. As you can see, I am not familiar at all with animations, and I am aware that my issue probably comes from my lack of knowledge about it. I have been reading a lot but still feel lost.

I was wondering if the fact that my SplashActivity doesn't have a layout set as a content view was affecting my results. I am only using a theme for the splash screen activity. Here is its implementation in the manifest:

```<code><activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</code>```

and the theme (initially without the 2 last items):

```<code><style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/launch_logo</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
</code>```

I also tried to add a "fade in theme" to my MainActivity:

```<code><style name="AppTheme.FadeIn" parent="AppTheme" >
    <item name="android:windowNoTitle">true</item>
    <item name="android:activityOpenEnterAnimation">@anim/fade_in</item>
</style>
</code>```

Regarding the animation, I saw that people were sometimes using:

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="1000" />
</set>
</code>```

while other times using:

```<code><?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/accelerate_interpolator"
   android:fromAlpha="0.0" android:toAlpha="1.0"
   android:duration="1000" />
</code>```

So I tried both... (optional question: what's the difference between them?)

In SplashActivity, I tried:

```<code>Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
</code>```

and

```<code>Intent intent = new Intent(this, MainActivity.class);
Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getBaseContext(), android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
startActivity(intent, bundle);
</code>```

Also tried this in MainActivity's onCreate function:

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ViewGroup mRootView = (ViewGroup) findViewById(R.id.main_layout);
Fade mFade = new Fade(IN);
// Start recording changes to the view hierarchy
TransitionManager.beginDelayedTransition(mRootView, mFade);
</code>```

and

```<code>ViewGroup mRootView = (ViewGroup) findViewById(R.id.main_layout);
mRootView.animate().alpha(0.0f); // at this point the view is totally transparent
mRootView.animate().alpha(1.0f).setDuration(2000); // here the view becomes 100% visible instantly, there is no animation
</code>```

That's the layout of the main activity:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:weightSum="16"
    android:background="@color/background"
    android:animateLayoutChanges="true"
    tools:context=".MainActivity">
    ...
</code>```

I checked that Transition animation scale was correct in my settings (I am using Android Studio's emulator for my tests). There was never a fade effect between my two activities. Please someone enlighten me.

.

.

For some reason, I have some kind of fade effect when I do this:

```<code><style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/launch_logo</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
</code>```0

I really don't understand. Of course it gets black then the fade-in effect of the main activity is working, but I don't understand why it works this way. If I delete a single line it stops working (I discovered it was working this way when I forgot to comment the second startActivity command). When I say I tried to delete a line, I also changed the order like this:

```<code><style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/launch_logo</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
</code>```1

.

.

.

.

.

I'm just posting here what I've done after failing using all the previous solutions (that I've tried each separately). I am attaching a boolean extra to the intent when I want to get a fade-in effect when opening my next activity. Then in the onCreate method of the opening activity, I have:

```<code><style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/launch_logo</item>
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
</code>```2

If someone needs help implementing this kind of solution, I can help.

答:
Add this option bundle to your startActivity method to make fade anim between two activities:

```<code>Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getContext(),
        android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
        startActivity(intent, bundle);
</code>```

There is no need to add any further code to accomplish what you asked! :)

Body:
I am trying to add a fade effect when my splash screen activity finishes and/or when my main activity starts (ideally the main activity would fade in after the splash screen finishes but I am trying anything). I have tried many things involving animations and transitions, however none of them has worked so far. As you can see, I am not familiar at all with animations, and I am aware that my issue probably comes from my lack of knowledge about it. I have been reading a lot but still feel lost.

I was wondering if the fact that my SplashActivity doesn't have a layout set as a content view was affecting my results. I am only using a theme for the splash screen activity. Here is its implementation in the manifest:

<activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

and the theme (initially without the 2 last items):

I also tried to add a "fade in theme" to my MainActivity:

Regarding the animation, I saw that people were sometimes using:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="1000" />
</set>

while other times using:

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/accelerate_interpolator"
   android:fromAlpha="0.0" android:toAlpha="1.0"
   android:duration="1000" />

So I tried both... (optional question: what's the difference between them?)

In SplashActivity, I tried:

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

and

Intent intent = new Intent(this, MainActivity.class);
Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getBaseContext(), android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
startActivity(intent, bundle);

Also tried this in MainActivity's onCreate function:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ViewGroup mRootView = (ViewGroup) findViewById(R.id.main_layout);
Fade mFade = new Fade(IN);
// Start recording changes to the view hierarchy
TransitionManager.beginDelayedTransition(mRootView, mFade);

and

ViewGroup mRootView = (ViewGroup) findViewById(R.id.main_layout);
mRootView.animate().alpha(0.0f); // at this point the view is totally transparent
mRootView.animate().alpha(1.0f).setDuration(2000); // here the view becomes 100% visible instantly, there is no animation

That's the layout of the main activity:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:weightSum="16"
    android:background="@color/background"
    android:animateLayoutChanges="true"
    tools:context=".MainActivity">
    ...

I checked that Transition animation scale was correct in my settings (I am using Android Studio's emulator for my tests). There was never a fade effect between my two activities. Please someone enlighten me.

.

.

For some reason, I have some kind of fade effect when I do this:

Intent intent = new Intent(this, MainActivity.class);
Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getBaseContext(),
                android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
startActivity(intent, bundle);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

I really don't understand. Of course it gets black then the fade-in effect of the main activity is working, but I don't understand why it works this way. If I delete a single line it stops working (I discovered it was working this way when I forgot to comment the second startActivity command). When I say I tried to delete a line, I also changed the order like this:

Intent intent = new Intent(this, MainActivity.class);
Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getBaseContext(),
                android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent, bundle);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // with or without this line, this code doesn't work.
// I must have tried pretty much all combinations without any success...

.

.

.

.

.

I'm just posting here what I've done after failing using all the previous solutions (that I've tried each separately). I am attaching a boolean extra to the intent when I want to get a fade-in effect when opening my next activity. Then in the onCreate method of the opening activity, I have:

boolean fadeEffect = getIntent().getBooleanExtra("fade_in", false);
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.login_main_layout);
if(fadeEffect) {
    mainLayout.setAlpha(0.f);
    mainLayout.animate()
              .alpha(1.f)
              .setDuration(1000)
              .start();
}

If someone needs help implementing this kind of solution, I can help.

Body:
Add this option bundle to your startActivity method to make fade anim between two activities:

Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getContext(),
        android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
        startActivity(intent, bundle);

There is no need to add any further code to accomplish what you asked! :)


来源: stackexchange

问:
Adding Spring Framework to existing JSP/EJB application
I had an existing application developed in JSP and EJB 2.1 years ago. Now i want to enhance the application with new features. Is there a way to use Spring and Hibernate frameworks within the same old application for adding new features or do i need to go for developing new application to use latest frameworks.

Thanks in advance.

答:
You can add Spring and Hibernate to your existing application (after all, they're just a bunch of jar files), although I wouldn't really recommend doing so.

First of all, EJB 2.1 and Hibernate will clash since EJB 2.1 doesn't have standard JPA and uses the old EJB query language.

For persistence, I'd suggest using one or other and not mixing them. If you have significant amount of database access code written using EJB 2.1, then avoid introducing Hibernate into your mix. It will be a mess. If you're just using JDBC, then I guess Hibernate could be a nice fit.

As for Spring, since it's a framework, it's not really trivial to just "add Spring" to your application. Spring is huge and you should ask yourself what would be the benefits. Which parts do you want to use? Just dependency injection? Abstraction layers that aren't present in EJB 2.1? Not easy.

Bottom line: introducing Spring and Hibernate to your application is doable, although it's gonna be a messy, painful and time consuming endaveour without serious considerations, especially if your application is large.

ContentLicense: CC BY-SA 2.5


问:
Merging two unevenly spaced timeseries in Python
I have two unevenly spaced timeseries:

```<code>      time    X1
1234567000 96.32
1234567005 96.01
1234567009 96.05

      time    X2
1234567001 23.88
1234567005 23.96
</code>```

I would like to merge them:

```<code>      time    X1    X2
1234567000 96.32   nan
1234567001   nan 23.88
1234567005 96.01 23.96
1234567009 96.05   nan
</code>```

How can I do so in Python? I'm open to using packages, e.g. pandas.

time is integer (It isn't a UNIX timestamp). X1 and X2 are float.

答:
Here's a super naive way to merge.  First format your two series so they are dictionaries, define a row object, and then go through each element of each series adding it's entry to the row object.</p>

```<code>from collections import defaultdict

class series_row:
    def __init__(self):
        self.x1 = 'nan'
        self.x2 = 'nan'

    def __repr__(self):
        return f"{self.x1}, {self.x2}"

series1 = {
    1234567000: 96.32,
    1234567005: 96.01,
    1234567009: 96.05,
}

series2 = {
    1234567001: 23.88,
    1234567005: 23.96
}

merged_series = defaultdict(series_row)

for k, v in series1.items():
    merged_series[k].x1 = v

for k, v in series2.items():
    merged_series[k].x2 = v

for entry in merged_series.items():
    print(entry)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two unevenly spaced timeseries:

      time    X1
1234567000 96.32
1234567005 96.01
1234567009 96.05

      time    X2
1234567001 23.88
1234567005 23.96

I would like to merge them:

      time    X1    X2
1234567000 96.32   nan
1234567001   nan 23.88
1234567005 96.01 23.96
1234567009 96.05   nan

How can I do so in Python? I'm open to using packages, e.g. pandas.

time is integer (It isn't a UNIX timestamp). X1 and X2 are float.

Body:
Here's a super naive way to merge.  First format your two series so they are dictionaries, define a row object, and then go through each element of each series adding it's entry to the row object.

from collections import defaultdict

class series_row:
    def __init__(self):
        self.x1 = 'nan'
        self.x2 = 'nan'

    def __repr__(self):
        return f"{self.x1}, {self.x2}"

series1 = {
    1234567000: 96.32,
    1234567005: 96.01,
    1234567009: 96.05,
}

series2 = {
    1234567001: 23.88,
    1234567005: 23.96
}

merged_series = defaultdict(series_row)

for k, v in series1.items():
    merged_series[k].x1 = v

for k, v in series2.items():
    merged_series[k].x2 = v

for entry in merged_series.items():
    print(entry)


问:
Bootstrap on scroll active class need to add before 100px from top
Bootstrap scroll navigation changes the active state only when it reaches top of the screen. I need it to be changed when it reaches 100px from the top.

When I click on navigation it stops before 100px which is correct but the active state doesn't change.

```<code>$(function() {
  $(document).on('click', 'a.page-scroll', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top - 50
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
   });
});
</code>```

For eg: In this demo (download link)the active state only changes if the the div goes to top. How do I make it so the active state change when it is 100px from the top.

答:
If I understand your question correctly you want to change the active state of the links in your nav when it gets to 100px from from the top, correct?
  Bootstrap's scrollspy has some javascript references that you can set to the body tag to control the offset if you look at the body tag in the example that you have given you can see that it looks like the following:

```<code><body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
</code>```

It sets the scrollspy plugin and the target.  You can also set the data-offset.  So it would look something like the following:

```<code><body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top" data-offset="100">
</code>```

You can read Bootstrap's javascript reference Here

Body:
Bootstrap scroll navigation changes the active state only when it reaches top of the screen. I need it to be changed when it reaches 100px from the top.

When I click on navigation it stops before 100px which is correct but the active state doesn't change.

$(function() {
  $(document).on('click', 'a.page-scroll', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top - 50
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
   });
});

For eg: In this demo (download link)the active state only changes if the the div goes to top. How do I make it so the active state change when it is 100px from the top.

Body:
If I understand your question correctly you want to change the active state of the links in your nav when it gets to 100px from from the top, correct?
  Bootstrap's scrollspy has some javascript references that you can set to the body tag to control the offset if you look at the body tag in the example that you have given you can see that it looks like the following:

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">

It sets the scrollspy plugin and the target.  You can also set the data-offset.  So it would look something like the following:

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top" data-offset="100">

You can read Bootstrap's javascript reference Here


问:
Disable Hover Effects on resize using jQuery
Ok so Im new to jQuery and a little confused how to achieve my goal here. The goal is whenever the browser is less than 780px wide I want to disable all hover effects. So I did a lot of research and still cant figure out a specific way that works for me, though I have come close. Below is the jQuery and HTML. So the class .allHover is what is triggering the hover effects. So I thought to remove the hover effect when the browser is less than 780px I would use a .removeClass method which would break the hover effect. The jQuery code below works, however when I resize the window to less than 780 px then refresh my browser the hover effect comes back and I dont want that. Is there something I can add to ensure the class .allHover doesnt come back when the page is less than 780px wide and the page is refreshed? Thank you in advance.

CHOOSE FROM
1000+Insert designs...

as low as $<?=($prod[1]->sale_price ?: $prod[1]->aslow_price);?>

```

答:
An example of how to accomplish this with media queries (given the hover effect is done with css.) The style will only work when screen size is <780.

```<code>@media only screen and (min-width: 780px) {
    .allHover:hover {
...
    }
}
</code>```

But if you need this to be js, you'll just need to add an else:

```<code>  function checkViewportWidth() {
    var viewportWidth = $(window).width();
     console.log(viewportWidth);
    if (viewportWidth <= 780) {
        $(".allHover").removeClass("allHover").addClass("gallery-mobile");
    }
    else{
        $(".allHover").addClass("allHover").removeClass("gallery-mobile");
    }
  }
</code>```

Body:
An example of how to accomplish this with media queries (given the hover effect is done with css.) The style will only work when screen size is <780.

@media only screen and (min-width: 780px) {
    .allHover:hover {
...
    }
}

But if you need this to be js, you'll just need to add an else:

  function checkViewportWidth() {
    var viewportWidth = $(window).width();
     console.log(viewportWidth);
    if (viewportWidth <= 780) {
        $(".allHover").removeClass("allHover").addClass("gallery-mobile");
    }
    else{
        $(".allHover").addClass("allHover").removeClass("gallery-mobile");
    }
  }


问:
Swift iOS -Can a Loop Run Faster then Date Secs generated by Date().timeIntervalSince1970
I pull some data from Firebase, add the data to a loop, then print the secs as each loop is ran. Is there a chance that the loop will run so fast that it will print the same secs twice?

For e.g. in the code below is this outcome possible?

```<code>image0__1507792099
image1__1507793000
image2__1507793001
image3__1507793001
image4__1507793002
image5__1507793002
</code>```

Can both image2 and image3 get printed with the same time stamp and can the same thing happen with image4 and image5?

```<code>var images:[String] = []
let secs = Int(Date().timeIntervalSince1970)

myRef?.observeSingleEvent(of: .value, with: {
     (snapshot) in

     if let dict = snapshot.value as? [String:Any]{

          let image0 = dict["image0"] as? String
          let image1 = dict["image1"] as? String
          let image2 = dict["image2"] as? String
          let image3 = dict["image3"] as? String
          let image4 = dict["image4"] as? String
          let image5 = dict["image5"] as? String

          self.images.append(image0)
          self.images.append(image1)
          self.images.append(image2)
          self.images.append(image3)
          self.images.append(image4)
          self.images.append(image5)

         for image in self.images{
             print("\(image)__\(self.secs)")
             let x = someConversionMethodThatReturnsAnImage(str: image)
             saveData(image: x)
         }
     }
}

fileprivate func saveData(image: UIImage){
        let imageExt = String(describing: secs).appending(".jpg")
        let fileManager = FileManager.default
        let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
        let imagePath = documentsPath.appendingPathComponent(imageExt)?.path
        let data = UIImageJPEGRepresentation(image, 0.8)
        fileManager.createFile(atPath: imagePath!, contents: data, attributes: nil)
    }
</code>```

FYI the reason I'm asking this question is because I'm using the secs as an extension to add the Firebase data to the DocumentsDirectory. Everything has been working fine but I'm not sure if there can be an overlap in time which means some of the data that is pulled and saved will be overwritten if they both have the same time stamp. I was pondering using arc4Random instead.

答:
Although you certainly can use a timestamp to make filenames unique I wouldn't do it. Even if it works right now circumstances may change down the line, making the loop run faster and causing you to lose data because you create two files during the same quanta. There's also factors such as clocks changing due to daylight savings or other adjustments. I would avoid that chance completely by using a method that is much safer: using a UUID.

A UUID is a series of values that are designed to be as unique as possible, either through an algorithm or through random means. They are much safer than a timestamp or a value generated through arc4Random and they have the additional benefit of being self-documenting in your code. When you see the UUID struct you know at a glance that you are creating a unique identifier.

Apple's UUID uses RFC 4122 version 4 which has 5.3x10^36 possible values, leaving the chances of collisons to be infinitesimal.

You can replace this line:

```<code>    let imageExt = String(describing: secs).appending(".jpg")
</code>```

with this:

```<code>    let imageExt = UUID().uuidString.appending(".jpg")
</code>```

Body:
I pull some data from Firebase, add the data to a loop, then print the secs as each loop is ran. Is there a chance that the loop will run so fast that it will print the same secs twice?

For e.g. in the code below is this outcome possible?

image0__1507792099
image1__1507793000
image2__1507793001
image3__1507793001
image4__1507793002
image5__1507793002

Can both image2 and image3 get printed with the same time stamp and can the same thing happen with image4 and image5?

var images:[String] = []
let secs = Int(Date().timeIntervalSince1970)

myRef?.observeSingleEvent(of: .value, with: {
     (snapshot) in

     if let dict = snapshot.value as? [String:Any]{

          let image0 = dict["image0"] as? String
          let image1 = dict["image1"] as? String
          let image2 = dict["image2"] as? String
          let image3 = dict["image3"] as? String
          let image4 = dict["image4"] as? String
          let image5 = dict["image5"] as? String

          self.images.append(image0)
          self.images.append(image1)
          self.images.append(image2)
          self.images.append(image3)
          self.images.append(image4)
          self.images.append(image5)

         for image in self.images{
             print("\(image)__\(self.secs)")
             let x = someConversionMethodThatReturnsAnImage(str: image)
             saveData(image: x)
         }
     }
}

fileprivate func saveData(image: UIImage){
        let imageExt = String(describing: secs).appending(".jpg")
        let fileManager = FileManager.default
        let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
        let imagePath = documentsPath.appendingPathComponent(imageExt)?.path
        let data = UIImageJPEGRepresentation(image, 0.8)
        fileManager.createFile(atPath: imagePath!, contents: data, attributes: nil)
    }

FYI the reason I'm asking this question is because I'm using the secs as an extension to add the Firebase data to the DocumentsDirectory. Everything has been working fine but I'm not sure if there can be an overlap in time which means some of the data that is pulled and saved will be overwritten if they both have the same time stamp. I was pondering using arc4Random instead.

Body:
Although you certainly can use a timestamp to make filenames unique I wouldn't do it. Even if it works right now circumstances may change down the line, making the loop run faster and causing you to lose data because you create two files during the same quanta. There's also factors such as clocks changing due to daylight savings or other adjustments. I would avoid that chance completely by using a method that is much safer: using a UUID.

A UUID is a series of values that are designed to be as unique as possible, either through an algorithm or through random means. They are much safer than a timestamp or a value generated through arc4Random and they have the additional benefit of being self-documenting in your code. When you see the UUID struct you know at a glance that you are creating a unique identifier.

Apple's UUID uses RFC 4122 version 4 which has 5.3x10^36 possible values, leaving the chances of collisons to be infinitesimal.

You can replace this line:

    let imageExt = String(describing: secs).appending(".jpg")

with this:

    let imageExt = UUID().uuidString.appending(".jpg")


问:
Can I check which database is running configuration and content for a WSS 3.0 site?
The problem is I have full access to the server where the Sharepoint site is hosted etc, however all i've ever done is maintained the site. I didn't set it up.

There is now an issue where Sharepoint can't connect to the Config or Content databases. I don't know which of our servers run these, so is there anyway I can find out, maybe from a config file or anything which server/database I need to check.

Other websites on the web server are still running fine, I know the database isn't on that same server because i've checked.

Any ideas?

答:
Check out the Event Viewer Log. There would be an entry similar like this:</p>

```<code>Event Type: Error
Event Source: Windows SharePoint Services 3
Event Category: Database
Event ID: 3760
Date:  4/16/2009
Time:  11:51:07 AM
User:  N/A
Computer: IMIAPP03
Description:
SQL database  **'STS_Config'** on SQL Server instance 'np:\\.\pipe\MSSQL$Microsoft##SSEE\sql\query' not found. Additional error  information from SQL Server is included below.

Cannot open database "STS_Config" requested by the login. The login failed.
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
</code>```

Body:
Check out the Event Viewer Log. There would be an entry similar like this:

Event Type: Error
Event Source: Windows SharePoint Services 3
Event Category: Database
Event ID: 3760
Date:  4/16/2009
Time:  11:51:07 AM
User:  N/A
Computer: IMIAPP03
Description:
SQL database  **'STS_Config'** on SQL Server instance 'np:\\.\pipe\MSSQL$Microsoft##SSEE\sql\query' not found. Additional error  information from SQL Server is included below.

Cannot open database "STS_Config" requested by the login. The login failed.
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.


问:
How to use custom domain on Heroku with Parse Server?
A Parse Server is hosted on Heroku at myapp.herokuapps.com.

The Heroku app has a custom domain example.com. The domain has the CNAME record myapp.herokuapps.com.

Connecting the Parse iOS SDK works for the endpoints:

```<code>https://myapp.herokuapps.com/parse
http://myapp.herokuapps.com/parse
http://example.com/parse
</code>```

But it does not work for

```<code>https://example.com/parse
</code>```

The Xcode console shows the error:

```<code>An SSL error has occurred and a secure connection to the server cannot be made. (Code: 100, Version: ...)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9838)
</code>```

Why isn't it working?

答: You have to buy an SSL cert for the domain, which Heroku upcharges like crazy. It's gonna be like $200 / mo. or something ridiculous, but you really should have one if you're going to have a production app.</p>

Body:
A Parse Server is hosted on Heroku at myapp.herokuapps.com.

The Heroku app has a custom domain example.com. The domain has the CNAME record myapp.herokuapps.com.

Connecting the Parse iOS SDK works for the endpoints:

https://myapp.herokuapps.com/parse
http://myapp.herokuapps.com/parse
http://example.com/parse

But it does not work for

https://example.com/parse

The Xcode console shows the error:

An SSL error has occurred and a secure connection to the server cannot be made. (Code: 100, Version: ...)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9838)

Why isn't it working?


问:
Hovered element to overflow out from an overflow:hidden element css
I have made a fiddle for reference: http://jsfiddle.net/kLFn9/

The overflow:hidden in question is highlighted.

Basically, i'm using :hover:after to show a tool tip. but the parent element has overflow: hidden on it. How can i force the element hovered to escape the parent element?

Relevant CSS:

div {
    width:500px;
    height:200px;
    background:red;
    margin: 50px;
    overflow: hidden; /* this rule */
}

span:hover:after {
    content: attr(data-name);
    color: black;
    position: absolute;
    top: -150px;;
    left: 0;
}
```

答:
You can use margin-top and padding-top.

padding-top will extend your parent area, but a negative margin-top will keep it in the expected position.

It will look like you're escaping the overflow, but in fact you're not.

div {
    width:500px;
    height:200px;
    background:red;
    margin: 50px;
    overflow: hidden; /* this rule */

    background-clip: content-box; /*use this to constrain the background color within the content-box and do not paint the padding */
    padding-top: 200px; /* space required to display the tooltip */
    margin-top: -150px; /*200px - 50px of the original margin*/
}

span {
 background: blue;
 color: white;
 position: relative;
 top:100px;
 display:block;
 width: 100px;
 margin: auto;
}

span:hover:after {
    content: attr(data-name);
    color: black;
    position: absolute;
    top: -150px;;
    left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<span data-name="here">hover</span>
</div></code>```

This may introduce pointer events problems, but you can fix them using pointer-events then.

Body:
You can use margin-top and padding-top.

padding-top will extend your parent area, but a negative margin-top will keep it in the expected position.

It will look like you're escaping the overflow, but in fact you're not.

div {
    width:500px;
    height:200px;
    background:red;
    margin: 50px;
    overflow: hidden; /* this rule */

    background-clip: content-box; /*use this to constrain the background color within the content-box and do not paint the padding */
    padding-top: 200px; /* space required to display the tooltip */
    margin-top: -150px; /*200px - 50px of the original margin*/
}

span {
 background: blue;
 color: white;
 position: relative;
 top:100px;
 display:block;
 width: 100px;
 margin: auto;
}

span:hover:after {
    content: attr(data-name);
    color: black;
    position: absolute;
    top: -150px;;
    left: 0;
}

<div>
<span data-name="here">hover</span>
</div>

This may introduce pointer events problems, but you can fix them using pointer-events then.


问:
How to remove node in D3 force layout?
I have a simple D3 simulation that looks like this

When I click the 'remove 1 and 4' button I want to remove nodes 1 and 4 from the simulation.  The result, however, is the following:

Visually it seems to have removed 3 and 4 (not 1 and 4).

My code is below.  Any ideas what I need to do to make this work correctly?

I'm assuming I've fundamentally misunderstood how updating nodes works in d3.  Any help appreciated.

<!DOCTYPE html>
<meta charset="utf-8">

<button>remove 1 and 4</button>
```

答:
You can solve your problem by adding a "key" function to the .data call inside the refresh function: nodeElement = nodeElement.data(nodesData, function(d){ return d.name });.

The problem you saw is not specific to updating nodes. Ordinarily, selections work based off of index of the data array. So if first D3 had [a,b,c,d] and now it has [a,d], it's going to take the first two elements ([a,b]) unless you tell it the key that defines each item in the array. That's what the function above does.

For more see https://github.com/d3/d3-selection/blob/master/README.md#selection_data

Title: How to remove node in D3 force layout?


问:
Angular 2 — Error occured when executing command: lite-server
I have this machine that I install Zsh and OhMyZsh and then I uninstalled them.

Now when I run "npm start" on the Angular 2 Quick Starter template it give me back this error:

```<code>Error occured when executing command: lite-server
 Error: spawn /usr/bin/zsh ENOENT
     at exports._errnoException (util.js:1022:11)
     at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
     at onErrorNT (internal/child_process.js:359:16)
     at _combinedTickCallback (internal/process/next_tick.js:74:11)
     at process._tickCallback (internal/process/next_tick.js:98:9)
     at Module.runMain (module.js:606:11)
     at run (bootstrap_node.js:394:7)
     at startup (bootstrap_node.js:149:9)
     at bootstrap_node.js:509:3
 Error occured when executing command: lite-server
 Error: spawn /usr/bin/zsh ENOENT
     at exports._errnoException (util.js:1022:11)
     at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
     at onErrorNT (internal/child_process.js:359:16)
     at _combinedTickCallback (internal/process/next_tick.js:74:11)
     at process._tickCallback (internal/process/next_tick.js:98:9)
     at Module.runMain (module.js:606:11)
     at run (bootstrap_node.js:394:7)
     at startup (bootstrap_node.js:149:9)
     at bootstrap_node.js:509:3
[1] lite-server exited with code -2

npm ERR! Linux 4.4.0-59-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "start"
npm ERR! node v6.9.4
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! angular-quickstart@1.0.0 start: `tsc && concurrently "tsc -w" "lite-server" `
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the angular-quickstart@1.0.0 start script 'tsc && concurrently "tsc -w" "lite-server" '.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the angular-quickstart package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     tsc && concurrently "tsc -w" "lite-server"
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs angular-quickstart
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls angular-quickstart
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/hos4m/Workspace/angular2-spotify/npm-debug.log
</code>```

From that second line of the errors stack, I can see that there is a problem with Zsh but I couldn't figure out how to solve this.

Thanks.

答:
Try

Open 2 instances of cmd at your quickstart dir:

Window 1#
npm run build: watch

then....

window 2#
npm run serve

It will open browser window and run the application

AngularJS2 npm start Error message

Body:
I have this machine that I install Zsh and OhMyZsh and then I uninstalled them.

Now when I run "npm start" on the Angular 2 Quick Starter template it give me back this error:

Error occured when executing command: lite-server
 Error: spawn /usr/bin/zsh ENOENT
     at exports._errnoException (util.js:1022:11)
     at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
     at onErrorNT (internal/child_process.js:359:16)
     at _combinedTickCallback (internal/process/next_tick.js:74:11)
     at process._tickCallback (internal/process/next_tick.js:98:9)
     at Module.runMain (module.js:606:11)
     at run (bootstrap_node.js:394:7)
     at startup (bootstrap_node.js:149:9)
     at bootstrap_node.js:509:3
 Error occured when executing command: lite-server
 Error: spawn /usr/bin/zsh ENOENT
     at exports._errnoException (util.js:1022:11)
     at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
     at onErrorNT (internal/child_process.js:359:16)
     at _combinedTickCallback (internal/process/next_tick.js:74:11)
     at process._tickCallback (internal/process/next_tick.js:98:9)
     at Module.runMain (module.js:606:11)
     at run (bootstrap_node.js:394:7)
     at startup (bootstrap_node.js:149:9)
     at bootstrap_node.js:509:3
[1] lite-server exited with code -2

npm ERR! Linux 4.4.0-59-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "start"
npm ERR! node v6.9.4
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! angular-quickstart@1.0.0 start: `tsc && concurrently "tsc -w" "lite-server" `
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the angular-quickstart@1.0.0 start script 'tsc && concurrently "tsc -w" "lite-server" '.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the angular-quickstart package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     tsc && concurrently "tsc -w" "lite-server"
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs angular-quickstart
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls angular-quickstart
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/hos4m/Workspace/angular2-spotify/npm-debug.log

From that second line of the errors stack, I can see that there is a problem with Zsh but I couldn't figure out how to solve this.

Thanks.


问:
HttpConfiguration missing assembly
I am building a site using MVC4. I couldn't even begin that I am having a strange error. This is my code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MyProject
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
</code>```

The error message: The type or name of the assembly 'HttpConfiguration' does not exist in the namespace 'System.Web.Http' (are you missing a using directive or an assembly reference?)

It also doesn't recognize the readonly field RouteParameter. It occurs to me that it may have something to do with the version, my System.Web dll is version 4.0.0.0.

Another additional piece of information is that when I type "using System.Web.   ", Intellisense DOES recognize the .Http dll

HOWEVER, in the code, it does not recognize any of its parameters.

答: when you updated and reinstalled all the AspNet packages from Nuget, and seems there were no appropriate solution - restart of Visual Studio saved me.</p>

Title: HttpConfiguration missing assembly

Body:
I am building a site using MVC4. I couldn't even begin that I am having a strange error. This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MyProject
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

The error message: The type or name of the assembly 'HttpConfiguration' does not exist in the namespace 'System.Web.Http' (are you missing a using directive or an assembly reference?)

It also doesn't recognize the readonly field RouteParameter. It occurs to me that it may have something to do with the version, my System.Web dll is version 4.0.0.0.

Another additional piece of information is that when I type "using System.Web.   ", Intellisense DOES recognize the .Http dll

HOWEVER, in the code, it does not recognize any of its parameters.


问:
Angular4 router, Lazy loaded module child routes, named router outlets
I have a wierd question. I need to setup secondary router outlets on the root routing elements of my lazy loaded modules, which have URL bases setup in the app routing module. The explanation seems a bit hard, but I am going to try to explain this.

My app routing has this

```<code>{
     path: 'shop',
     loadChildren: 'app/shop/shop.module#ShopModule',
     canActivate: [AuthGuardService]
},
</code>```

this means that all of the shop routes should begin with

/shop

Now In the shop module I need to have the main content appear in a secondary router-outlet called "ShopContent". For this I have setup 2 test routes, one of which works for me.

The shop tool routing is as follows.

```<code>const routes: Routes = [
    {
        path: '',
        component: ShopComponent,
        children: [
            {
                path: 'overview',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            },
            {
                path: 'products',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            }
        ]
    },
    {
        path: 'test',
        component: ShopComponent,
        children: [
            {
                path: 'overview',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            },
            {
                path: 'products',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            }
        ]
    }
];
</code>```

as you can see, the empty '' route and 'test' route both have identical children. I also have the router outlet setup.

```<code><router-outlet name="ShopContent"></router-outlet>
</code>```

What seems to be my officer problem?

I need to have the "/shop/overview" route open the ShopMarketingComponent in my secondary outlet, yet this routerLink gives me an undefined route error

```<code>[routerLink]="['/shop', {outlets: {ShopContent: ['overview']}}]"
</code>```

Yet this one works completely fine

```<code>[routerLink]="['/shop/test', {outlets: {ShopContent: ['overview']}}]"
</code>```

My question would be, why do I have to put an extra URL segment ( '/test' ) into the mix, so that I can have secondary router outlets? What in gods name am I doing wrong here?

答:
Are all of the lazy loaded routes displayed in the secondary outlet? If so, you could try adding the outlet to the lazy loaded route configuration:</p>

```<code>{
     path: 'management',
     loadChildren: 'app/management-tool/managementtool.module#ManagementToolModule',
     canActivate: [AuthGuardService],
     outlet: 'managementtoolcontent'
},
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a wierd question. I need to setup secondary router outlets on the root routing elements of my lazy loaded modules, which have URL bases setup in the app routing module. The explanation seems a bit hard, but I am going to try to explain this.

My app routing has this

{
     path: 'shop',
     loadChildren: 'app/shop/shop.module#ShopModule',
     canActivate: [AuthGuardService]
},

this means that all of the shop routes should begin with

/shop

Now In the shop module I need to have the main content appear in a secondary router-outlet called "ShopContent". For this I have setup 2 test routes, one of which works for me.

The shop tool routing is as follows.

const routes: Routes = [
    {
        path: '',
        component: ShopComponent,
        children: [
            {
                path: 'overview',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            },
            {
                path: 'products',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            }
        ]
    },
    {
        path: 'test',
        component: ShopComponent,
        children: [
            {
                path: 'overview',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            },
            {
                path: 'products',
                component: ShopMarketingComponent,
                outlet: 'ShopContent'
            }
        ]
    }
];

as you can see, the empty '' route and 'test' route both have identical children. I also have the router outlet setup.

<router-outlet name="ShopContent"></router-outlet>

What seems to be my officer problem?

I need to have the "/shop/overview" route open the ShopMarketingComponent in my secondary outlet, yet this routerLink gives me an undefined route error

[routerLink]="['/shop', {outlets: {ShopContent: ['overview']}}]"

Yet this one works completely fine

[routerLink]="['/shop/test', {outlets: {ShopContent: ['overview']}}]"

My question would be, why do I have to put an extra URL segment ( '/test' ) into the mix, so that I can have secondary router outlets? What in gods name am I doing wrong here?

Body:
Are all of the lazy loaded routes displayed in the secondary outlet? If so, you could try adding the outlet to the lazy loaded route configuration:

{
     path: 'management',
     loadChildren: 'app/management-tool/managementtool.module#ManagementToolModule',
     canActivate: [AuthGuardService],
     outlet: 'managementtoolcontent'
},


问:
Converting String value to Float - using textbox
I'm serializing object to json using Newtonsoft.
One of the fields that are supposed to be filled is a field containing a numeric value - a float exactly. When I was creating a car object in my project, I used float in my constructor. Like this:

```<code> public class brakes
    {
        public float park_brake { get; set; }
        public float work_brake { get; set; }
        public float discrepancy { get; set; }
    }
</code>```

User will fill the textBox which is a string but it is supposed to be a float. Is there a way to convert it? Found something like this but it's not working

```<code>Car.tires.front_value_mm = (float)Convert.ToDouble(textBox.Text);
</code>```

答:
I don't think that using float.Parse() makes any difference. Try this:</p>

```<code>Car.tires.front_value_mm = (float)Convert.ToDouble(textBox.Text, new NumberFormatInfo() {  NumberDecimalSeparator = "," });
</code>```

Body:
I'm serializing object to json using Newtonsoft.
One of the fields that are supposed to be filled is a field containing a numeric value - a float exactly. When I was creating a car object in my project, I used float in my constructor. Like this:

 public class brakes
    {
        public float park_brake { get; set; }
        public float work_brake { get; set; }
        public float discrepancy { get; set; }
    }

User will fill the textBox which is a string but it is supposed to be a float. Is there a way to convert it? Found something like this but it's not working

Car.tires.front_value_mm = (float)Convert.ToDouble(textBox.Text);

Body:
I don't think that using float.Parse() makes any difference. Try this:

Car.tires.front_value_mm = (float)Convert.ToDouble(textBox.Text, new NumberFormatInfo() {  NumberDecimalSeparator = "," });


问:
JS class child returns undefined while accessing parent constructor
I am getting undefined value while calling rnd.winner() in child class. This should return the name of player from parent like JOHN. Calling test function from child returns correct value of win() from parent. Calling super.constructor.name as return status in child returns parents class name -> player Now why is that?

class player {
  constructor(name) {
    this.name = name;
    this.win = 0;
    this.loss = 0;
  };
  win() {
    return this.win;
  };
  loss() {
    return this.loss;
  };
};

class scoreBoard extends player {
  constructor(round) {
    super();
    this.round = round;
    this.emblem = 0;
  };
  add() {
    return this.round.push([...this.round].pop() + 1);
  }
  winner() {
    return super.name;
  };
  loser() {
    return super.constructor.name;
  };
  emblem() {
    return this.emblem;
  };
  test() {
    return super.win();
  };
};
let plr = new player("JOHN"),
  rnd = new scoreBoard([0]);
console.log(plr.name, rnd.winner(), rnd.test());```

答:
Calling super.constructor.name as return status in child returns parents class name (player). Now why is that?

Because that's what super does. It does not take the own constructor property, but the constructor property on the object that you inherit from. For scoreBoard.prototype methods, that's the player.prototype object, and its .constructor.name is "player".

There is no reason to use super at all, unless you are overwriting an inherited method (or the constructor). This means not to use super with plain data properties ever. They always exist on your current instance. Use this.… instead.

I am getting undefined value while calling rnd.winner() in child class. This should return the name of player from parent like JOHN.

That's because .name was not initialised, as your child class did not pass an argument through to the parent constructor in super(). In fact, your rnd doesn't know about the plr instance at all.

In any case, inheritance seems to be the wrong tool to describe the relation between a player and a scoreboard. Use composition instead - e.g. the scoreboard holding an array of player objects to display.


问:
Displaying PDF from base64 string with Spring/Java
I have a PDF saved as a base 64 CLOB in a database.

As a functional test, I'm just trying to get it to display in my browser. I made a new endpoint in my controller and just put the base64 String into the controller, without even getting the PDF from the database, that looks like this:

```<code>@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
public void makePDF(HttpServletResponse response) throws Exception {
    String value = "R04jArrrw45jNH6bV02="; //<--This is longer, but I shortened it for this question
    byte[] imageByte = value.getBytes();
    response.setContentType("application/pdf");
    response.setContentLength(imageBytes.length);
    response.getOutputStream().write(imageBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Whenever I hit the endpoint, I get a Failed to load PDF document message. I can't figure out why.

I'm pretty new to this, so I'm having trouble figuring out what my next steps are. How do I get the PDF to display in the web browser?

 EDIT

I was able to get this working, by using modifying my method to the following:

```<code>@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
public void makePDF(HttpServletResponse response) throws Exception {
    try {
      String value = "R04jArrrw45jNH6bV02="; //<--This is longer, but I shortened it for this question
      byte[] image = Base64.decodeBase64(value.getBytes());

      Document document = new Document();
      document.setPageSize(PageSize.LETTER);
      PdfWriter.getInstance(document, response.getOutputStream());

      Image labelImage = Image.getInstance(image);
      labelImage.setAlignment(Image.TOP);
      labelImage.scalePercent(new Float("35"));

      document.open();
      document.add(labelImage);

      response.setContentType("application/pdf");
      response.setContentLength(imageBytes.length);
      response.getOutputStream().write(image);

      document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
}
</code>```

Trying to understand exactly what I'm doing here, and why it worked. Obviously has something to do with Base64 decoding, and using the Document object.

答:
Stack Overflow post Blob vs Clob and why you should not store binary data in Clobs

PDF has a general text-based structure. However, PDF files can contain non-ASCII ("binary") data and should always be considered binary files, - sorry unable to find a source of truth link for this.

There is potential for a lossy encoding of data, and decoding encoded Base-64 in that case.

Decode using Base64 before you stream it out

```<code>Base64.decode(base64String, Base64.NO_WRAP)
</code>```

Body:
I have a PDF saved as a base 64 CLOB in a database.

As a functional test, I'm just trying to get it to display in my browser. I made a new endpoint in my controller and just put the base64 String into the controller, without even getting the PDF from the database, that looks like this:

@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
public void makePDF(HttpServletResponse response) throws Exception {
    String value = "R04jArrrw45jNH6bV02="; //<--This is longer, but I shortened it for this question
    byte[] imageByte = value.getBytes();
    response.setContentType("application/pdf");
    response.setContentLength(imageBytes.length);
    response.getOutputStream().write(imageBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Whenever I hit the endpoint, I get a Failed to load PDF document message. I can't figure out why.

I'm pretty new to this, so I'm having trouble figuring out what my next steps are. How do I get the PDF to display in the web browser?

 EDIT

I was able to get this working, by using modifying my method to the following:

@RequestMapping(value = "/output.pdf", method = RequestMethod.GET, produces = "application/pdf")
public void makePDF(HttpServletResponse response) throws Exception {
    try {
      String value = "R04jArrrw45jNH6bV02="; //<--This is longer, but I shortened it for this question
      byte[] image = Base64.decodeBase64(value.getBytes());

      Document document = new Document();
      document.setPageSize(PageSize.LETTER);
      PdfWriter.getInstance(document, response.getOutputStream());

      Image labelImage = Image.getInstance(image);
      labelImage.setAlignment(Image.TOP);
      labelImage.scalePercent(new Float("35"));

      document.open();
      document.add(labelImage);

      response.setContentType("application/pdf");
      response.setContentLength(imageBytes.length);
      response.getOutputStream().write(image);

      document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
}

Trying to understand exactly what I'm doing here, and why it worked. Obviously has something to do with Base64 decoding, and using the Document object.

Body:
Stack Overflow post Blob vs Clob and why you should not store binary data in Clobs

PDF has a general text-based structure. However, PDF files can contain non-ASCII ("binary") data and should always be considered binary files, - sorry unable to find a source of truth link for this.

There is potential for a lossy encoding of data, and decoding encoded Base-64 in that case.

Decode using Base64 before you stream it out

Base64.decode(base64String, Base64.NO_WRAP)


问:
Website doesn't find stylesheet in Safari/IE
No idea why this is happening... this is what it looks like in firefox:

And this is what it looks like in Safari:

A quick inspection with firebug for safari shows that its not picking up any style sheets except transmenu.css (for the menu - which isnt' even being used). I can't find ANY reason why this would happen.

Any ideas?

website: http://tradartsteam.co.uk

Thanks

答:
Link to your stylesheet before your scripts (even better - put your scripts at the bottom of the page.)

I'm not sure exactly what the problem is but you do have an awful lot of javascript and the errors look to be interfering with the page load.


问:
How to handle exceptions in async void methods with NUnit
I have some tests that run through the workflow of my WPF program. I do the normal MVVM approach which is binding buttons on the view to commands on the view model, which then handles the event. The way my tests test my workflow is then by directly executing the commands on the view model. This roughly translates to look something like:

```<code>[Test]
public void Test()
{
    var vm = new ViewModel();
    vm.AcceptCommand.Execute();
    Assert.IsTrue(stuff);
}
</code>```

All of this works well, except for the fact that the code in the viewmodel that handles the command ends up being an async void method since this just becomes an event handler. If an exception gets thrown here, nunit does not show a failing test because it doesn't "see" this exception in the background thread.

My question is: is there a way to get NUnit to handle these background exceptions?

答:
There is a separate method in NUnit to verify exceptions in async methods:

```<code>var exception = Assert.ThrowsAsync<NotImplementedException>(() => vm.AcceptCommand.Execute());
</code>```

or vice versa:

```<code>Assert.DoesNotThrowAsync(() => vm.AcceptCommand.Execute());
</code>```

Body:
I have some tests that run through the workflow of my WPF program. I do the normal MVVM approach which is binding buttons on the view to commands on the view model, which then handles the event. The way my tests test my workflow is then by directly executing the commands on the view model. This roughly translates to look something like:

[Test]
public void Test()
{
    var vm = new ViewModel();
    vm.AcceptCommand.Execute();
    Assert.IsTrue(stuff);
}

All of this works well, except for the fact that the code in the viewmodel that handles the command ends up being an async void method since this just becomes an event handler. If an exception gets thrown here, nunit does not show a failing test because it doesn't "see" this exception in the background thread.

My question is: is there a way to get NUnit to handle these background exceptions?

Body:
There is a separate method in NUnit to verify exceptions in async methods:

var exception = Assert.ThrowsAsync<NotImplementedException>(() => vm.AcceptCommand.Execute());

or vice versa:

Assert.DoesNotThrowAsync(() => vm.AcceptCommand.Execute());


问:
How to rotate the Image along y-axis?
The code i tried is rotating the image but i want to rotate the image vertically like rotating earth at 360 degrees with 0 inclination

The code i tried is

```<code> public class MainClass extends JPanel {
    static ImageIcon icon = null;
    static RotatedIcon rotate = null;
    static JLabel label = null;

    public MainClass() {
        try {
            BufferedImage wPic = ImageIO.read(this.getClass().getResource(
                    "globe.png"));
            icon = new ImageIcon(wPic);
            rotate = new RotatedIcon(icon, 180);

            label = new JLabel(rotate);

        } catch (Exception e) {
            System.out.println("raise exception");
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        label.repaint();
    }

    public static void main(String[] args) throws IOException,
            InterruptedException {
        MainClass mainClass = new MainClass();
        JFrame frame = new JFrame();
        mainClass.add(label);
        frame.add(mainClass);
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        ActionListener taskPerformer = new ActionListener() {
            int degree = 360;

            public void actionPerformed(ActionEvent evt) {

                rotate.setDegrees(degree);
                degree = degree + 90;
                label.repaint();

                mainClass.repaint();

            }
        };
        Timer timer = new Timer(1000, taskPerformer);
        // timer.setRepeats(false);
        timer.start();
        Thread.sleep(5000);
    }
}
</code>```

https://tips4java.wordpress.com/2009/04/06/rotated-icon/ Reference link of the RotatedIcon class i used.
As Explained am able to rotate image but that is not vertically.

答:
If you only have a flat 2D image of the world then then best you might be able to do is use the Marquee Panel.

The Marquee Panel will allow you to scroll the image and you can set it to wrap when it reaches the end. You won't get a 3D effect buy you will scroll around the world with a flat 2D image.

Title: How to rotate the Image along y-axis?

Body:
The code i tried is rotating the image but i want to rotate the image vertically like rotating earth at 360 degrees with 0 inclination

The code i tried is

 public class MainClass extends JPanel {
    static ImageIcon icon = null;
    static RotatedIcon rotate = null;
    static JLabel label = null;

    public MainClass() {
        try {
            BufferedImage wPic = ImageIO.read(this.getClass().getResource(
                    "globe.png"));
            icon = new ImageIcon(wPic);
            rotate = new RotatedIcon(icon, 180);

            label = new JLabel(rotate);

        } catch (Exception e) {
            System.out.println("raise exception");
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        label.repaint();
    }

    public static void main(String[] args) throws IOException,
            InterruptedException {
        MainClass mainClass = new MainClass();
        JFrame frame = new JFrame();
        mainClass.add(label);
        frame.add(mainClass);
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        ActionListener taskPerformer = new ActionListener() {
            int degree = 360;

            public void actionPerformed(ActionEvent evt) {

                rotate.setDegrees(degree);
                degree = degree + 90;
                label.repaint();

                mainClass.repaint();

            }
        };
        Timer timer = new Timer(1000, taskPerformer);
        // timer.setRepeats(false);
        timer.start();
        Thread.sleep(5000);
    }
}

https://tips4java.wordpress.com/2009/04/06/rotated-icon/ Reference link of the RotatedIcon class i used.
As Explained am able to rotate image but that is not vertically.


问:
oracle sql multiple condition for a column
I'm having real trouble here with oracle sql queries, I'm new to this so thanks in advance.

I'm joining two queries with multiple columns, I have 3 conditions for column DUE_DATE_STATUS I just don't know how to have 3 conditions in the Select Statments

For example

```<code>SELECT t1, t2, t3,

FROM B2

UNION

SELECT t1, t2, t3,

FROM B2
</code>```

and I have this column I want to add, that tells if each row is late, ontime or null..

```<code>SELECT 'LATE_SUBMITTAL' as DUE_DATE_STATUS

from C2

WHERE

END_DATE <= START_DATE
</code>```

How do I add all three conditions to the DUE_DATE_STATUS?

答:
As a guess, you might be wanting to use a CASE expression.

```<code> SELECT t1
      , t2
      , t3
      , CASE WHEN end_date <= start_date THEN 'LATE'
             WHEN end_date >  start_date THEN 'ONTIME'
             ELSE NULL
        END AS due_date_status
   FROM B2
</code>```

This is just a guess. From the question, it's not clear what we are trying to achieve... an example of the result we want to return.

And we don't know what's up with the table named C2 in the second query, when the first table references a table named B2. I feel like we're missing a whole lot of information about the problem we are trying to solve.

Body:
I'm having real trouble here with oracle sql queries, I'm new to this so thanks in advance.

I'm joining two queries with multiple columns, I have 3 conditions for column DUE_DATE_STATUS I just don't know how to have 3 conditions in the Select Statments

For example

SELECT t1, t2, t3,

FROM B2

UNION

SELECT t1, t2, t3,

FROM B2

and I have this column I want to add, that tells if each row is late, ontime or null..

SELECT 'LATE_SUBMITTAL' as DUE_DATE_STATUS

from C2

WHERE

END_DATE <= START_DATE

How do I add all three conditions to the DUE_DATE_STATUS?

Body:
As a guess, you might be wanting to use a CASE expression.

 SELECT t1
      , t2
      , t3
      , CASE WHEN end_date <= start_date THEN 'LATE'
             WHEN end_date >  start_date THEN 'ONTIME'
             ELSE NULL
        END AS due_date_status
   FROM B2

This is just a guess. From the question, it's not clear what we are trying to achieve... an example of the result we want to return.

And we don't know what's up with the table named C2 in the second query, when the first table references a table named B2. I feel like we're missing a whole lot of information about the problem we are trying to solve.


问:
SUM values - output error when de sum is equal to zero
With the following query I get the sum of the sales value per year for each country in the database

```<code>   $country_parameter = $_REQUEST['parameter'];

   $query = "SELECT YEAR(sl.year_sales) AS year,
                       COALESCE(SUM(sl.value_sales),0) AS value
                       FROM sales sl LEFT JOIN country co
                       ON sl.id_country = co.id_country
                       WHERE parameter = ?
                       GROUP BY year
                       ORDER BY year";

    if($statement = $conexao->prepare($query)){
        $statement->bind_param("i", $country_parameter );
        $statement->execute();

        $result = $statement ->get_result();

        while($data = $result->fetch_assoc()){
            $output[] = $data;
        }

        echo json_encode($output);

    $conexao->close();
</code>```

Problem: when there are no sales and the sum is equal to zero, on the client side the output returns only null and I get de error Uncaught TypeError: Cannot read property 'metaData' of null

EDITED:

If value the output is:

```<code>[{"year":2017,"value":11600}]
</code>```

If not output is just:

```<code>null
</code>```

If I query the database directly the result is:

year:

value:

Is the year supposed to always return a result and the value equal zero?

year: 2016

value: 0

答:
Best way to get rid of the error is by checking the that the country parameter is set so do an if statement after the declaration of $country_parameter like this</p>

```<code>$country_parameter = //value;
if (!isset($country_parameter)==0){
// do something
}
</code>```

Body:
With the following query I get the sum of the sales value per year for each country in the database

   $country_parameter = $_REQUEST['parameter'];

   $query = "SELECT YEAR(sl.year_sales) AS year,
                       COALESCE(SUM(sl.value_sales),0) AS value
                       FROM sales sl LEFT JOIN country co
                       ON sl.id_country = co.id_country
                       WHERE parameter = ?
                       GROUP BY year
                       ORDER BY year";

    if($statement = $conexao->prepare($query)){
        $statement->bind_param("i", $country_parameter );
        $statement->execute();

        $result = $statement ->get_result();

        while($data = $result->fetch_assoc()){
            $output[] = $data;
        }

        echo json_encode($output);

    $conexao->close();

Problem: when there are no sales and the sum is equal to zero, on the client side the output returns only null and I get de error Uncaught TypeError: Cannot read property 'metaData' of null

EDITED:

If value the output is:

[{"year":2017,"value":11600}]

If not output is just:

null

If I query the database directly the result is:

year:

value:

Is the year supposed to always return a result and the value equal zero?

year: 2016

value: 0

Body:
Best way to get rid of the error is by checking the that the country parameter is set so do an if statement after the declaration of $country_parameter like this

$country_parameter = //value;
if (!isset($country_parameter)==0){
// do something
}


问:
Properly use 'this' in jquery
I have created this iOS-like menu and I'm trying to make the slide right work when you click on a certain category. I have made something that works here but with only one div that needs clicking (showing .page.second).

Now when I try to do the same on this longer menu, it needs more editing because there are several clickable
 that can lead to different .page.second. I wanted to know if I could succeed thanks to a 'this' or if the only option was to name all the pages and refer to them one by one in the jquery code?

I'm not sure this is very clear, please ask questions if you didn't understand something, or what I wanted to do!

Thanks for the help!

$('.mtitle').click(function(){
  $('.page.second').show()
});
$('.back').click(function(){
  $('.page.second').hide()
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main{
  position:relative;
  width:600px;
  height:700px;
  overflow-y:scroll;
  overflow-x:hidden;
  border:2px solid #aaa;
  border-radius:10px;
}
.space{
  height:35px;
  margin:0;
  border-bottom:1px solid #aaa;
}
.page{
  top:0;
  left:0;
  background:#ddd;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -ms-transition: 1s ease;
  -o-transition: 1s ease;
  transition: 1s ease;
}
.page p{
  text-align:center;
  font-size:25px;
  font-family:Helvetica, arial, sans-serif;
  font-weight:700;
}
.top{
  border-bottom:1px solid #333;
  background:#fff;
  margin-bottom:20px;
}
.page.second{
  display:none;
  position:absolute;
  top:0;
  left:0;
}
.back{
  cursor:pointer;
  border:none;
  color:#0084ff;
  font-family:helvetica, arial, sans-serif;
  background:transparent;
}
.mtitle{
  background:#fff;
  cursor:pointer;
  width:100%;
  display:inline-block;
}

.mtitle img{
  float:left;
  width:30px;
  height:30px;
  margin:8px 10px;
}
.mtitle h1{
  color:#222;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.mtitle i{
  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
  line-height:40px;
}

.tags{
  width:100%;
  float:right;
  cursor:pointer;
  display:inline-block;
}
.tags a, .droptitle{
  display:inline-block;
  text-decoration:none;
  width:100%;
  color:#222;
  background:#fff;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  line-height:25px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.droptitle i{  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
}</code>```

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

{Title} - All links

General

Home

Contact

Soundtrack

Icons

TV Shows

  <button class="back"> General</button>

TV Shows

brooklyn nine-nine

Amy Santiago
Charles Boyle
Gina Linetti
Hitchcock
Jake Peralta
Raymond Holt
Rosa Diaz
Scully
Terry Jeffords

friends

Rachel Green
Monica Geller
Phoebe Buffay
Joey Tribbiani
Chandler Bing
Ross Geller

game of thrones
how i met your mother
how to get away with murder
jane the virgin
new girl
one tree hill
orange is the new black

orphan black

Alison Hendrix
Beth Childs
Cosima Niehaus
Delphine Cormier
Donnie Hendrix
Felix Dawkins
Helena
Kira Manning
Krystal Goderitch
Paul Dierden
Rachel Duncan
Sarah Manning
Siobhan Sadler

skam

main characters

Eva Kviig Mohn
Noora Amalie Sætre
Isak Valtersen
Sana Bakkoush

Chris Berg
Christoffer Schistad
Eskild Tryggvason
Even Bech Næsheim
Ingrid Theis Gaupseth
Jonas Noah Vasquez
Linn Larsen Hansen
Magnus Fossbakken
Mahdi Disi
Sara Nørrstelien
Vilde Lien Hellerud
William Magnusson

once upon a time

August Booth
Belle French
David Nolan
Emma Swan
Graham Humbert
Henry Daniel Mills
Jefferson
Killian Jones
Mary Margaret Blanchard
Neal Cassidy
Regina Mills
Robin Hood
Ruby
Rumplestiltskin
Zelena

stranger things
13 reasons why

Ships

Emma & Regina
Noora & William
Frank & Laurel
Magnus & Vilde

Actors

Alfie Enoch
Andy Samberg
Bruno Mars
Charlie Heaton
Chloe Bennet
Chris Hemsworth
Chris Pratt
Cobie Smulders
Daniel Sharman
Danielle Panabaker
Dylan Minnette
Emilia Clarke
Evelyne Brochu
Gina Rodriguez
Halsey
Jack Falahee
Jamie Dornan
Jennifer Aniston
Jennifer Morrison
Jessica Alba
Justin Baldoni
Karla Souza
Kate Mara
Katherine Langford
Katherine McNamara
Katie Cassidy
Kit Harington
Lana Parrilla
Leighton Meester
Lily Collins
Lisa Kudrow
Madelaine Petsch
Margot Robbie
Max Greenfield
Melissa Fumero
Natalie Dormer
Natalia Dyer
Richard Madden
Rose Leslie
Rose McIver
Sarah Paulson
Selena Gomez
Stephanie Beatriz
Stephen Amell
Sophia Bush
Sophie Turner
Tatiana Maslany
Theo James
Theresa Eggesbø
Yael Grobglas
Zooey Deschanel

Post types

gif
photo
icons
tutorial
answer
edit

Movies

Guardians of the Galaxy
The End of the Longing
Suicide Squad
La La Land

Magazines

Complex
Evening Standard
Daman
Darling
LA Times
NKD
Popular TV
Shape
Vanity Fair
Vogue
WWD

   ```

答:
If your .pages are tightly coupled with some trigger buttons the best way is to use data-* attribute like:

```<code><div class="mtitle" data-toggle="Some page">Some page</div>
</code>```

and as you can already see, it's used to couple it with this page:

```<code><div class="page" data-togglable="Some page">Some page content</div>
</code>```

using the matching data value of "Some page".

Here's a quick example as a minified proof of concept

(function() {

  var $togglable = $("[data-togglable]"), // Collect all pages
      $target; // Used to store the last opened target page

  $("[data-toggle]").on("click", function(e) {

    e.preventDefault();  // prevent default browser behavior
    e.stopPropagation(); // prevent button click propagate to a parent button

    var dataID = $(this).data("toggle"); // Get the data value "ID" (i.e: "Page 1")

    $target = $("[data-togglable='" + dataID + "']");

    $togglable.not( $target ).stop().slideUp(); // Slide all up (not the target page)
    $target.stop().slideToggle();               // Toggle the target page

  });

}());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mtitle{border:1px solid #eee;}
.page{display:none; background: #eee;}</code>```

Page 1

  Some page 1 content

Page 2

  Some page 2 content

I also toggle page 2

```

Title: Properly use 'this' in jquery

Body:
I have created this iOS-like menu and I'm trying to make the slide right work when you click on a certain category. I have made something that works here but with only one div that needs clicking (showing .page.second).

Now when I try to do the same on this longer menu, it needs more editing because there are several clickable
 that can lead to different .page.second. I wanted to know if I could succeed thanks to a 'this' or if the only option was to name all the pages and refer to them one by one in the jquery code?

I'm not sure this is very clear, please ask questions if you didn't understand something, or what I wanted to do!

Thanks for the help!

$('.mtitle').click(function(){
  $('.page.second').show()
});
$('.back').click(function(){
  $('.page.second').hide()
})

#main{
  position:relative;
  width:600px;
  height:700px;
  overflow-y:scroll;
  overflow-x:hidden;
  border:2px solid #aaa;
  border-radius:10px;
}
.space{
  height:35px;
  margin:0;
  border-bottom:1px solid #aaa;
}
.page{
  top:0;
  left:0;
  background:#ddd;
  -webkit-transition: 1s ease;
  -moz-transition: 1s ease;
  -ms-transition: 1s ease;
  -o-transition: 1s ease;
  transition: 1s ease;
}
.page p{
  text-align:center;
  font-size:25px;
  font-family:Helvetica, arial, sans-serif;
  font-weight:700;
}
.top{
  border-bottom:1px solid #333;
  background:#fff;
  margin-bottom:20px;
}
.page.second{
  display:none;
  position:absolute;
  top:0;
  left:0;
}
.back{
  cursor:pointer;
  border:none;
  color:#0084ff;
  font-family:helvetica, arial, sans-serif;
  background:transparent;
}
.mtitle{
  background:#fff;
  cursor:pointer;
  width:100%;
  display:inline-block;
}

.mtitle img{
  float:left;
  width:30px;
  height:30px;
  margin:8px 10px;
}
.mtitle h1{
  color:#222;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.mtitle i{
  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
  line-height:40px;
}

.tags{
  width:100%;
  float:right;
  cursor:pointer;
  display:inline-block;
}
.tags a, .droptitle{
  display:inline-block;
  text-decoration:none;
  width:100%;
  color:#222;
  background:#fff;
  border-bottom:1px solid #aaa;
  margin:0;
  padding:10px;
  line-height:25px;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
  font-weight:500;
}
.droptitle i{  float:right;
  color:#aaa;
  margin-right:5px;
  font-size:20px;
  -webkit-text-stroke: 2px white;
}

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

{Title} - All links

General

Home

Contact

Soundtrack

Icons

TV Shows

  <button class="back"> General</button>

TV Shows

brooklyn nine-nine

Amy Santiago
Charles Boyle
Gina Linetti
Hitchcock
Jake Peralta
Raymond Holt
Rosa Diaz
Scully
Terry Jeffords

friends

Rachel Green
Monica Geller
Phoebe Buffay
Joey Tribbiani
Chandler Bing
Ross Geller

game of thrones
how i met your mother
how to get away with murder
jane the virgin
new girl
one tree hill
orange is the new black

orphan black

Alison Hendrix
Beth Childs
Cosima Niehaus
Delphine Cormier
Donnie Hendrix
Felix Dawkins
Helena
Kira Manning
Krystal Goderitch
Paul Dierden
Rachel Duncan
Sarah Manning
Siobhan Sadler

skam

main characters

Eva Kviig Mohn
Noora Amalie Sætre
Isak Valtersen
Sana Bakkoush

Chris Berg
Christoffer Schistad
Eskild Tryggvason
Even Bech Næsheim
Ingrid Theis Gaupseth
Jonas Noah Vasquez
Linn Larsen Hansen
Magnus Fossbakken
Mahdi Disi
Sara Nørrstelien
Vilde Lien Hellerud
William Magnusson

once upon a time

August Booth
Belle French
David Nolan
Emma Swan
Graham Humbert
Henry Daniel Mills
Jefferson
Killian Jones
Mary Margaret Blanchard
Neal Cassidy
Regina Mills
Robin Hood
Ruby
Rumplestiltskin
Zelena

stranger things
13 reasons why

Ships

Emma & Regina
Noora & William
Frank & Laurel
Magnus & Vilde

Actors

Alfie Enoch
Andy Samberg
Bruno Mars
Charlie Heaton
Chloe Bennet
Chris Hemsworth
Chris Pratt
Cobie Smulders
Daniel Sharman
Danielle Panabaker
Dylan Minnette
Emilia Clarke
Evelyne Brochu
Gina Rodriguez
Halsey
Jack Falahee
Jamie Dornan
Jennifer Aniston
Jennifer Morrison
Jessica Alba
Justin Baldoni
Karla Souza
Kate Mara
Katherine Langford
Katherine McNamara
Katie Cassidy
Kit Harington
Lana Parrilla
Leighton Meester
Lily Collins
Lisa Kudrow
Madelaine Petsch
Margot Robbie
Max Greenfield
Melissa Fumero
Natalie Dormer
Natalia Dyer
Richard Madden
Rose Leslie
Rose McIver
Sarah Paulson
Selena Gomez
Stephanie Beatriz
Stephen Amell
Sophia Bush
Sophie Turner
Tatiana Maslany
Theo James
Theresa Eggesbø
Yael Grobglas
Zooey Deschanel

Post types

gif
photo
icons
tutorial
answer
edit

Movies

Guardians of the Galaxy
The End of the Longing
Suicide Squad
La La Land

Magazines

Complex
Evening Standard
Daman
Darling
LA Times
NKD
Popular TV
Shape
Vanity Fair
Vogue
WWD

Body:
If your .pages are tightly coupled with some trigger buttons the best way is to use data-* attribute like:

<div class="mtitle" data-toggle="Some page">Some page</div>

and as you can already see, it's used to couple it with this page:

<div class="page" data-togglable="Some page">Some page content</div>

using the matching data value of "Some page".

Here's a quick example as a minified proof of concept

(function() {

  var $togglable = $("[data-togglable]"), // Collect all pages
      $target; // Used to store the last opened target page

  $("[data-toggle]").on("click", function(e) {

    e.preventDefault();  // prevent default browser behavior
    e.stopPropagation(); // prevent button click propagate to a parent button

    var dataID = $(this).data("toggle"); // Get the data value "ID" (i.e: "Page 1")

    $target = $("[data-togglable='" + dataID + "']");

    $togglable.not( $target ).stop().slideUp(); // Slide all up (not the target page)
    $target.stop().slideToggle();               // Toggle the target page

  });

}());

.mtitle{border:1px solid #eee;}
.page{display:none; background: #eee;}

<div class="mtitle" data-toggle="Page 1">Page 1</div>
<div class="page" data-togglable="Page 1">
  Some page 1 content
</div>

<div class="mtitle" data-toggle="Page 2">Page 2</div>
<div class="page" data-togglable="Page 2">
  Some page 2 content
</div>

<a data-toggle="Page 2">I also toggle page 2</a>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
jQuery.toggle() extremely slow on many
 elements
I have a table like this:

```<code><table>
    <tr class="a"><td></td></tr>
    <tr class="b"><td></td></tr>
</table>
</code>```

There are nearly 800 rows and most of them of class a. Now I want to toggle these rows like this:

```<code>    $("#toggle_a").click(function(){
        $("tr.a").toggle();
    });
    $("#toggle_b").click(function(){
        $("tr.b").toggle();
    });
</code>```

But this is really extremely slow and most of the time the browser wants to stop the action.

Has anybody an idea how to make this thing faster and usable?

答:
Instead of using table structure, use the LI tag. It will speedy the html render process.

```<code><UL style="padding: 0; list-style-type: none;">
    <LI class="a">1</LI>
    <LI class="b">2</LI>
    <LI>3</LI>
    <LI>4</LI>
</UL>
</code>```

Now you can write the selector on this. This will definitely be an improvement

Title: jQuery.toggle() extremely slow on many <TR> elements

Body:
I have a table like this:

There are nearly 800 rows and most of them of class a. Now I want to toggle these rows like this:

    $("#toggle_a").click(function(){
        $("tr.a").toggle();
    });
    $("#toggle_b").click(function(){
        $("tr.b").toggle();
    });

But this is really extremely slow and most of the time the browser wants to stop the action.

Has anybody an idea how to make this thing faster and usable?

Body:
Instead of using table structure, use the LI tag. It will speedy the html render process.

<UL style="padding: 0; list-style-type: none;">
    <LI class="a">1</LI>
    <LI class="b">2</LI>
    <LI>3</LI>
    <LI>4</LI>
</UL>

Now you can write the selector on this. This will definitely be an improvement


问:
How to Export multiple header Gridview Data to Excel
I have a gridview which has multiple headers added during run time as shown in snap below:

I want to export the data from this gridview to excel for which I have the following code:

```<code>protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gdView.HeaderRow.BackColor = Color.White;
            foreach (TableCell hcell in gdView.HeaderRow.Cells)
            {
                hcell.BackColor = Color.White;
            }
            foreach (GridViewRow row in gdView.Rows)
            {
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        cell.CssClass = "textmode";
                    }
                }
            }
            gdView.RenderControl(hw);
            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
    public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {
        // controller
    }
</code>```

The excel output I am getting is as follows:

As you can see the color of the header rows is continuing beyond the table area. Also the top header rows are collapsed in the excel output.

Request you all to kindly suggest how this can be resolved.

Thanks.

答:
I could finally solve the issue by modifying the code as below:</p>

```<code>protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int x = 0; x <= 3; x++)
            {
                GridViewRow rows = (GridViewRow)gdView.HeaderRow.Parent.Controls[x];
                rows.BackColor = Color.White;
                rows.Height = 15;
                for (int i = 0; i <= rows.Cells.Count - 1; i++)
                {
                    rows.Cells[i].BackColor = Color.Maroon;
                }
            }
            foreach (GridViewRow row in gdView.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    cell.VerticalAlign = VerticalAlign.Middle;
                    cell.CssClass = "textmode";
                }
            }
            gdView.RenderControl(hw);
            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
    public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {
        // controller
    }
</code>```

Body:
I have a gridview which has multiple headers added during run time as shown in snap below:

I want to export the data from this gridview to excel for which I have the following code:

protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gdView.HeaderRow.BackColor = Color.White;
            foreach (TableCell hcell in gdView.HeaderRow.Cells)
            {
                hcell.BackColor = Color.White;
            }
            foreach (GridViewRow row in gdView.Rows)
            {
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        cell.CssClass = "textmode";
                    }
                }
            }
            gdView.RenderControl(hw);
            //style to format numbers to string
            string style = @"";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
    public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {
        // controller
    }

The excel output I am getting is as follows:

As you can see the color of the header rows is continuing beyond the table area. Also the top header rows are collapsed in the excel output.

Request you all to kindly suggest how this can be resolved.

Thanks.

Body:
I could finally solve the issue by modifying the code as below:

protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int x = 0; x <= 3; x++)
            {
                GridViewRow rows = (GridViewRow)gdView.HeaderRow.Parent.Controls[x];
                rows.BackColor = Color.White;
                rows.Height = 15;
                for (int i = 0; i <= rows.Cells.Count - 1; i++)
                {
                    rows.Cells[i].BackColor = Color.Maroon;
                }
            }
            foreach (GridViewRow row in gdView.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    cell.VerticalAlign = VerticalAlign.Middle;
                    cell.CssClass = "textmode";
                }
            }
            gdView.RenderControl(hw);
            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
    public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
    {
        // controller
    }


问:
Keras model.summary() object to string
I want to write a *.txt file with the neural network hyperparameters and the model architecture. Is it possible to write the object model.summary() to my output file?

```<code>(...)
summary = str(model.summary())
(...)
out = open(filename + 'report.txt','w')
out.write(summary)
out.close
</code>```

It happens that I'm getting "None" as you can see below.

```<code>Hyperparameters
=========================

learning_rate: 0.01
momentum: 0.8
decay: 0.0
batch size: 128
no. epochs: 3
dropout: 0.5
-------------------------

None
val_acc: 0.232323229313
val_loss: 3.88496732712
train_acc: 0.0965207634216
train_loss: 4.07161939425
train/val loss ratio: 1.04804469418
</code>```

Any idea how to deal with that?

答:
One option, although not an exact replacement for model.summary, is to export a model's configuration using model.get_config(). From the docs:

model.get_config(): returns a dictionary containing the configuration of the model. The model can be reinstantiated from its config via:

```<code>config = model.get_config()
model = Model.from_config(config)
# or, for Sequential:
model = Sequential.from_config(config)
</code>```

Title: Keras model.summary() object to string

Body:
I want to write a *.txt file with the neural network hyperparameters and the model architecture. Is it possible to write the object model.summary() to my output file?

(...)
summary = str(model.summary())
(...)
out = open(filename + 'report.txt','w')
out.write(summary)
out.close

It happens that I'm getting "None" as you can see below.

Hyperparameters
=========================

learning_rate: 0.01
momentum: 0.8
decay: 0.0
batch size: 128
no. epochs: 3
dropout: 0.5
-------------------------

None
val_acc: 0.232323229313
val_loss: 3.88496732712
train_acc: 0.0965207634216
train_loss: 4.07161939425
train/val loss ratio: 1.04804469418

Any idea how to deal with that?

Body:
One option, although not an exact replacement for model.summary, is to export a model's configuration using model.get_config(). From the docs:

model.get_config(): returns a dictionary containing the configuration of the model. The model can be reinstantiated from its config via:

config = model.get_config()
model = Model.from_config(config)
# or, for Sequential:
model = Sequential.from_config(config)


问:
How to make one hyperlink give different pages?
I'm trying to set up a hyperlink that will randomly open a different webpage per click from a list of URLs. Does anyone know what would be a good function to start with to achieve this?</p>

答:
Like this?</p>

```<code> <!DOCTYPE html>
<html>
<head>
<script>
var links = ['http://google.com', 'http://facebook.com']
function GoToSomeAddress() {
    window.open(links[getRandomInt(0, 1)]);
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
</head>
<body>
The content of the body element is displayed in your browser.
<a href="" onclick="GoToSomeAddress();return false;">Take me on an adventure</a>
</body>

</html>
</code>```

Body:
Like this?

 <!DOCTYPE html>
<html>
<head>
<script>
var links = ['http://google.com', 'http://facebook.com']
function GoToSomeAddress() {
    window.open(links[getRandomInt(0, 1)]);
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
</head>
<body>
The content of the body element is displayed in your browser.
<a href="" onclick="GoToSomeAddress();return false;">Take me on an adventure</a>
</body>

</html>