问:
Laravel view content showing twice for routes with parameters
I am working with Laravel 5.5, I have two get routes with parameters like this

Route::get( 'route/{parameter}', 'Controller@action' )->name( 'controller.action' );

My controller action is simply loading the view:

```<code>public function action( $slug ) {
    return view( 'view', [
        'post' => Post::whereSlug( $slug )->first()
    ] );
}
</code>```

My base app.blade.php view content is:

```<code><!-- ==========================
  PAGE WRAPPER
=========================== -->
<div class="page-wrapper">

    <!-- ==========================
          HEADER
        =========================== -->
    <header class="header" id="header">

        <!-- Hamburger -->
        <div class="h-hamburger" id="hamburger">
            <svg class="h-hamburger__icon">
                <use xlink:href="#icon-hamburger"></use>
            </svg>
        </div>

        <!-- Logo -->
        <div class="h-logo">
            <a href="{{route('dashboard')}}" title="{{config('app.name','Sensei U')}}">
                <img class="h-logo__img" src="{{URL::to('/')}}/images/logo-black.svg"
                     alt="{{ config('app.name', 'Sensei U') }}">
            </a>
        </div>

    @if (Auth::user())

        <!-- Welcome -->
            <div class="h-welcome">

                <!-- Title -->
                <div class="h-welcome__title">Welcome Back, {{Auth::user()->name}}</div>

                <!-- Date -->
                <div class="h-welcome__date">{{date('F j')}}</div>

                <!-- Time -->
                <div class="h-welcome__time">{{date('g:i a')}}</div>

            </div>
            <!-- Profile -->
            <div class="h-profile">

                <!-- Avatar -->
                <img class="h-profile__avatar"
                     src="{{Auth::user()->image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 58, 58) : ''}}"
                     srcset="{{Auth::user()->image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 116, 116) : ''}} 2x"
                     alt="{{Auth::user()->name}}">
            @if(($notifications = SenseiU::generateNotificationMessages( Auth::user() )) )
                <!-- Notifications -->
                    <button class="h-profile__notifications" data-uid="{{Auth::user()->id}}"
                            data-url="{{route('member.nr', [Auth::user()])}}">
                        {{count($notifications)}}
                    </button>
                @endif

            </div>

        @if($notifications)

            <!-- Notifications Dropdown -->
                <ul class="noti-dropdown">
                    @foreach($notifications as $notification)
                        <li class="noti-dropdown__item">
                            <a class="noti-dropdown__link" href="{{$notification['link']}}">
                                {{$notification['msg']}}
                            </a>
                        </li>
                    @endforeach
                </ul>
            @endif
        @endif

    </header>
    <!-- ==========================
      CONTENT WRAPPER
    =========================== -->
    <div class="wrapper">
        <!-- ==========================
          SIDEBAR
        =========================== -->
        <aside class="sidebar" id="sidebar">
            <!-- Menu -->
            <nav class="sidebar-menu">
                @if(Auth::user())
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'dashboard' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('dashboard')}}">
                        <span class="sidebar-menu__title">Home</span>
                    </a>

                    @permission('daily-mastery')
                    <a class="sidebar-menu__item  {{Route::currentRouteName() == 'member.daily-mastery' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.daily-mastery')}}">
                        <span class="sidebar-menu__title">Daily Mastery</span>

                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] ))

                            <span class="sidebar-menu__notifications">{{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] )}}</span>
                        @endif
                    </a>
                    @endpermission

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.macros' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.macros')}}">
                        <span class="sidebar-menu__title">Macros Calculator</span>
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.instructional-videos' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.instructional-videos')}}">
                        <span class="sidebar-menu__title">Instructional Videos</span>
                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] )}}</span>
                        @endif
                    </a>

                    @permission('health-articles')
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.nutrition' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.nutrition')}}">
                        <span class="sidebar-menu__title">Nutrition</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.sports-injuries' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.sports-injuries')}}">
                        <span class="sidebar-menu__title">Sports Injuries</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.mobility-stretching' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.mobility-stretching')}}">
                        <span class="sidebar-menu__title">Mobility & Stretching</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.functional-training' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.functional-training')}}">
                        <span class="sidebar-menu__title">Functional Training</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.articles' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.articles')}}">
                        <span class="sidebar-menu__title">Articles</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 )}}</span>
                        @endif
                    </a>
                    @endpermission

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.faqs' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.faqs')}}">
                        <span class="sidebar-menu__title">FAQs</span>
                    </a>

                    <a class="sidebar-menu__item" href="#">
                        <span class="sidebar-menu__title">Ultimate Personal Trainer</span>
                    </a>
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.profile.edit' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.profile.edit')}}">
                        <span class="sidebar-menu__title">Edit Profile</span>
                    </a>
                    <a class="sidebar-menu__item" href="{{URL::to('logout')}}">
                        <span class="sidebar-menu__title">Logout</span>
                    </a>
                @else
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'login' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('login')}}">
                        <span class="sidebar-menu__title">Login</span>
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'register' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('register')}}">
                        <span class="sidebar-menu__title">Register</span>
                    </a>
                @endif
            </nav>

        </aside>

        <!-- ==========================
              CONTENT
            =========================== -->
        <main class="content @yield('main-class')">
            <!-- Container -->
            <div class="@yield('container-class')">
                @if(session('msg'))
                    <div class="msg msg-{{session('status')}}">
                        {{session('msg')}}
                    </div>
                @endif
                @yield('content')
            </div>
        </main>
    </div>
</div>
</code>```

My view content is like this:

```<code>@extends('layouts.app')

@section('title', $title)
@section('container-class', 'container')

@section('content')
    @if($post)
        <div class="cover" style="background-image:url('{{Storage::url($post->file)}}');"></div>
        <article class="article__container">
            <h1>{{$post->title}}</h1>
            <div>{!!$post->text!!}</div>
        </article>
    @endif
@stop
</code>```

The problem is that my view content is showing duplicated, one 404 on top of the actual view content like this:

答:
This could be due to the slug of your Posts. If you include special characters in the slug Laravel won't automatically be able to resolve this, because it assumes it's another URL. I assume you're trying to view a post which has a slug like my/first/post, this will work if you include a where statement at the route. You would have to do something like this:

```<code>Route::get('route/{parameter}', 'Controller@action')
    ->name('controller.action')
    ->where('parameter', '([A-Za-z0-9\-\/]+)');
</code>```

This way the route will include a regex, which validates if the complete string is valid.

I don't know why it would display both the post and a 404 page, it looks like your just including the default 404 page in layouts.app

Body:
I am working with Laravel 5.5, I have two get routes with parameters like this

Route::get( 'route/{parameter}', 'Controller@action' )->name( 'controller.action' );

My controller action is simply loading the view:

public function action( $slug ) {
    return view( 'view', [
        'post' => Post::whereSlug( $slug )->first()
    ] );
}

My base app.blade.php view content is:

            <svg class="h-hamburger__icon">
                <use xlink:href="#icon-hamburger"></use>
            </svg>

    @if (Auth::user())

Welcome Back, {{Auth::user()->name}}

{{date('F j')}}

{{date('g:i a')}}

                image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 58, 58) : ''}}"
                     srcset="{{Auth::user()->image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 116, 116) : ''}} 2x"
                     alt="{{Auth::user()->name}}">
            @if(($notifications = SenseiU::generateNotificationMessages( Auth::user() )) )

                    <button class="h-profile__notifications" data-uid="{{Auth::user()->id}}"
                            data-url="{{route('member.nr', [Auth::user()])}}">
                        {{count($notifications)}}
                    </button>
                @endif

        @if($notifications)

                    @foreach($notifications as $notification)

                                {{$notification['msg']}}

                    @endforeach

            @endif
        @endif

                @if(Auth::user())

                        Home

                    @permission('daily-mastery')

                        Daily Mastery

                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] ))

                            {{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] )}}
                        @endif

                    @endpermission

                        Macros Calculator

                        Instructional Videos
                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] ))
                            {{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] )}}
                        @endif

                    @permission('health-articles')

                        Nutrition
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 )}}
                        @endif

                        Sports Injuries
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 )}}
                        @endif

                        Mobility & Stretching
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 )}}
                        @endif

                        Functional Training
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 )}}
                        @endif

                        Articles
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 )}}
                        @endif

                    @endpermission

                        FAQs

                        Ultimate Personal Trainer

                        Edit Profile

                        Logout

                @else

                        Login

                        Register

                @endif

                @if(session('msg'))

                        {{session('msg')}}

                @endif
                @yield('content')

My view content is like this:

@extends('layouts.app')

@section('title', $title)
@section('container-class', 'container')

@section('content')
    @if($post)

file)}}');">

{{$post->title}}

{!!$post->text!!}

    @endif
@stop

The problem is that my view content is showing duplicated, one 404 on top of the actual view content like this:

Body:
This could be due to the slug of your Posts. If you include special characters in the slug Laravel won't automatically be able to resolve this, because it assumes it's another URL. I assume you're trying to view a post which has a slug like my/first/post, this will work if you include a where statement at the route. You would have to do something like this:

Route::get('route/{parameter}', 'Controller@action')
    ->name('controller.action')
    ->where('parameter', '([A-Za-z0-9\-\/]+)');

This way the route will include a regex, which validates if the complete string is valid.

I don't know why it would display both the post and a 404 page, it looks like your just including the default 404 page in layouts.app


来源: stackexchange

问:
Manipulating Javascript with Java
I have a complex, generated Javascript file (it's generated by the GWT compiler), and I need to be able to programmatically make changes to this and output a 'cleaned' version of the file. In particular, I have:

```<code>function bookmark(){
    // lots-o-javascript
    var M=Vb+s+I+Wb;n.write(Xb+Yb+Zb+$b+_b+ac+bc+$b+_b+cc+dc+ec+M+fc+gc+hc+ic)
}
bookmark();
</code>```

Un-obfuscated, the inside of the function looks like:

```<code>var compiledScriptTag = '"<script src=\\"' + base + strongName + '.cache.js\\"><\/scr" + "ipt>"';
$doc_0.write('<scr' + 'ipt><!-' + '-\n' + 'blah blah blah' + 'document.write(' + compiledScriptTag + ');' + '\n-' + '-><\/scr' + 'ipt>');
</code>```

So what I need to do is in a Java servlet, transform the above two lines into the equivalent of:

```<code>eval('blah blah blah');
document.body.appendChild(document.createElement('script')).src=base + strongName + ".cache.js";
</code>```

What are my best options to parse and re-arrange this Javascript file? Should I look into Rhino, would it be able to give handles to these (as well as the nested Javascript which is being written using $doc.write)? Any ideas would be appreciated.

答: You can use RegEx in Java but I would recommend using the regular String search functions and rebuilding the JavaScript code in a new StringBuilder object.</p>

ContentLicense: CC BY-SA 2.5

Title: Manipulating Javascript with Java

Body:
I have a complex, generated Javascript file (it's generated by the GWT compiler), and I need to be able to programmatically make changes to this and output a 'cleaned' version of the file. In particular, I have:

function bookmark(){
    // lots-o-javascript
    var M=Vb+s+I+Wb;n.write(Xb+Yb+Zb+$b+_b+ac+bc+$b+_b+cc+dc+ec+M+fc+gc+hc+ic)
}
bookmark();

Un-obfuscated, the inside of the function looks like:

var compiledScriptTag = '"


问:
replacing AnnotationMethodHandlerAdapter with RequestMappingHandlerAdapter issue
I recently upgraded to spring 3.2 and noticed that AnnotationMethodHandlerAdapter had been deprecated in favor of RequestMappingHandlerAdapter.  So I reconfigured to use the new class, complete with a custom MessageConverter I need.  All fine and good.

However, when attempting to hit a URL supported by an annotated Controller, I'm getting an error:

```<code> [java] javax.servlet.ServletException: No adapter for handler [my.company.TagController@1c2e7808]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
 [java]     at org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1128)
 [java]     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:903)
 [java]     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
</code>```

When debugging the dispatcher, and in particular, the Dispatcher.getHandlerAdapter() method, it's finding my HandlerAdapter, but the AbstractHandlerMethodAdapter.supports() that is invoked wants a MethodHandler:

```<code>public final boolean supports(Object handler) {
  return handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler);
}
</code>```

and the controller is not a HandlerMethod.  The AnnotatedMethodHandlerAdapter's support method is.. well, different (and works still!)

```<code>public boolean supports(Object handler) {
  return getMethodResolver(handler).hasHandlerMethods();
}
</code>```

So I apparently cannot simply upgrade to the new class... I'm missing some additional configuration, but the documentation isn't really helping me out.  Any ideas?

Thanks.

答:
```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
  @Override
  protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
    return new XXXXRequestMappingHandlerAdapter();
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I recently upgraded to spring 3.2 and noticed that AnnotationMethodHandlerAdapter had been deprecated in favor of RequestMappingHandlerAdapter.  So I reconfigured to use the new class, complete with a custom MessageConverter I need.  All fine and good.

However, when attempting to hit a URL supported by an annotated Controller, I'm getting an error:

 [java] javax.servlet.ServletException: No adapter for handler [my.company.TagController@1c2e7808]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
 [java]     at org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1128)
 [java]     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:903)
 [java]     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)

When debugging the dispatcher, and in particular, the Dispatcher.getHandlerAdapter() method, it's finding my HandlerAdapter, but the AbstractHandlerMethodAdapter.supports() that is invoked wants a MethodHandler:

public final boolean supports(Object handler) {
  return handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler);
}

and the controller is not a HandlerMethod.  The AnnotatedMethodHandlerAdapter's support method is.. well, different (and works still!)

public boolean supports(Object handler) {
  return getMethodResolver(handler).hasHandlerMethods();
}

So I apparently cannot simply upgrade to the new class... I'm missing some additional configuration, but the documentation isn't really helping me out.  Any ideas?

Thanks.


问:
Dotnet compliation error; aspnetcore.mvc.razor.viewcompliation.rsp exited with code 1
I have the following issue in my API where the code is running ok when i try to run it in local host, however when i try to publish it, this error comes up
Help!!

Error The command ""dotnet" exec --runtimeconfig "~\xxxx-api\API.xxxx\bin\Release\netcoreapp2.0\API.xxxx.runtimeconfig.json" --depsfile "~\xxxx-api\API.xxxx\bin\Release\netcoreapp2.0\API.xxxx.deps.json" "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.razor.viewcompilation\2.0.0\build\netstandard2.0\Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.dll" @"obj\Release\netcoreapp2.0\microsoft.aspnetcore.mvc.razor.viewcompilation.rsp"" exited with code 1. API.xxxx        0

names are crossed out due to company policy :(

答:
Remove the following file:

privateregistry.user.bin

Located in

```<code>C:\Users\[UserId]\AppData\Local\Microsoft\VisualStudio\15.0_[UniqueCode]
</code>```

No need to restart computer, now Visual Studio 2017 starts successfully.

Body:
Remove the following file:

privateregistry.user.bin

Located in

C:\Users\[UserId]\AppData\Local\Microsoft\VisualStudio\15.0_[UniqueCode]

No need to restart computer, now Visual Studio 2017 starts successfully.


问:
Triangles algorithm
I have this problem to solve:

The input is a number and a triangle, for example:

```<code>5
#-##----#
 -----#-
  ---#-
   -#-
    -
</code>```

The number is count of rows of the triangle.

And I have to print the largest "triangle area" - the largest triangle made of -. For this one the answer is 9.

The triangle can also be upside down:

```<code>4
#-#-#--
 #---#
  ##-
   -
</code>```

For this, the output is 4.

I need some help with the algorithm. Please give me just a little help, not the whole algorithm, because I want to try to solve it by myself, I just need a direction.

答:
If efficiency doesn't matter that much:

Have one loop which searchs for candidates (it traverses each row from left to right). If you find a -, interrupt the search and try to compute this candidate.

Therefore first move to the right checking where it ends (#). Then you know the base of your triangle (indices) and directly know where it must continue in the next line, check that and repeat until you've explored that candidate fully. If left indix was li and right ri of row row, then the triangle must continue in the next row * row + 1 at indices li + 1 and ri - 1.

Store its size and continue with the search part again. Terminate once the search visited all rows.

You can slightly improve its efficiency by ignoring - which are already part of an discovered triangle. But only if they are part of the triangle base row.

Title: Triangles algorithm

Body:
I have this problem to solve:

The input is a number and a triangle, for example:

5
#-##----#
 -----#-
  ---#-
   -#-
    -

The number is count of rows of the triangle.

And I have to print the largest "triangle area" - the largest triangle made of -. For this one the answer is 9.

The triangle can also be upside down:

4
#-#-#--
 #---#
  ##-
   -

For this, the output is 4.

I need some help with the algorithm. Please give me just a little help, not the whole algorithm, because I want to try to solve it by myself, I just need a direction.


问:
Vim style folding for CSS/javascript in Visual Studio
Is anyone aware of a way to have VIM style folding in Visual Studio? I use #region blocks in c# class files and they're great, but unfortunately there's no equivalent functionality for javascript and css. The site/app I'm currently working on has a rather lot of css selectors and javascript and navigating the monolithic files is becoming difficult.

One option that we've considered is breaking up the css and javascript into separate files similiar to jquery modules, but then that introduces performance problems in terms of increasing the overall number of http requests.

If anyone has any suggestions for managing the madness, I'd be greatly appreciative!

Update: Richard Kimber suggests using the bookmarking features of visual studio to make navigating by headings more manageable. This is a step in the right direction, but not as useful as code folding/blocking.

答:
I found a Microsoft extension that improved the JavaScript text editor for Visual Studio 2010.

http://visualstudiogallery.msdn.microsoft.com/en-us/872d27ee-38c7-4a97-98dc-0d8a431cc2ed

I have used it, and it gives all of the following for JavaScript files:

Brace Matching

Outlining / Code-folding

Current Word Highlighting

IntelliSense Doc-Comments  Support

OwnerDisplayName: squidsoup

LastEditorDisplayName: Bayard Randel


问:
How to change border width of custom UIButton
So, I'm working on simple form for my app. I have two button that allow user to choose wether they want to input email or phone number. I make 2 button that looks like android style tab button. Like Below:

So I made custom class for my button. Here is the code:

```<code>@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width

        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}
</code>```

And here is the code on my view controller:

```<code>   @IBAction func PhoneTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        EmailButton.tabButtonBorderWidth = 1.0
        EmailButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        EmailButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = "62"
        UserPhoneEmailTextField.keyboardType = .numberPad
    }

    @IBAction func EmailTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        PhoneButton.tabButtonBorderWidth = 1.0
        PhoneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        PhoneButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = ""
        UserPhoneEmailTextField.placeholder = "Alamat Email"
    }
</code>```

But this is the result I got:

I want only one button that have colored border, like a switch. How can I fix this issue?

答:
You can create a custom button like this: </p>

```<code>class CustomButton: UIButton {

    override func awakeFromNib() {

        layer.borderWidth = 0.5
    }

}
</code>```

<p>and change attributes in awakeFromNib. </p>

Body:
So, I'm working on simple form for my app. I have two button that allow user to choose wether they want to input email or phone number. I make 2 button that looks like android style tab button. Like Below:

So I made custom class for my button. Here is the code:

@IBDesignable
class HC24Button: UIButton {

    @IBInspectable var tabButtonBorderWidth: CGFloat = 1.0

    @IBInspectable var borderWidth: CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor: UIColor? {
        didSet{
            updateView()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var tabsButton : Bool = false{
        didSet{
            updateView()
        }
    }

    func updateView(){
        let border = CALayer()
        let width = tabButtonBorderWidth
        border.borderColor = borderColor?.cgColor
        border.frame = CGRect(x: 0, y: frame.size.height - width, width:  frame.size.width + 20, height: frame.size.height)

        border.borderWidth = width

        layer.addSublayer(border)
        layer.masksToBounds = true
    }

}

And here is the code on my view controller:

   @IBAction func PhoneTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        EmailButton.tabButtonBorderWidth = 1.0
        EmailButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        EmailButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = "62"
        UserPhoneEmailTextField.keyboardType = .numberPad
    }

    @IBAction func EmailTapped(_ sender: HC24Button) {
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        sender.tabButtonBorderWidth = 4.0
        sender.borderColor = HC24AppColors.Main
        PhoneButton.tabButtonBorderWidth = 1.0
        PhoneButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        PhoneButton.borderColor = .lightGray
        UserPhoneEmailTextField.text = ""
        UserPhoneEmailTextField.placeholder = "Alamat Email"
    }

But this is the result I got:

I want only one button that have colored border, like a switch. How can I fix this issue?

Body:
You can create a custom button like this:

class CustomButton: UIButton {

    override func awakeFromNib() {

        layer.borderWidth = 0.5
    }

}

and change attributes in awakeFromNib.


问:
Wildfly 11 management integration with KeyCloak over new Elytron subsystem
I would like to integrate security for WildFly 11 management interfaces (management console, web console) with KeyCloak over the new Elytron subsystem.

I've been looking the latest documentation for Wildfly 11 and there is chapter Using KeyCloak with WildFly Elytron but is unfortunately empty.

I will be really appreciated if someone could give me some advice how to do that.

答: Keycloak documentation for version 3.4 is very detailed http://www.keycloak.org/docs/latest/securing_apps/index.html#_jboss_adapter - you have to install the adapter for your Elytron subsystem on Wildfly 11 (beware: the CLI is different from the Wildfly 10 version! ) </p>


问:
Return rows with column not equals null
I have a working Spring Boot application, I'm vey new to JPA/Hibernate and I'm trying to retrieve results having one of the fields containing no null values. Right now I am getting everything including nulls.

It is phone_number_id that I don't want it to be null. I added nullable=false but it looks like it has no effect on retrievals.

What do I need to do to get only columns which have no null occurrences of phone_number_id

My Model

```<code>@Entity
@NamedQuery(name="Ad.findAll", query="SELECT a FROM Ad a")
public class Ad implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

    @Column(name="ad_content")
    private String adContent;

    @Column(name="ad_title")
    private String adTitle;

    @Column(name="ad_url")
    private String adUrl;

    private Integer age;

    @Column(name="post_id")
    private Long postId;

    //bi-directional many-to-one association to City
    @ManyToOne
    private City city;

    //bi-directional many-to-one association to PhoneNumber
    @ManyToOne
    @JoinColumn(name="phone_number_id", nullable=false)
    private PhoneNumber phoneNumber;

    //bi-directional many-to-one association to AdPhoto
    @OneToMany(mappedBy="ad")
    private List<AdPhoto> adPhotos;

    public Ad() {
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAdContent() {
        return this.adContent;
    }

    public void setAdContent(String adContent) {
        this.adContent = adContent;
    }

    public String getAdTitle() {
        return this.adTitle;
    }

    public void setAdTitle(String adTitle) {
        this.adTitle = adTitle;
    }

    public String getAdUrl() {
        return this.adUrl;
    }

    public void setAdUrl(String adUrl) {
        this.adUrl = adUrl;
    }

    public Integer getAge() {
        return this.age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Long getPostId() {
        return this.postId;
    }

    public void setPostId(Long postId) {
        this.postId = postId;
    }

    public City getCity() {
        return this.city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public PhoneNumber getPhoneNumber() {
        return this.phoneNumber;
    }

    public void setPhoneNumber(PhoneNumber phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public List<AdPhoto> getAdPhotos() {
        return this.adPhotos;
    }

    public void setAdPhotos(List<AdPhoto> adPhotos) {
        this.adPhotos = adPhotos;
    }

    public AdPhoto addAdPhoto(AdPhoto adPhoto) {
        getAdPhotos().add(adPhoto);
        adPhoto.setAd(this);

        return adPhoto;
    }

    public AdPhoto removeAdPhoto(AdPhoto adPhoto) {
        getAdPhotos().remove(adPhoto);
        adPhoto.setAd(null);

        return adPhoto;
    }
</code>```

My repository

```<code>@Repository
public interface AdRepository extends PagingAndSortingRepository<Ad, Long> {

}
</code>```

and my Service class

```<code>@Service
public class AdService {
    private final static int PAGESIZE = 3;

    @Autowired
    AdRepository adRepository;

    public Iterable<Ad> findAllAds() {
        return adRepository.findAll();
    }

    public List<Ad> getPage(int pageNumber) {
        PageRequest request = new PageRequest(pageNumber - 1, PAGESIZE, Sort.Direction.ASC, "id");

        return adRepository.findAll(request).getContent();
    }
}
</code>```

答:
This should work

```<code>@Repository
public interface AdRepository extends PagingAndSortingRepository<Ad, Long> {
   List<Ad> findByPhoneNumberIsNull();
}
</code>```

You don't need the NameQuery you get the findAll for free from PagingAndSortingRepository

See the full documentation here

Title: Return rows with column not equals null

Body:
I have a working Spring Boot application, I'm vey new to JPA/Hibernate and I'm trying to retrieve results having one of the fields containing no null values. Right now I am getting everything including nulls.

It is phone_number_id that I don't want it to be null. I added nullable=false but it looks like it has no effect on retrievals.

What do I need to do to get only columns which have no null occurrences of phone_number_id

My Model

@Entity
@NamedQuery(name="Ad.findAll", query="SELECT a FROM Ad a")
public class Ad implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

    @Column(name="ad_content")
    private String adContent;

    @Column(name="ad_title")
    private String adTitle;

    @Column(name="ad_url")
    private String adUrl;

    private Integer age;

    @Column(name="post_id")
    private Long postId;

    //bi-directional many-to-one association to City
    @ManyToOne
    private City city;

    //bi-directional many-to-one association to PhoneNumber
    @ManyToOne
    @JoinColumn(name="phone_number_id", nullable=false)
    private PhoneNumber phoneNumber;

    //bi-directional many-to-one association to AdPhoto
    @OneToMany(mappedBy="ad")
    private List<AdPhoto> adPhotos;

    public Ad() {
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAdContent() {
        return this.adContent;
    }

    public void setAdContent(String adContent) {
        this.adContent = adContent;
    }

    public String getAdTitle() {
        return this.adTitle;
    }

    public void setAdTitle(String adTitle) {
        this.adTitle = adTitle;
    }

    public String getAdUrl() {
        return this.adUrl;
    }

    public void setAdUrl(String adUrl) {
        this.adUrl = adUrl;
    }

    public Integer getAge() {
        return this.age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Long getPostId() {
        return this.postId;
    }

    public void setPostId(Long postId) {
        this.postId = postId;
    }

    public City getCity() {
        return this.city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public PhoneNumber getPhoneNumber() {
        return this.phoneNumber;
    }

    public void setPhoneNumber(PhoneNumber phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public List<AdPhoto> getAdPhotos() {
        return this.adPhotos;
    }

    public void setAdPhotos(List<AdPhoto> adPhotos) {
        this.adPhotos = adPhotos;
    }

    public AdPhoto addAdPhoto(AdPhoto adPhoto) {
        getAdPhotos().add(adPhoto);
        adPhoto.setAd(this);

        return adPhoto;
    }

    public AdPhoto removeAdPhoto(AdPhoto adPhoto) {
        getAdPhotos().remove(adPhoto);
        adPhoto.setAd(null);

        return adPhoto;
    }

My repository

@Repository
public interface AdRepository extends PagingAndSortingRepository<Ad, Long> {

}

and my Service class

@Service
public class AdService {
    private final static int PAGESIZE = 3;

    @Autowired
    AdRepository adRepository;

    public Iterable<Ad> findAllAds() {
        return adRepository.findAll();
    }

    public List<Ad> getPage(int pageNumber) {
        PageRequest request = new PageRequest(pageNumber - 1, PAGESIZE, Sort.Direction.ASC, "id");

        return adRepository.findAll(request).getContent();
    }
}

Body:
This should work

@Repository
public interface AdRepository extends PagingAndSortingRepository<Ad, Long> {
   List<Ad> findByPhoneNumberIsNull();
}

You don't need the NameQuery you get the findAll for free from PagingAndSortingRepository

See the full documentation here


问:
How to access a class variable from a foreach in Javascript
I want to push data to  this.organizationIDList. I'm getting error undefined while pushing. How to push data to that variable?

```<code> class NewsScreen extends React.Component {
     render() {
         this.organizationIDList = [];

         this.organizations.forEach(function (organization) {
             this.organizationIDList.push(organization.id);
         });
     }
 }
</code>```

答:
Use arrow function

```<code>            this.organizations.forEach((organization) => {
                this.organizationIDList.push(organization.id);
            });
</code>```

Or pass this to forEach which accepts a thisArg

```<code>            this.organizations.forEach(function (organization) {
                this.organizationIDList.push(organization.id);
            }, this);
</code>```

The above code can also be written as:

```<code>this.organizationIdList = this.organizations.map(organization =>organization.id);
</code>```

Body:
I want to push data to  this.organizationIDList. I'm getting error undefined while pushing. How to push data to that variable?

 class NewsScreen extends React.Component {
     render() {
         this.organizationIDList = [];

         this.organizations.forEach(function (organization) {
             this.organizationIDList.push(organization.id);
         });
     }
 }

Body:
Use arrow function

            this.organizations.forEach((organization) => {
                this.organizationIDList.push(organization.id);
            });

Or pass this to forEach which accepts a thisArg

            this.organizations.forEach(function (organization) {
                this.organizationIDList.push(organization.id);
            }, this);

The above code can also be written as:

this.organizationIdList = this.organizations.map(organization =>organization.id);


问:
Partial template specialization of non type argument not allowed
The following code does not work, it gives an error saying "Too few template arguments for struct foo" and I do not understand why. To me it seems like the code should be valid. I found a snippet from CPP reference here in the section "The argument list", paragraph 4 which might explain why it does not work but I don't understand it.</p>

```<code>template<int a, int b, int c> struct foo { };
template<int a> struct foo<a, 0, 0> { };

int main()
{
    foo<1> f;
}
</code>```

答:
Note that the primary template takes 3 template parameters. Then you have to specify all of them. e.g.</p>

```<code>foo<1, 0, 0> f; // the partial specification is used
</code>```

Body:
The following code does not work, it gives an error saying "Too few template arguments for struct foo" and I do not understand why. To me it seems like the code should be valid. I found a snippet from CPP reference here in the section "The argument list", paragraph 4 which might explain why it does not work but I don't understand it.

template<int a, int b, int c> struct foo { };
template<int a> struct foo { };

int main()
{
    foo<1> f;
}

Body:
Note that the primary template takes 3 template parameters. Then you have to specify all of them. e.g.

foo<1, 0, 0> f; // the partial specification is used


问:
STRUTS2 - Value stack values are passed in URL!
I need a solution to hide or encode the "Value Stack" Values in URL.

The 'Value stack' values shows in URL if in struts.xml file the result was a jsp:
example

```<code> <action name="actionName" class="ActionClass">
      <result name="resultReturned">page.jsp</result>
    </action>
</code>```

I found 1 solution.
1) when we redirect to another ACTION, the values doesn't show in url.
Example:

```<code> <action...>
    <result name="resultReturned" type="redirectAction">ActionNameX</result>
    ..
    </action>

<action name="ActionNameX" >
...
</action>
</code>```

Is there any other solution?

Thank you !

答: You mean your form values are passed in the URL? Which in turn are set on the action and then become part of the value stack... Just use a plain html form with method="POST" although remember that hiding the URL values can make book marking difficult and really just makes you feel better, there is nothing more secure about it perhaps less as it may lull you into a false sense of security.</p>

Body:
I need a solution to hide or encode the "Value Stack" Values in URL.

The 'Value stack' values shows in URL if in struts.xml file the result was a jsp:
example

 <action name="actionName" class="ActionClass">
      <result name="resultReturned">page.jsp</result>
    </action>

I found 1 solution.
1) when we redirect to another ACTION, the values doesn't show in url.
Example:

 <action...>
    <result name="resultReturned" type="redirectAction">ActionNameX</result>
    ..
    </action>

<action name="ActionNameX" >
...
</action>

Is there any other solution?

Thank you !


问:
Combine two non-contiguous ranges for pivot table
If you have a table in excel all column headers are forced to be formatted as general text. I am trying to use a pivot table to reference the data in the table AND see the column headers as dates the only way to do this is to have a completely separate row somewhere else on the spreadsheet that's not part of the table but mirrors the columns with the exception of it being formatted as a date. Thus is my problem, I need to combine these two ranges to make a single range I can use as a value in the pivot table range.

```<code>OFFSET($B$11,0,0,ROWS(tblOther[#Data]),COLUMNS(tblOther[#Data]-2))
</code>```

and

```<code>OFFSET(tblOther[#Data],0,0,ROWS(tblOther[#Data]),COLUMNS(tblOther[#Data]-2))
</code>```

Thanks

答:
Again, all I can do is point you to two great ways I suggested you can mash multiple tables together at your other thread at Combine Multiple Tables Rows Into Master Table

One using PowerQuery, as Ralph suggests

One using VBA.

Now I know at that other thread that you didn't want a PQ or VBA solution, but neither of them is that hard, and I've given you a link to a previous answer with step-by-step pictures that shows how easy PQ is, and a generic VBA routine that is pretty simple to implement.

If you want easy ways to mash tables together, then they are pretty much it. If there's some reason you can't use one or both of those, post back and let me know what the reason is and I'll see if I can help you overcome it.

Body:
If you have a table in excel all column headers are forced to be formatted as general text. I am trying to use a pivot table to reference the data in the table AND see the column headers as dates the only way to do this is to have a completely separate row somewhere else on the spreadsheet that's not part of the table but mirrors the columns with the exception of it being formatted as a date. Thus is my problem, I need to combine these two ranges to make a single range I can use as a value in the pivot table range.

OFFSET($B$11,0,0,ROWS(tblOther[#Data]),COLUMNS(tblOther[#Data]-2))

and

OFFSET(tblOther[#Data],0,0,ROWS(tblOther[#Data]),COLUMNS(tblOther[#Data]-2))

Thanks


问:
Animate SVG on scroll
I'm animating an SVG line based on my scroll position. It works but the FPS is really low and the animation itself is laggy. I pretty sure it's my native Javascript skills that are screwing things up, but I don't know how to solve it.

I made a quick and dirty JSbin replica of what I currently have on the actual website;

http://jsbin.com/vigaqoxiru/edit?html,css,js,output

```<code>window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(f){setTimeout(f, 1000/60)}

document.addEventListener('DOMContentLoaded', function() {
    Timeline();
});

function Timeline() {
    requestAnimationFrame(animateLine)

    function convertRange( value, r1, r2 ) {
         return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
    }

    function animateLine() {
        var offset = window.scrollY;
        var wheight = window.innerHeight;
        var timeline = document.querySelector(".Approach--steps");
        var theight = timeline.getBoundingClientRect().top - wheight;

        if (theight < 0) {
            var timelineMin = timeline.offsetHeight;
            var objectMin = timeline.offsetTop;
            var objectMax = timeline.offsetTop + timeline.offsetHeight;

            document.querySelector(".Approach--timeline svg").setAttribute("style", "transform: scaleY(" + Math.floor(convertRange( (offset + wheight), [objectMin, objectMax], [0, 1.0]) * 100) / 100 + ")");
        }
    }

    window.addEventListener('scroll', function(){
        requestAnimationFrame(animateLine)
    });
}
</code>```

As you can see it's jumpy it doesn't scroll at 60fps, altho I'm using the scale attribute, requestAnimationFrame and rounded values. Any idea what a better way of implementing this animation is? Preferably without jQuery. GSAP is okay since I'm already running it.

答:
Why don't you add a transition time to make it work more smoothly?

```<code>.Approach--timeline svg {
    transition: .5s ease;
}
</code>```

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(f){setTimeout(f, 1000/60)}

document.addEventListener('DOMContentLoaded', function() {
    Timeline();
});

function Timeline() {
 requestAnimationFrame(animateLine)

    function convertRange( value, r1, r2 ) {
        return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
    }

    function animateLine() {
        var offset = window.scrollY;
        var wheight = window.innerHeight;
        var timeline = document.querySelector(".Approach--steps");
        var theight = timeline.getBoundingClientRect().top - wheight;

        if (theight < 0) {
            var timelineMin = timeline.offsetHeight;
            var objectMin = timeline.offsetTop;
            var objectMax = timeline.offsetTop + timeline.offsetHeight;

            document.querySelector(".Approach--timeline svg").setAttribute("style", "transform: scaleY(" + Math.floor(convertRange( (offset + wheight), [objectMin, objectMax], [0, 1.0]) * 100) / 100 + ")");
        }
    }

    window.addEventListener('scroll', function(){
        requestAnimationFrame(animateLine)
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Approach--steps {
  margin-top: 600px;
  margin-bottom: 200px
}

.Approach--header {
    margin-top: 80px;
}

.Approach--step {
    margin-top: 500px;
    padding-left: 56px;
}

.Approach--timeline {

}

.Approach--timeline svg {
    position: absolute;
    margin-top: -100px;
    height: 100%;
    width: 4px;
    transition: .5s ease;
    transform: scaleY(0);
    transform-origin: top left;
}

.Approach--steps {
    position: relative;
}</code>```

      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">
          <linearGradient id="grad" x1="0%" y1="0%" x2="0%" y2="100%" gradientUnits="userSpaceOnUse">
              <stop stop-color="#22D9BC" stop-opacity="1.0" offset="0%" />
              <stop stop-color="#1674F5" stop-opacity="1.0" offset="50%" />
              <stop stop-color="#7D00FF" stop-opacity="1.0" offset="100%" />
          </linearGradient>
          <rect x="0" y="0" width="1" height="1" fill="url(#grad)" id="Approach--svg" />
      </svg>

1. Khaled Ipsum

Lorem Khaled Ipsum is a major key to success. Eliptical talk. How’s business? Boomin. They will try to close the door on you, just open it. You see the hedges, how I got it shaped up? It’s important to shape up your hedges, it’s like getting a haircut, stay fresh. Wraith talk. We don’t see them, we will never see them. Life is what you make it, so let’s make it. Another one. Hammock talk come soon. It’s important to use cocoa butter. It’s the key to more success, why not live smooth? Why live rough?

2. Lion

The ladies always say Khaled you smell good, I use no cologne. Cocoa butter is the key. Hammock talk come soon. Put it this way, it took me twenty five years to get these plants, twenty five years of blood sweat and tears, and I’m never giving up, I’m just getting started. Major key, don’t fall for the trap, stay focused. It’s the ones closest to you that want to see you fail. The key to success is to keep your head above the water, never give up.

3. We the best

```

Title: Animate SVG on scroll

Body:
I'm animating an SVG line based on my scroll position. It works but the FPS is really low and the animation itself is laggy. I pretty sure it's my native Javascript skills that are screwing things up, but I don't know how to solve it.

I made a quick and dirty JSbin replica of what I currently have on the actual website;

http://jsbin.com/vigaqoxiru/edit?html,css,js,output

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(f){setTimeout(f, 1000/60)}

document.addEventListener('DOMContentLoaded', function() {
    Timeline();
});

function Timeline() {
    requestAnimationFrame(animateLine)

    function convertRange( value, r1, r2 ) {
         return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
    }

    function animateLine() {
        var offset = window.scrollY;
        var wheight = window.innerHeight;
        var timeline = document.querySelector(".Approach--steps");
        var theight = timeline.getBoundingClientRect().top - wheight;

        if (theight < 0) {
            var timelineMin = timeline.offsetHeight;
            var objectMin = timeline.offsetTop;
            var objectMax = timeline.offsetTop + timeline.offsetHeight;

            document.querySelector(".Approach--timeline svg").setAttribute("style", "transform: scaleY(" + Math.floor(convertRange( (offset + wheight), [objectMin, objectMax], [0, 1.0]) * 100) / 100 + ")");
        }
    }

    window.addEventListener('scroll', function(){
        requestAnimationFrame(animateLine)
    });
}

As you can see it's jumpy it doesn't scroll at 60fps, altho I'm using the scale attribute, requestAnimationFrame and rounded values. Any idea what a better way of implementing this animation is? Preferably without jQuery. GSAP is okay since I'm already running it.

Body:
Why don't you add a transition time to make it work more smoothly?

.Approach--timeline svg {
    transition: .5s ease;
}

window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(f){setTimeout(f, 1000/60)}

document.addEventListener('DOMContentLoaded', function() {
    Timeline();
});

function Timeline() {
 requestAnimationFrame(animateLine)

    function convertRange( value, r1, r2 ) {
        return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
    }

    function animateLine() {
        var offset = window.scrollY;
        var wheight = window.innerHeight;
        var timeline = document.querySelector(".Approach--steps");
        var theight = timeline.getBoundingClientRect().top - wheight;

        if (theight < 0) {
            var timelineMin = timeline.offsetHeight;
            var objectMin = timeline.offsetTop;
            var objectMax = timeline.offsetTop + timeline.offsetHeight;

            document.querySelector(".Approach--timeline svg").setAttribute("style", "transform: scaleY(" + Math.floor(convertRange( (offset + wheight), [objectMin, objectMax], [0, 1.0]) * 100) / 100 + ")");
        }
    }

    window.addEventListener('scroll', function(){
        requestAnimationFrame(animateLine)
    });
}

.Approach--steps {
  margin-top: 600px;
  margin-bottom: 200px
}

.Approach--header {
    margin-top: 80px;
}

.Approach--step {
    margin-top: 500px;
    padding-left: 56px;
}

.Approach--timeline {

}

.Approach--timeline svg {
    position: absolute;
    margin-top: -100px;
    height: 100%;
    width: 4px;
    transition: .5s ease;
    transform: scaleY(0);
    transform-origin: top left;
}

.Approach--steps {
    position: relative;
}

<div class="Approach--steps">
   <div class="Approach--timeline">
      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">
          <linearGradient id="grad" x1="0%" y1="0%" x2="0%" y2="100%" gradientUnits="userSpaceOnUse">
              <stop stop-color="#22D9BC" stop-opacity="1.0" offset="0%" />
              <stop stop-color="#1674F5" stop-opacity="1.0" offset="50%" />
              <stop stop-color="#7D00FF" stop-opacity="1.0" offset="100%" />
          </linearGradient>
          <rect x="0" y="0" width="1" height="1" fill="url(#grad)" id="Approach--svg" />
      </svg>
  </div>

  <div class="Approach--step">
      <p>1. Khaled Ipsum</p>
      <p>Lorem Khaled Ipsum is a major key to success. Eliptical talk. How’s business? Boomin. They will try to close the door on you, just open it. You see the hedges, how I got it shaped up? It’s important to shape up your hedges, it’s like getting a haircut, stay fresh. Wraith talk. We don’t see them, we will never see them. Life is what you make it, so let’s make it. Another one. Hammock talk come soon. It’s important to use cocoa butter. It’s the key to more success, why not live smooth? Why live rough?</p>
  </div>

  <div class="Approach--step">
      <p>2. Lion</p>
      <p>The ladies always say Khaled you smell good, I use no cologne. Cocoa butter is the key. Hammock talk come soon. Put it this way, it took me twenty five years to get these plants, twenty five years of blood sweat and tears, and I’m never giving up, I’m just getting started. Major key, don’t fall for the trap, stay focused. It’s the ones closest to you that want to see you fail. The key to success is to keep your head above the water, never give up.</p>
  </div>

  <div class="Approach--step">
      <p>3. We the best</p>
  </div>

</div>


问:
Get rid of NaN as key in python dictionary
I have a dictionary in which one key is a NaN, and I want to delete the key and its corresponding value. I have tried this:

```<code>from math import isnan

clean_dict = filter(lambda k: not isnan(k), dict_HMDB_ID)
</code>```

but the clean_dict is not a dictionary. I want to output it from python, but I get ''

答:
filter doesn't return a dictionary. It returns a list in Python 2 and a filter object in Python 3.

You can use dict.pop:

```<code>d = {'a': 1, 'b': 2}
print(d)
# {'a': 1, 'b': 2}
d.pop('b')
print(d)
# {'a': 1}
</code>```

And in your specific case,

```<code>dict_HMDB_ID.pop(float('NaN'))
</code>```

For the sake of completeness. it could be done with a dictionary comprehension but there is no point in iterating since keys are unique anyway

```<code>clean_dict = {k: v for k, v in dict_HMDB_ID.items() if not math.isnan(k)}
</code>```

If you insist on using filter here (you really shouldn't) you will need to:

pass it dict_HMDB_ID.items() so it will keep the original values

provide a custom function because it will now operate on (key, value) tuples.

transform the returned filter object (it will contain an iterator with (key, value) tuples) back to a dictionary

```<code>import math

dict_HMDB_ID = {1: 'a', float('Nan'): 'b'}
clean_dict = dict(filter(lambda tup: not math.isnan(tup[0]), dict_HMDB_ID.items()))
print(clean_dict)
# {1: 'a'}
</code>```

I should probably mention that the first approach (.pop) directly modifies the dict_HMDB_ID while the other two create a new dictionary. If you wish to use .pop and create a new dictionary (leaving dict_HMDB_ID as it is) you can create a new dictionary with dict:

```<code>d = {'a': 1, 'b': 2}
new_d = dict(d)
new_d.pop('b')
print(d)
# {'b': 2, 'a': 1}
print(new_d)
# {'a': 1}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dictionary in which one key is a NaN, and I want to delete the key and its corresponding value. I have tried this:

from math import isnan

clean_dict = filter(lambda k: not isnan(k), dict_HMDB_ID)

but the clean_dict is not a dictionary. I want to output it from python, but I get ''

Body:
filter doesn't return a dictionary. It returns a list in Python 2 and a filter object in Python 3.

You can use dict.pop:

d = {'a': 1, 'b': 2}
print(d)
# {'a': 1, 'b': 2}
d.pop('b')
print(d)
# {'a': 1}

And in your specific case,

dict_HMDB_ID.pop(float('NaN'))

For the sake of completeness. it could be done with a dictionary comprehension but there is no point in iterating since keys are unique anyway

clean_dict = {k: v for k, v in dict_HMDB_ID.items() if not math.isnan(k)}

If you insist on using filter here (you really shouldn't) you will need to:

pass it dict_HMDB_ID.items() so it will keep the original values

provide a custom function because it will now operate on (key, value) tuples.

transform the returned filter object (it will contain an iterator with (key, value) tuples) back to a dictionary

import math

dict_HMDB_ID = {1: 'a', float('Nan'): 'b'}
clean_dict = dict(filter(lambda tup: not math.isnan(tup[0]), dict_HMDB_ID.items()))
print(clean_dict)
# {1: 'a'}

I should probably mention that the first approach (.pop) directly modifies the dict_HMDB_ID while the other two create a new dictionary. If you wish to use .pop and create a new dictionary (leaving dict_HMDB_ID as it is) you can create a new dictionary with dict:

d = {'a': 1, 'b': 2}
new_d = dict(d)
new_d.pop('b')
print(d)
# {'b': 2, 'a': 1}
print(new_d)
# {'a': 1}


问:
Evict not working in Spring boot
I have a method that fetches all the data and i am caching the result of that method but i am not able to evict the result.

```<code>@Component("cacheKeyGenerator")
public class CacheKeyGenerator implements KeyGenerator {

    @Override
    public Object generate(Object target, Method method, Object... params) {
        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        return key;
    }
}
</code>```

CachedMethod:-

```<code> @Override
        @Cacheable(value="appCache",keyGenerator="cacheKeyGenerator")
        public List<Contact> showAllContacts() {
            return contactRepository.findAll();
        }

    @Override
        @CachePut(value="appCache",key="#result.id")
        public Contact addData(Contact contact) {
            return contactRepository.save(contact);
        }
</code>```

Now when ever addData is called i want the data in the cache "appCache" with the key ="cacheKeyGenerator" to be evicted.So that the data returned by the method "showAllContacts()" is accurate.Can anyone please help!

The Entire code can be found at - https://github.com/iftekharkhan09/SpringCaching

答:
Assuming you have a known constant cache key for showAllContacts then the solution should be to simply add @CacheEvict on addData passing in the cache name and key value:

```<code>@Override
@Caching(
    put = {@CachePut(value="appCache", key="#result.id")},
    evict = {@CacheEvict(cacheNames="appCache", key="someConstant")}
)
public Contact addData(Contact contact) {
    return contactRepository.save(contact);
}
</code>```

However because you use a key generator it is a bit more involved. Now given what your key generator does, you could instead pick a value for that cache key, making sure there can't be any collisions with the values from #result.id and use that value instead of a the key generator returned one.

Title: Evict not working in Spring boot

Body:
I have a method that fetches all the data and i am caching the result of that method but i am not able to evict the result.

@Component("cacheKeyGenerator")
public class CacheKeyGenerator implements KeyGenerator {

    @Override
    public Object generate(Object target, Method method, Object... params) {
        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        return key;
    }
}

CachedMethod:-

 @Override
        @Cacheable(value="appCache",keyGenerator="cacheKeyGenerator")
        public List<Contact> showAllContacts() {
            return contactRepository.findAll();
        }

    @Override
        @CachePut(value="appCache",key="#result.id")
        public Contact addData(Contact contact) {
            return contactRepository.save(contact);
        }

Now when ever addData is called i want the data in the cache "appCache" with the key ="cacheKeyGenerator" to be evicted.So that the data returned by the method "showAllContacts()" is accurate.Can anyone please help!

The Entire code can be found at - https://github.com/iftekharkhan09/SpringCaching

Body:
Assuming you have a known constant cache key for showAllContacts then the solution should be to simply add @CacheEvict on addData passing in the cache name and key value:

@Override
@Caching(
    put = {@CachePut(value="appCache", key="#result.id")},
    evict = {@CacheEvict(cacheNames="appCache", key="someConstant")}
)
public Contact addData(Contact contact) {
    return contactRepository.save(contact);
}

However because you use a key generator it is a bit more involved. Now given what your key generator does, you could instead pick a value for that cache key, making sure there can't be any collisions with the values from #result.id and use that value instead of a the key generator returned one.


问:
How to check two parameter($other and $user) of function in laravel repository?
How to check two parameter($other and $user) of function in laravel repository

I have this query:

```<code> public function GetFriend($other,$user)
 {
  $list = $this->makeModel()
        ->where(function ($query) {
            $query->where('otheruser',$other)
                  ->orWhere('user_id',$user);
        })
        ->get();
        return $list;
 }
</code>```

i have user table(MongoDB):

```<code>{
   _id : 59db41e78ed7bc5c0d000029,
   is_active : true
},
{
   _id : 59db41e78ed7bc5c0d000031,
   is_active : true
}
</code>```

I have friend table(MongoDB):

```<code>{
    _id : 1234567890,
    otheruser : 59db41e78ed7bc5c0d000031,
    user_id : 59db41e78ed7bc5c0d000029,
    is_friend : true
}
</code>```

答:
Pass the variables to the closure</p>

```<code> public function GetFriend($other, $user)
 {
      $list = $this->makeModel()
                   ->where(function ($query) use ($other, $user) {
                       $query->where('otheruser', $other)
                             ->orWhere('user_id', $user);
                   })->get();
      return $list;
 }
</code>```

Body:
How to check two parameter($other and $user) of function in laravel repository

I have this query:

 public function GetFriend($other,$user)
 {
  $list = $this->makeModel()
        ->where(function ($query) {
            $query->where('otheruser',$other)
                  ->orWhere('user_id',$user);
        })
        ->get();
        return $list;
 }

i have user table(MongoDB):

{
   _id : 59db41e78ed7bc5c0d000029,
   is_active : true
},
{
   _id : 59db41e78ed7bc5c0d000031,
   is_active : true
}

I have friend table(MongoDB):

{
    _id : 1234567890,
    otheruser : 59db41e78ed7bc5c0d000031,
    user_id : 59db41e78ed7bc5c0d000029,
    is_friend : true
}

Body:
Pass the variables to the closure

 public function GetFriend($other, $user)
 {
      $list = $this->makeModel()
                   ->where(function ($query) use ($other, $user) {
                       $query->where('otheruser', $other)
                             ->orWhere('user_id', $user);
                   })->get();
      return $list;
 }


问:
in iOS11 CBCentralManagerOptionShowPowerAlertKey it doesnot work
in iOS11 it doesnot work,how to solve this problem except write the alert by myself? I still want to use to system one</p>

答:
The missing system dialouge is filed in open radar: CBCentralManager does not prompt the user to turn on Bluetooth on iOS 11

It seems fixed with 11.1 but broken with 11.1.1 and then fixed with at least 11.2 beta 3.


问:
Function in a select option not triggering when using Chrome
I have the following select structure. The problem is that it works only in Firefox (last version). If I use Chrome (last version) for example, the onSelection() function won't trigger. The point of it is to select a node and save it in selectedNode for further use. I found people having similar issues but none of the solutions worked for me. Thanks in advance.

component.html

```<code><select  [(ngModel)]="selectedNode" required>
  <option *ngFor="let node of tenant.nodes" (click)="onSelection()" [ngValue]="node">{{node}}</option>
</select>
</code>```

component.ts

```<code>export class TESTComponent {
 selectedNode: string
 tenant: Tenant = {name:'asd',nodes:['node1','node2']};
}
</code>```

答:
First of all , (click)="onSelection()" should not be on option tag , and Second you need changed value so use (change) instead of (click)

```<code><select [(ngModel)]="selectedNode" (change)="onSelection()" required>
  <option *ngFor="let node of tenant.nodes" [ngValue]="node">{{node}}</option>
</select>
</code>```

Body:
I have the following select structure. The problem is that it works only in Firefox (last version). If I use Chrome (last version) for example, the onSelection() function won't trigger. The point of it is to select a node and save it in selectedNode for further use. I found people having similar issues but none of the solutions worked for me. Thanks in advance.

component.html

<select  [(ngModel)]="selectedNode" required>
  <option *ngFor="let node of tenant.nodes" (click)="onSelection()" [ngValue]="node">{{node}}</option>
</select>

component.ts

export class TESTComponent {
 selectedNode: string
 tenant: Tenant = {name:'asd',nodes:['node1','node2']};
}

Body:
First of all , (click)="onSelection()" should not be on option tag , and Second you need changed value so use (change) instead of (click)

<select [(ngModel)]="selectedNode" (change)="onSelection()" required>
  <option *ngFor="let node of tenant.nodes" [ngValue]="node">{{node}}</option>
</select>


答:
I am not an expert in algorithms, but as you only asked for some help and not the answer I believe I can submit an answer.

You need to figure out a way to test a space to determine if it is within a triangle. Once you have that I would design a brute force approach (run the "triangle test" against every space).

Then, when you have a brute force solution (which won't be an optimum approach) try and make it more efficient.
E.g. don't worry about being efficient or clever until you have a working solution.
Hope that helps.

Title: Triangles algorithm

Body:
I have this problem to solve:

The input is a number and a triangle, for example:

5
#-##----#
 -----#-
  ---#-
   -#-
    -

The number is count of rows of the triangle.

And I have to print the largest "triangle area" - the largest triangle made of -. For this one the answer is 9.

The triangle can also be upside down:

4
#-#-#--
 #---#
  ##-
   -

For this, the output is 4.

I need some help with the algorithm. Please give me just a little help, not the whole algorithm, because I want to try to solve it by myself, I just need a direction.


问:
AJAX post JSON data arrives empty
This is my AJAX request

```<code>data = JSON.stringify(data);
url = base_url + "index.php/home/make_order";
//alert(url);

var request = $.ajax({
  url: url,
  type: 'POST',
  contentType: 'application/json',
  data: data
});
request.done(function(response){
  alert('success');
});
request.fail(function(jqXHR, textStatus, errorThrown){
  alert('FAILED! ERROR: ' + errorThrown);
});
</code>```

My problem is that when it arrives to the PHP CI-controller $this->input->post('data'), it is empty.

This is my data: as shown before the AJAX request:

```<code>data = {"sum":"2.250","info":[{"id":"6","name":"bla","price":"1.000"}]}
</code>```

答:
I have extended the CI_Input class to allow using json.

Place this in application/core/MY_input.php and you can use $this->input->post() as usually.

```<code>class MY_Input extends CI_Input {

    public function __construct() {
        parent::__construct();
    }

    public function post($index = NULL, $xss_clean = NULL){
        if($xss_clean){
            $json = json_decode($this->security->xss_clean($this->raw_input_stream), true);
        } else {
            $json = json_decode($this->raw_input_stream, true);
        }
        if($json){
            if($index){
                return $json[$index] ?? NULL;
            }
            return $json;
        } else {
            return parent::post($index, $xss_clean);
        }
    }

}
</code>```

If you are using PHP5.x. Replace

```<code>return $json[$index] ?? NULL;
</code>```

with

```<code>return isset($json[$index]) ? $json[$index] : NULL;
</code>```

Title: AJAX post JSON data arrives empty

Body:
This is my AJAX request

data = JSON.stringify(data);
url = base_url + "index.php/home/make_order";
//alert(url);

var request = $.ajax({
  url: url,
  type: 'POST',
  contentType: 'application/json',
  data: data
});
request.done(function(response){
  alert('success');
});
request.fail(function(jqXHR, textStatus, errorThrown){
  alert('FAILED! ERROR: ' + errorThrown);
});

My problem is that when it arrives to the PHP CI-controller $this->input->post('data'), it is empty.

This is my data: as shown before the AJAX request:

data = {"sum":"2.250","info":[{"id":"6","name":"bla","price":"1.000"}]}

Body:
I have extended the CI_Input class to allow using json.

Place this in application/core/MY_input.php and you can use $this->input->post() as usually.

class MY_Input extends CI_Input {

    public function __construct() {
        parent::__construct();
    }

    public function post($index = NULL, $xss_clean = NULL){
        if($xss_clean){
            $json = json_decode($this->security->xss_clean($this->raw_input_stream), true);
        } else {
            $json = json_decode($this->raw_input_stream, true);
        }
        if($json){
            if($index){
                return $json[$index] ?? NULL;
            }
            return $json;
        } else {
            return parent::post($index, $xss_clean);
        }
    }

}

If you are using PHP5.x. Replace

return $json[$index] ?? NULL;

with

return isset($json[$index]) ? $json[$index] : NULL;


问:
Update SQL with consecutive numbering
I want to update a table with consecutive numbering starting with 1. The update has a where clause so only results that meet the clause will be renumbered.  Can I accomplish this efficiently without using a temp table?</p>

答:
As well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:

```<code>UPDATE a
SET a.columnToBeSet = b.sequence
FROM tableXxx a
INNER JOIN
(
   SELECT ROW_NUMBER() OVER ( ORDER BY columnX ) AS sequence, columnY, columnZ
   FROM tableXxx
   WHERE columnY = @groupId AND columnY = @lang2
) b ON b.columnY = a.columnY AND b.columnZ = a.columnZ
</code>```

The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with some other columns which form a virtual primary key.
Typically, each row will require a unique sequence value.

The WHERE clause is optional and limits the update to those rows that satisfy the specified conditions.

The derived table is then joined to the same table, alias a, joining on the virtual primary key columns with the column to be updated set to the generated sequence.

Title: Update SQL with consecutive numbering

Body:
As well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:

UPDATE a
SET a.columnToBeSet = b.sequence
FROM tableXxx a
INNER JOIN
(
   SELECT ROW_NUMBER() OVER ( ORDER BY columnX ) AS sequence, columnY, columnZ
   FROM tableXxx
   WHERE columnY = @groupId AND columnY = @lang2
) b ON b.columnY = a.columnY AND b.columnZ = a.columnZ

The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with some other columns which form a virtual primary key.
Typically, each row will require a unique sequence value.

The WHERE clause is optional and limits the update to those rows that satisfy the specified conditions.

The derived table is then joined to the same table, alias a, joining on the virtual primary key columns with the column to be updated set to the generated sequence.


问:
Numbers are not correctly added up
I want to compute some number for each given day. The actual number does not matter, it should just be somewhat different but it must be stable.

So I have done the following so far:

```<code>now = new Date();

begin_of_week = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1);

for (idx in [0, 1, 2, 3, 4]) {
    seed = parseInt(idx)
        + begin_of_week.getFullYear() * 400,
        + begin_of_week.getMonth() * 31,
        + begin_of_week.getDate();

    // ...
}
</code>```

I expect that this gives me some seed for each day of the week from Monday to Friday. However, I different numbers for the days, but I now have the same numbers as last week.

JavaScript's type system is a mystery to me. I would expect that all those are int and they just get added up. It makes a difference whether I put the idx at the beginning or the end of the chain. And the parseInt, which should do nothing, actually changes the results.

What is going on here? How can I just add those numbers?

答:
I expect that this gives me some seed for each day of the week from
  Monday to Friday. However, I different numbers for the days, but I now
  have the same numbers as last week.

This is because your begin_of_week is going to be same for entire week as you have given

```<code>now.getDate() - now.getDay() + 1
</code>```

which essentially ensures that your date parameter is always offset'ed by number of days passed already in the week.

I would expect that all those are int and they just get added up.

You are assigning the value to seed rather than incrementing the seed value by the other values, so this is as good as

```<code>seed = parseInt(4)
        + begin_of_week.getFullYear() * 400,
        + begin_of_week.getMonth() * 31,
        + begin_of_week.getDate();
</code>```

If you want to keep incrementing seed value, then use += instead of =

Title: Numbers are not correctly added up

Body:
I want to compute some number for each given day. The actual number does not matter, it should just be somewhat different but it must be stable.

So I have done the following so far:

now = new Date();

begin_of_week = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1);

for (idx in [0, 1, 2, 3, 4]) {
    seed = parseInt(idx)
        + begin_of_week.getFullYear() * 400,
        + begin_of_week.getMonth() * 31,
        + begin_of_week.getDate();

    // ...
}

I expect that this gives me some seed for each day of the week from Monday to Friday. However, I different numbers for the days, but I now have the same numbers as last week.

JavaScript's type system is a mystery to me. I would expect that all those are int and they just get added up. It makes a difference whether I put the idx at the beginning or the end of the chain. And the parseInt, which should do nothing, actually changes the results.

What is going on here? How can I just add those numbers?

Body:
I expect that this gives me some seed for each day of the week from
  Monday to Friday. However, I different numbers for the days, but I now
  have the same numbers as last week.

This is because your begin_of_week is going to be same for entire week as you have given

now.getDate() - now.getDay() + 1

which essentially ensures that your date parameter is always offset'ed by number of days passed already in the week.

I would expect that all those are int and they just get added up.

You are assigning the value to seed rather than incrementing the seed value by the other values, so this is as good as

seed = parseInt(4)
        + begin_of_week.getFullYear() * 400,
        + begin_of_week.getMonth() * 31,
        + begin_of_week.getDate();

If you want to keep incrementing seed value, then use += instead of =


问:
Alternate of like in oracle select query
I have a table with single column.
 TABLE T with data like:

```<code> A11
B1
As112
DF123
VG112
</code>```

I'm lookingfor alternate of like (VG% and DF%) ... Because i think if there will be more to compare it may effect performance

答:
I think that like is the best choice. You can create list of patterns and use join, like here:

```<code>select * from t join p on t.text like p.pattern||'%'
</code>```

It does not matter if you use built-in type odcivarchar2list or define patterns using union all, it only makes syntax shorter.

Example:

```<code>with t(text) as (
    select column_value
      from table(sys.odcivarchar2list('A11', 'B1', 'As112', 'DF123', 'VG112'))),
p(pattern) as (
    select column_value
      from table(sys.odcivarchar2list('DF', 'VG')))
select *
  from t join p on t.text like p.pattern||'%'

TEXT    PATTERN
------  -------
DF123   DF
VG112   VG
</code>```

Body:
I have a table with single column.
 TABLE T with data like:

 A11
B1
As112
DF123
VG112

I'm lookingfor alternate of like (VG% and DF%) ... Because i think if there will be more to compare it may effect performance

Body:
I think that like is the best choice. You can create list of patterns and use join, like here:

select * from t join p on t.text like p.pattern||'%'

It does not matter if you use built-in type odcivarchar2list or define patterns using union all, it only makes syntax shorter.

Example:

with t(text) as (
    select column_value
      from table(sys.odcivarchar2list('A11', 'B1', 'As112', 'DF123', 'VG112'))),
p(pattern) as (
    select column_value
      from table(sys.odcivarchar2list('DF', 'VG')))
select *
  from t join p on t.text like p.pattern||'%'

TEXT    PATTERN
------  -------
DF123   DF
VG112   VG


问:
Call a class method as soon as an object it extends is created
Assume we have the following class (simplified):

```<code>class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

```<code>class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}
</code>```

and I could access the properties in the child class like this:

```<code>class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}
</code>```

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

```<code>class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

答:
```<code>class SuperConfig {
    public $mainDir;

    public function __construct() {
        $this->setDir();  // consider moving setDir's code here as well,
                          // unless you have a good reason for it to be a method
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}
</code>```

You simply do this, and then you expect all subclasses to call the parent constructor if they're overriding the constructor:

```<code>public function __construct() {
    parent::__construct();
    // more code
}
</code>```

It's perfectly reasonable to expect children to call their parent constructor, unless they deliberately want to leave the instance in an unknown and potentially broken state.

Body:
Assume we have the following class (simplified):

class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}

and I could access the properties in the child class like this:

class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

Body:
class SuperConfig {
    public $mainDir;

    public function __construct() {
        $this->setDir();  // consider moving setDir's code here as well,
                          // unless you have a good reason for it to be a method
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

You simply do this, and then you expect all subclasses to call the parent constructor if they're overriding the constructor:

public function __construct() {
    parent::__construct();
    // more code
}

It's perfectly reasonable to expect children to call their parent constructor, unless they deliberately want to leave the instance in an unknown and potentially broken state.


答:
It's not how template specialization works. You have* to specify all arguments.

*(Except when you have default arguments (see @StoryTeller's answer), or when C++17 argument deduction kicks in, but both don't apply here.)

Here's a small demo:

```<code>#include <iostream>

template<int a, int b, int c> struct foo { void bar() {std::cout << "1\n";} };
template<int a> struct foo<a, 0, 0> { void bar() {std::cout << "2\n";} };

int main()
{
    foo<1, 2, 3> a;
    foo<4, 0, 0> b;
    a.bar(); // prints 1
    b.bar(); // prints 2
}
</code>```

Title: Partial template specialization of non type argument not allowed

Body:
The following code does not work, it gives an error saying "Too few template arguments for struct foo" and I do not understand why. To me it seems like the code should be valid. I found a snippet from CPP reference here in the section "The argument list", paragraph 4 which might explain why it does not work but I don't understand it.

template<int a, int b, int c> struct foo { };
template<int a> struct foo { };

int main()
{
    foo<1> f;
}

Body:
It's not how template specialization works. You have* to specify all arguments.

*(Except when you have default arguments (see @StoryTeller's answer), or when C++17 argument deduction kicks in, but both don't apply here.)

Here's a small demo:

#include <iostream>

template<int a, int b, int c> struct foo { void bar() {std::cout << "1\n";} };
template<int a> struct foo<a, 0, 0> { void bar() {std::cout << "2\n";} };

int main()
{
    foo<1, 2, 3> a;
    foo<4, 0, 0> b;
    a.bar(); // prints 1
    b.bar(); // prints 2
}


问:
Why a struct declared by let can be changed?
In the following code, 'ptr' is a struct declared by let, but its member variable 'pointee' could be changed, Why?

    let ptr = UnsafeMutablePointer<Int>.allocate(capacity:1)
    ptr.pointee = 1

答: Here, ptr is constant, so you cannot assign a new UnsafeMutablePointer to it, but the structure it holds within can be modified. In short, you cannot reassign anything to a let entity, but you can access and modify its properties.


问:
Angular2: How to enable save button if any model value changed on edit page
I am new for angular 2. I have a page where we can edit details of customer profile. How to enable save button if any property of has been changed. I know it is possible in angular1 by using $watch.</p>

答:
Finally I resolved this issue.</p>

```<code>import { Component, Input, Output, OnInit, AfterViewInit, EventEmitter, ViewChild } from '@angular/core';

@Component({
  selector: 'subscribe-modification',
  templateUrl: './subscribe.component.html'
})

export class SampleModifyComponent implements OnInit, AfterViewInit {
disableSaveSampleButton: boolean = true;
@ViewChild('sampleModifyForm') sampleForm;

ngAfterViewInit() {
    setTimeout(() => {
            this.sampleForm.control.valueChanges.subscribe(values => this.enableSaveSampleButton());
    }, 1000);
}

enableSaveSampleButton() {
    console.log('change');
    this.disableSaveSampleButton = false;
   }
}

HTML
<button id="btnSave" class="btn btn-primary" (click)="save()" />
</code>```

Body:
Finally I resolved this issue.

import { Component, Input, Output, OnInit, AfterViewInit, EventEmitter, ViewChild } from '@angular/core';

@Component({
  selector: 'subscribe-modification',
  templateUrl: './subscribe.component.html'
})

export class SampleModifyComponent implements OnInit, AfterViewInit {
disableSaveSampleButton: boolean = true;
@ViewChild('sampleModifyForm') sampleForm;

ngAfterViewInit() {
    setTimeout(() => {
            this.sampleForm.control.valueChanges.subscribe(values => this.enableSaveSampleButton());
    }, 1000);
}

enableSaveSampleButton() {
    console.log('change');
    this.disableSaveSampleButton = false;
   }
}

HTML
<button id="btnSave" class="btn btn-primary" (click)="save()" />


问:
Base 62 conversion
How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').

I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.

答:
I have benefited greatly from others' posts here. I needed the python code originally for a Django project, but since then I have turned to node.js, so here's a javascript version of the code (the encoding part) that Baishampayan Ghose provided.

```<code>var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

function base62_encode(n, alpha) {
  var num = n || 0;
  var alphabet = alpha || ALPHABET;

  if (num == 0) return alphabet[0];
  var arr = [];
  var base = alphabet.length;

  while(num) {
    rem = num % base;
    num = (num - rem)/base;
    arr.push(alphabet.substring(rem,rem+1));
  }

  return arr.reverse().join('');
}

console.log(base62_encode(2390687438976, "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"));
</code>```

Title: Base 62 conversion

Body:
I have benefited greatly from others' posts here. I needed the python code originally for a Django project, but since then I have turned to node.js, so here's a javascript version of the code (the encoding part) that Baishampayan Ghose provided.

var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

function base62_encode(n, alpha) {
  var num = n || 0;
  var alphabet = alpha || ALPHABET;

  if (num == 0) return alphabet[0];
  var arr = [];
  var base = alphabet.length;

  while(num) {
    rem = num % base;
    num = (num - rem)/base;
    arr.push(alphabet.substring(rem,rem+1));
  }

  return arr.reverse().join('');
}

console.log(base62_encode(2390687438976, "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"));


问:
How to access a class variable from a foreach in Javascript
I want to push data to  this.organizationIDList. I'm getting error undefined while pushing. How to push data to that variable?

```<code> class NewsScreen extends React.Component {
     render() {
         this.organizationIDList = [];

         this.organizations.forEach(function (organization) {
             this.organizationIDList.push(organization.id);
         });
     }
 }
</code>```

答:
Use arrow function like below</p>

```<code>this.organizations.forEach((organization) => {
   this.organizationIDList.push(organization.id);
});
</code>```

Body:
I want to push data to  this.organizationIDList. I'm getting error undefined while pushing. How to push data to that variable?

 class NewsScreen extends React.Component {
     render() {
         this.organizationIDList = [];

         this.organizations.forEach(function (organization) {
             this.organizationIDList.push(organization.id);
         });
     }
 }

Body:
Use arrow function like below

this.organizations.forEach((organization) => {
   this.organizationIDList.push(organization.id);
});


问:
Vue: Update Component data from Vue instance
I want to update data in a component from my Vue instance. Finding plenty of examples on how to do the opposite, but nothing on this.

Say I have:

```<code>Vue.component('component', {
props: {
    prop: {
        default: null
    }
},
template: '#template',
data: function () {
    return {
        open: false
    };
}
});
</code>```

Now I would like to set open to true from my Vue instance:

```<code>var root = new Vue({
    el: '#root',
    data: {},
    methods: { updateComponentData: function() {//set open to true} } });
</code>```

答:
I just played with your code and the following codes works perfect please do try that. I have used Vue 'ref'. Add ref attribute in your component and then you can access that specific components data from parent.

Vue.component('component', {
    props: {
        prop: {
            default: null
        }
    },
    template: '#template',
    data: () => ({
        open: false
    })
});
var root = new Vue({
    el: '#root',
    data: () => ({}),
    methods: {
        updateComponentData: function() {
         this.$refs.myComponent.open = true
        }
    },
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue"></script>
<div id="root">
   <button @click="updateComponentData">Change</button>
    <hr>
    <component ref='myComponent'></component>
</div>
<script type="text/x-template" id="template" ref="component">
    <div>Open: {{ open }}!</div>
</script></code>```

Body:
I want to update data in a component from my Vue instance. Finding plenty of examples on how to do the opposite, but nothing on this.

Say I have:

Vue.component('component', {
props: {
    prop: {
        default: null
    }
},
template: '#template',
data: function () {
    return {
        open: false
    };
}
});

Now I would like to set open to true from my Vue instance:

var root = new Vue({
    el: '#root',
    data: {},
    methods: { updateComponentData: function() {//set open to true} } });

Body:
I just played with your code and the following codes works perfect please do try that. I have used Vue 'ref'. Add ref attribute in your component and then you can access that specific components data from parent.

Vue.component('component', {
    props: {
        prop: {
            default: null
        }
    },
    template: '#template',
    data: () => ({
        open: false
    })
});
var root = new Vue({
    el: '#root',
    data: () => ({}),
    methods: {
        updateComponentData: function() {
         this.$refs.myComponent.open = true
        }
    },
});

<script src="https://unpkg.com/vue"></script>
<div id="root">
   <button @click="updateComponentData">Change</button>
    <hr>
    <component ref='myComponent'></component>
</div>
<script type="text/x-template" id="template" ref="component">
    <div>Open: {{ open }}!</div>
</script>