问:
Clip-path not working with z-index
I am having trouble placing a container on top of another container that uses a clipped-path. I have tried using z-index on either of the containers but it doesn't seem to help.

If I remove the clipped-path class from the container then the block slides happily over the container. I have included a fiddle of my problem.

Here is my code:

window.onscroll = function(){
  var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  var para = Math.round(scrollTop / 1.2);
  document.querySelector('#block').style.transform = "translate3d(0px," + para + "px,0px)";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {margin: 5px;}

#main {height:100vh;}
#below-main {height:100vh;}
#row1 {height:100vh;}

/* Paralellogram to slide underneath block
--------------------------------------------- */
#bluestripe {
  height: 60vh;
  width:60vw;
  margin: 0 auto;
}

img {width: 100%;}

.clip-polygon {clip-path: polygon(100% 0, 100% 40%, 0 100%, 0 60%);}

/* Block to sit above parallelogram
--------------------------------------------- */
#block {
  height: 50px;
  width:100px;
  margin: 50px auto 0 auto;
  transform: translate3d(0px,0px,0px);
  background-color: #999;
}</code>```

This needs to slide on top

```

答:
To affect an element's z-index, it must have position set to something other than static (the default).

In the case of your #block, it has no position set, so it is using the layer implied by the element's order in the source: it appears in your source before your clipped element, and naturally settles below it.

To position it on a higher z-index in the stack, give it a position and a z-index:

```<code>#block {
    height: 50px;
    width: 100px;
    margin: 50px auto 0 auto;
    transform: translate3d(0px,95px,0px);
    background-color: #999;
    position: relative; /* Allows z-index to take affect */
    z-index: 2; /* Stacks it above the clipped layer, which has no position nor z-index and is at z-index 1 */
}
</code>```

Title: Clip-path not working with z-index

Body:
I am having trouble placing a container on top of another container that uses a clipped-path. I have tried using z-index on either of the containers but it doesn't seem to help.

If I remove the clipped-path class from the container then the block slides happily over the container. I have included a fiddle of my problem.

Here is my code:

window.onscroll = function(){
  var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  var para = Math.round(scrollTop / 1.2);
  document.querySelector('#block').style.transform = "translate3d(0px," + para + "px,0px)";
}

body {margin: 5px;}

#main {height:100vh;}
#below-main {height:100vh;}
#row1 {height:100vh;}

/* Paralellogram to slide underneath block
--------------------------------------------- */
#bluestripe {
  height: 60vh;
  width:60vw;
  margin: 0 auto;
}

img {width: 100%;}

.clip-polygon {clip-path: polygon(100% 0, 100% 40%, 0 100%, 0 60%);}

/* Block to sit above parallelogram
--------------------------------------------- */
#block {
  height: 50px;
  width:100px;
  margin: 50px auto 0 auto;
  transform: translate3d(0px,0px,0px);
  background-color: #999;
}

This needs to slide on top

Body:
To affect an element's z-index, it must have position set to something other than static (the default).

In the case of your #block, it has no position set, so it is using the layer implied by the element's order in the source: it appears in your source before your clipped element, and naturally settles below it.

To position it on a higher z-index in the stack, give it a position and a z-index:

#block {
    height: 50px;
    width: 100px;
    margin: 50px auto 0 auto;
    transform: translate3d(0px,95px,0px);
    background-color: #999;
    position: relative; /* Allows z-index to take affect */
    z-index: 2; /* Stacks it above the clipped layer, which has no position nor z-index and is at z-index 1 */
}


来源: stackexchange

问:
How to convert an array of char to array of int
Is there a way to convert an array of char to array of int32 without iterating every member.

I need to convert a huge amount of data so I'm looking for some faster than:

```<code>char ac[1000000];
int32_t ai[1000000];
for(int i=0;i<1000000;i++) {
    ai[i]=ac[i];
}
</code>```

Notes:

I'm not asking about how to convert '3' to 0x03, I'm talking about convert 0x03 (one byte) to 0x00000003 (to  4 bytes)

Not portable is not a problem (platform linux AMD64).

The proposed method is slow.

looking for a library that use SSE instructions or similar.
I need it to feed a math function that works with int32 numbers and my original data is in 8 bits size, so I need to convert it, and obviously I can't cast because is an memory area not a value.

答:
Not sure if this will be faster, you have to check (also it will be depend on the sizeof(int) == 4):</p>

```<code>// note: untested
char ac[1000000];
int ai[1000000];
memset(ai, 0, sizeof(int) * 1000000); // this should be very fast
char * d = (char *) (ai + 3); // go to last byte of the first int
for(int i=0;i<1000000;i++) {
    d += 4; // go to last byte of the next int
    *d=ac[i];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to convert an array of char to array of int32 without iterating every member.

I need to convert a huge amount of data so I'm looking for some faster than:

char ac[1000000];
int32_t ai[1000000];
for(int i=0;i<1000000;i++) {
    ai[i]=ac[i];
}

Notes:

I'm not asking about how to convert '3' to 0x03, I'm talking about convert 0x03 (one byte) to 0x00000003 (to  4 bytes)

Not portable is not a problem (platform linux AMD64).

The proposed method is slow.

looking for a library that use SSE instructions or similar.
I need it to feed a math function that works with int32 numbers and my original data is in 8 bits size, so I need to convert it, and obviously I can't cast because is an memory area not a value.

Body:
Not sure if this will be faster, you have to check (also it will be depend on the sizeof(int) == 4):

// note: untested
char ac[1000000];
int ai[1000000];
memset(ai, 0, sizeof(int) * 1000000); // this should be very fast
char * d = (char *) (ai + 3); // go to last byte of the first int
for(int i=0;i<1000000;i++) {
    d += 4; // go to last byte of the next int
    *d=ac[i];
}


问:
Swift launch waze from webview link
I have a webview which is connected to a url, on this url there is a link that when clicked, should open waze with an adress. on safari it works fine but when I try to open it through my webview it doesn't seem to work. is there any way to do that?</p>

答:
To open the link externally, you'll need to set the UIWebViewDelegate for the webview.

Then, implement:

```<code>func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
</code>```

From there, you can grab the URL out of the URLRequest and open the link externally.

Then, you can call func open(_ url: URL, options: [String : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil) on your UIApplication with the URL from the webview.

Title: Swift launch waze from webview link

Body:
To open the link externally, you'll need to set the UIWebViewDelegate for the webview.

Then, implement:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool

From there, you can grab the URL out of the URLRequest and open the link externally.

Then, you can call func open(_ url: URL, options: [String : Any] = [:], completionHandler completion: ((Bool) -> Void)? = nil) on your UIApplication with the URL from the webview.


问:
How to display loading spinner during image load with Url.Action Method in Razor/C#?
I'm currently loading an image through an API call in my Index.cshtml with this code:

```<code><img src="@Url.Action("ImageFromAPI")" width="500px" />
</code>```

This calls my HomeController.cs:

```<code>public ActionResult ImageFromAPI()
{
    var client = new RestClient("http://IP-ADDRESS/snapshot.cgi?channel=0");
    var request = new RestRequest(Method.GET);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("authorization", "Basic Xwjk15j5oi1gsdg");
    IRestResponse response = client.Execute(request);

    if (response == null)
    {
        var ms = new MemoryStream();
        using (Bitmap bitmap = new Bitmap("~/img/404.jpg"))
        {
            bitmap.Save(ms, ImageFormat.Jpeg);
        }

        ms.Position = 0;
        return File(ms, "image/jpg");
    }
    else
    {
        return File(response.RawBytes, "image/png");
    }
}
</code>```

To explain what's going on - I'm calling my API through the RestClient and seeing if it returns something. If so, I output the image to the page, if not, I output the 404 jpg to the page.

The problem is, during the Url.Action call (sometimes it takes more than just a second or two), there's no "Image is loading.." substitute.

Is there a proper way to do this? Any/or is there a better way?

答: I would not load the image directly from a call to the server side.  I would set all images being loaded to some "loading" image on page load and create some functionality with your client side framework to make a call to this action on your server side and replace the loading image with the fully loaded image once it has been received by the client side.</p>

Body:
I'm currently loading an image through an API call in my Index.cshtml with this code:

This calls my HomeController.cs:

public ActionResult ImageFromAPI()
{
    var client = new RestClient("http://IP-ADDRESS/snapshot.cgi?channel=0");
    var request = new RestRequest(Method.GET);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("authorization", "Basic Xwjk15j5oi1gsdg");
    IRestResponse response = client.Execute(request);

    if (response == null)
    {
        var ms = new MemoryStream();
        using (Bitmap bitmap = new Bitmap("~/img/404.jpg"))
        {
            bitmap.Save(ms, ImageFormat.Jpeg);
        }

        ms.Position = 0;
        return File(ms, "image/jpg");
    }
    else
    {
        return File(response.RawBytes, "image/png");
    }
}

To explain what's going on - I'm calling my API through the RestClient and seeing if it returns something. If so, I output the image to the page, if not, I output the 404 jpg to the page.

The problem is, during the Url.Action call (sometimes it takes more than just a second or two), there's no "Image is loading.." substitute.

Is there a proper way to do this? Any/or is there a better way?


问:
UIView - Center alignment all the contents of UIView?
How to center alignment all the contents of view. When i am rotating iPad contents are not align center it self how to resolve this problem??

Thanks!!!

答:
Provide an implementation of the didRotateFromInterfaceOrientation method and center all subviews.

```<code>- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    for(UIView *subview in [self.view subviews]) {
        subview.center = self.view.center;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Provide an implementation of the didRotateFromInterfaceOrientation method and center all subviews.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    for(UIView *subview in [self.view subviews]) {
        subview.center = self.view.center;
    }
}


问:
Flask Admin Custom Form Validation for Multiple Fields?
I have been intending to create a custom form validation logic that's based on multiple field values (in my case, 2 fields to ensure date range data integrity is ensured, I.E. start_time < end_time). However, flipping through the documentation on flask admin site, I couldn't find anywhere to do this sort of stuff. I am aware of that you can pretty trivially pass a list of validation functions to validators argument for form_args property in a subclass of a BaseModelView class, but again, that's per-field validation not exactly what I want.

So my question is this: how does one validate multiple fields together at once?

Also, I don't see any pre-save hook event function to tap into do do this. I am aware of on_model_change but then it's a post-save hook, it would defeat the purpose of validation to put the validation in there. What would be the appropriate the way go about doing pre-save actions?

答:
You can introduce custom form validation code to your flask admin model views by using inheritance and a custom "validate_form" method that incorporates your validation code before calling the parent "validate form".

If your validation logic finds a problem, your validate_form should display an appropriate error message and return False, otherwise it should continue by running the original flask admin validation form code.

from flask_admin.contrib.sqla import ModelView
from flask import flash

class MyModelView(ModelView):
    """ My model admin model view """

    def validate_form(self, form):
        """ Custom validation code that checks dates """
        if form.start_time.data > form.end_time.data:
            flash("start time cannot be greater than end time!")
            return False
        return super(MyModelView, self).validate_form(form)
```

This is a much more natural place to do form validation than at the change_model_model method, which shouldn't be concerned with model logic, not form validation logic. Also, note we don't need to use an exception and rely on reversing the transaction. We simply catch the error before any transaction has occurred, flash an error message and gracefully return a "False" state.

Relevant links:

flask admin documentation

flask admin source code

Body:
You can introduce custom form validation code to your flask admin model views by using inheritance and a custom "validate_form" method that incorporates your validation code before calling the parent "validate form".

If your validation logic finds a problem, your validate_form should display an appropriate error message and return False, otherwise it should continue by running the original flask admin validation form code.

from flask_admin.contrib.sqla import ModelView
from flask import flash

class MyModelView(ModelView):
    """ My model admin model view """

    def validate_form(self, form):
        """ Custom validation code that checks dates """
        if form.start_time.data > form.end_time.data:
            flash("start time cannot be greater than end time!")
            return False
        return super(MyModelView, self).validate_form(form)

This is a much more natural place to do form validation than at the change_model_model method, which shouldn't be concerned with model logic, not form validation logic. Also, note we don't need to use an exception and rely on reversing the transaction. We simply catch the error before any transaction has occurred, flash an error message and gracefully return a "False" state.

Relevant links:

flask admin documentation

flask admin source code


问:
The trait `FnMut<(char,)>` is not implemented for `String` when trying to split a string
I need to split a String (not &str) by another String:

```<code>use std::str::Split;

fn main() {
    let x = "".to_string().split("".to_string());
}
</code>```

Why do I get this error and how to avoid it if I already have to operate on strings?

error[E0277]: the trait bound `std::string::String: std::ops::FnMut<(char,)>` is not satisfied
 --> src/main.rs:4:32
  |
4 |         let x = "".to_string().split("".to_string());
  |                                ^^^^^ the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
  |
  = note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`
```

According to the #rust-beginners IRC channel, this might be an example of Deref failing in 1.20.0-nightly. How to split a string in Rust? doesn't address the problem of splitting by String, not &str.

答:
All is in the documentation. You can provide one of:

A &str,

A char,

A closure,

Those three types implement the Pattern trait. You are giving  a String to split instead of a &str.

Example:

```<code>fn main() {
    let x = "".to_string();
    let split = x.split("");
}
</code>```

Body:
I need to split a String (not &str) by another String:

use std::str::Split;

fn main() {
    let x = "".to_string().split("".to_string());
}

Why do I get this error and how to avoid it if I already have to operate on strings?

error[E0277]: the trait bound `std::string::String: std::ops::FnMut<(char,)>` is not satisfied
 --> src/main.rs:4:32
  |
4 |         let x = "".to_string().split("".to_string());
  |                                ^^^^^ the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
  |
  = note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`

According to the #rust-beginners IRC channel, this might be an example of Deref failing in 1.20.0-nightly. How to split a string in Rust? doesn't address the problem of splitting by String, not &str.

Body:
All is in the documentation. You can provide one of:

A &str,

A char,

A closure,

Those three types implement the Pattern trait. You are giving  a String to split instead of a &str.

Example:

fn main() {
    let x = "".to_string();
    let split = x.split("");
}


问:
Retrofit response Cache
There are a lot of complex answers here about Retrofit cache but none seem to help me.

How do I cache my code response coming from the Retrofit response?

My App works fine downloading the JSON below but I need to make a cache for it and I never did cache on Android.

I need to open the App offline and get the result from my Retrofit call as if I was online.

```<code>public class APIClient {

public static final String BASE_URL = "https://raw.githubusercontent.com/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client = httpClient.build();
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }
    return retrofit;
}}
</code>```

The json response is VERY simple:

{
   "fruits":[
      {
         "name":"Apple",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/265px-Red_Apple.jpg",
         "price":35
      },
      {
         "name":"Banana",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Bananas_white_background_DS.jpg/320px-Bananas_white_background_DS.jpg",
         "price":12
      },
      {
         "name":"Grapes",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Table_grapes_on_white.jpg/320px-Table_grapes_on_white.jpg",
         "price":45
      },
      {
         "name":"Pineapple",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Pineapple_and_cross_section.jpg/286px-Pineapple_and_cross_section.jpg",
         "price":200
      },
      {
         "name":"cherry",
         "image":"http://www.desicomments.com/wp-content/uploads/2017/05/Cherry-Image-600x570.jpg",
         "price":13
      },
      {
         "name":"clementine",
         "image":"http://www.icecreamnation.org/wp-content/uploads/2013/04/Clementine_orange.jpg",
         "price":12.4
      },
      {
         "name":"olive",
         "image":"https://www.homenaturalcures.com/wp-content/uploads/olive.jpg",
         "price":9.5
      },
      {
         "name":"tomato",
         "image":"http://cdn2.stylecraze.com/wp-content/uploads/2013/05/tomato-hair-benefits1.jpg",
         "price":8.75
      },
      {
         "name":"huckleberry",
         "image":"http://farm3.static.flickr.com/2131/2082287810_47339fc93e.jpg",
         "price":11.75
      },
      {
         "name":"papaya",
         "image":"http://media.mercola.com/assets/images/foodfacts/papaya-nutrition-facts.jpg",
         "price":2.75
      },
      {
         "name":"lime",
         "image":"https://www.florihana.com/images/stories/virtuemart/product/FLE019%20-%20LIME.jpg",
         "price":5.75
      },
      {
         "name":"pear",
         "image":"https://www.organicfacts.net/wp-content/uploads/pear.jpg",
         "price":4.75
      }
   ]
}```

答:
Assuming server respects Cache-Control/If-Modified-Since headers, than all you have to do is to create a Cache object and set it to OkHttpClient. Retrofit will take care of the rest.

```
<code>
    int cacheSize = 10 * 1024 * 1024; // 10 MB
    Cache cache = new Cache(getCacheDir(), cacheSize);

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .build();

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
</code>
```

Source: futurestud.io

Title: Retrofit response Cache

Body:
There are a lot of complex answers here about Retrofit cache but none seem to help me.

How do I cache my code response coming from the Retrofit response?

My App works fine downloading the JSON below but I need to make a cache for it and I never did cache on Android.

I need to open the App offline and get the result from my Retrofit call as if I was online.

public class APIClient {

public static final String BASE_URL = "https://raw.githubusercontent.com/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();

                Request request = original.newBuilder()
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client = httpClient.build();
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }
    return retrofit;
}}

The json response is VERY simple:

{
   "fruits":[
      {
         "name":"Apple",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/265px-Red_Apple.jpg",
         "price":35
      },
      {
         "name":"Banana",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Bananas_white_background_DS.jpg/320px-Bananas_white_background_DS.jpg",
         "price":12
      },
      {
         "name":"Grapes",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bb/Table_grapes_on_white.jpg/320px-Table_grapes_on_white.jpg",
         "price":45
      },
      {
         "name":"Pineapple",
         "image":"https://upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Pineapple_and_cross_section.jpg/286px-Pineapple_and_cross_section.jpg",
         "price":200
      },
      {
         "name":"cherry",
         "image":"http://www.desicomments.com/wp-content/uploads/2017/05/Cherry-Image-600x570.jpg",
         "price":13
      },
      {
         "name":"clementine",
         "image":"http://www.icecreamnation.org/wp-content/uploads/2013/04/Clementine_orange.jpg",
         "price":12.4
      },
      {
         "name":"olive",
         "image":"https://www.homenaturalcures.com/wp-content/uploads/olive.jpg",
         "price":9.5
      },
      {
         "name":"tomato",
         "image":"http://cdn2.stylecraze.com/wp-content/uploads/2013/05/tomato-hair-benefits1.jpg",
         "price":8.75
      },
      {
         "name":"huckleberry",
         "image":"http://farm3.static.flickr.com/2131/2082287810_47339fc93e.jpg",
         "price":11.75
      },
      {
         "name":"papaya",
         "image":"http://media.mercola.com/assets/images/foodfacts/papaya-nutrition-facts.jpg",
         "price":2.75
      },
      {
         "name":"lime",
         "image":"https://www.florihana.com/images/stories/virtuemart/product/FLE019%20-%20LIME.jpg",
         "price":5.75
      },
      {
         "name":"pear",
         "image":"https://www.organicfacts.net/wp-content/uploads/pear.jpg",
         "price":4.75
      }
   ]
}

Body:
Assuming server respects Cache-Control/If-Modified-Since headers, than all you have to do is to create a Cache object and set it to OkHttpClient. Retrofit will take care of the rest.

    int cacheSize = 10 * 1024 * 1024; // 10 MB
    Cache cache = new Cache(getCacheDir(), cacheSize);

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .build();

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();

Source: futurestud.io


问:
How do I get an audio file sample rate using sox?
I would like to get the sample-rate of a given audio file using sox. Couldn't find the commandline to do that.</p>

答:
just use:

```<code>soxi <filename>
</code>```

or

```<code>sox --i <filename>
</code>```

to produce output such as:

```<code>Input File     : 'final.flac'
Channels       : 4
Sample Rate    : 44100
Precision      : 16-bit
Duration       : 00:00:11.48 = 506179 samples = 860.849 CDDA sectors
File Size      : 2.44M
Bit Rate       : 1.70M
Sample Encoding: 16-bit FLAC
Comment        : 'Comment=Processed by SoX'
</code>```

The latter one is in case you're using the win32 version that doesn't include soxi, by default. To grab the sample rate only, just use:

```<code>soxi -r <filename>
</code>```

or

```<code>sox --i -r <filename>
</code>```

which will return the sample rate alone.

Body:
just use:

soxi <filename>

or

sox --i <filename>

to produce output such as:

Input File     : 'final.flac'
Channels       : 4
Sample Rate    : 44100
Precision      : 16-bit
Duration       : 00:00:11.48 = 506179 samples = 860.849 CDDA sectors
File Size      : 2.44M
Bit Rate       : 1.70M
Sample Encoding: 16-bit FLAC
Comment        : 'Comment=Processed by SoX'

The latter one is in case you're using the win32 version that doesn't include soxi, by default. To grab the sample rate only, just use:

soxi -r <filename>

or

sox --i -r <filename>

which will return the sample rate alone.


问:
Unable to resolve path [Player.playerName_en], unexpected token [Player]
I have this error can any one help me please

Here is my stacktrace:

```<code>Etat HTTP 500 - Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateQueryException: Unable to resolve path [Player.playerName_en], unexpected token [Player] [SELECT NEW PlayerTransient .
</code>```

Here is my code:

```<code>    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();
    tx.begin();

    try {
            String sql="SELECT NEW PlayerTransient (Player.playerName_en,Player.playerName_fr,Player.playerName_ar,Player.playerName_Abreviation, Player.playerImage,preference_player.identifier) FROM Player left join preference_player on Player.playerId= preference_player.playerId and preference_player.identifier=Player.identifier";
        playerTransients =  session.createQuery(sql).list();
        tx.commit();

    } catch (RuntimeException e) {

        tx.rollback();
        throw e;
    }

    return playerTransients;
}
</code>```

}
`

答:
There are many errors in your HQL query:

1/You've missed the alias after Player classname :

```<code>from Player as Player
</code>```

2/ Your join clause left join preference_player on Player.playerId= preference_player.playerId is not correct you have to put :

```<code>left join Player.preference_player // without the on part (which is sql syntax)
</code>```

Here the complete query :

```<code>SELECT NEW PlayerTransient (Player.playerName_en,Player.playerName_fr,Player.playerName_ar,Player.playerName_Abreviation, Player.playerImage,preference_player.identifier) FROM Player as Player
left join Player.preference_player  where Player.preference_player.identifier=Player.identifier;
</code>```

Body:
I have this error can any one help me please

Here is my stacktrace:

Etat HTTP 500 - Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateQueryException: Unable to resolve path [Player.playerName_en], unexpected token [Player] [SELECT NEW PlayerTransient .

Here is my code:

    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();
    tx.begin();

    try {
            String sql="SELECT NEW PlayerTransient (Player.playerName_en,Player.playerName_fr,Player.playerName_ar,Player.playerName_Abreviation, Player.playerImage,preference_player.identifier) FROM Player left join preference_player on Player.playerId= preference_player.playerId and preference_player.identifier=Player.identifier";
        playerTransients =  session.createQuery(sql).list();
        tx.commit();

    } catch (RuntimeException e) {

        tx.rollback();
        throw e;
    }

    return playerTransients;
}

}
`

Body:
There are many errors in your HQL query:

1/You've missed the alias after Player classname :

from Player as Player

2/ Your join clause left join preference_player on Player.playerId= preference_player.playerId is not correct you have to put :

left join Player.preference_player // without the on part (which is sql syntax)

Here the complete query :

SELECT NEW PlayerTransient (Player.playerName_en,Player.playerName_fr,Player.playerName_ar,Player.playerName_Abreviation, Player.playerImage,preference_player.identifier) FROM Player as Player
left join Player.preference_player  where Player.preference_player.identifier=Player.identifier;


问:
SASS/SCSS: Define variables based on other variables
How does one define variables with the use of other variables in SASS?

This is how one could do it with LESS:

```<code>// import Google Material Colors
// returns variables ie @blue-500, @blue-400 etc
@import 'material.colors.less';

// base
@_color: 'blue';
@_secondary: 'amber';

// primary colors
@color-primary: ~"@{@{_color}-500}";
@color-primary-bright: ~"@{@{_color}-300}";
@color-primary-brighter: ~"@{@{_color}-200}";
@color-primary-brightest: ~"@{@{_color}-50}";

// secondary colors
@color-secondary: ~"@{@{_secondary}-500}";
@color-secondary-bright: ~"@{@{_secondary}-300}";
@color-secondary-brighter: ~"@{@{_secondary}-200}";
@color-secondary-brightest: ~"@{@{_secondary}-50}";
</code>```

The LESS-way certainly isn't clean and dandy, but -- it works™

The idea is to set a base primary and then just set the other color(s) dynamically based on that.

I can't imagine that one would have to loop/map etc just to do this with SASS?(!)

答:
Sass does not support dynamic variables, period.

You will need to use maps, but I'm not sure this will help you in this specific case (as you are already using external colors):

@import 'material.colors';

$colors: (
  primary: (
    default: $blue-500,
    bright: $blue-300,
    brighter: $blue-200,
    brightest: $blue-50
  ),
  secondary: (
    default: $amber-500,
    bright: $amber-300,
    brighter: $amber-200,
    brightest: $amber-50
  )
);

@function color($color, $brightness: default) {
  @return map-get(map-get($colors, $color), $brightness);
}

h1 {
  color: color(primary, bright);
  background-color: color(secondary);
}
```

Body:
How does one define variables with the use of other variables in SASS?

This is how one could do it with LESS:

// import Google Material Colors
// returns variables ie @blue-500, @blue-400 etc
@import 'material.colors.less';

// base
@_color: 'blue';
@_secondary: 'amber';

// primary colors
@color-primary: ~"@{@{_color}-500}";
@color-primary-bright: ~"@{@{_color}-300}";
@color-primary-brighter: ~"@{@{_color}-200}";
@color-primary-brightest: ~"@{@{_color}-50}";

// secondary colors
@color-secondary: ~"@{@{_secondary}-500}";
@color-secondary-bright: ~"@{@{_secondary}-300}";
@color-secondary-brighter: ~"@{@{_secondary}-200}";
@color-secondary-brightest: ~"@{@{_secondary}-50}";

The LESS-way certainly isn't clean and dandy, but -- it works™

The idea is to set a base primary and then just set the other color(s) dynamically based on that.

I can't imagine that one would have to loop/map etc just to do this with SASS?(!)


问:
AJAX request is successful but return nothing
I was trying to make a weather app by using open weather API so when I was request through ajax, the request is successful but its returning nothing. please point out my mistake.

$(document).ready(function () {
    $('#submit-weather').click(function () {
        var city = $('#city').val();
        if (city != "") {
            $.ajax({
                url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric' + '&APPID=**********',
                type: "GET",
                datatype: "jsonp",
                success: function (data) {
                    console.log(data);
                }
            });
        } else {
            $('#error').html('Let first write city name');
        }
    });
});
```

答:
load jsfiddle with http instead of https, it will work

its because you probably have a free account and api don't support secure request on free. and your web has a secure connection so it blocked the request.
try  http on your website
Check your network tab in console.

```<code><!-- your code is fine-->
</code>```

try this first  https

try this then http

Body:
load jsfiddle with http instead of https, it will work

its because you probably have a free account and api don't support secure request on free. and your web has a secure connection so it blocked the request.
try  http on your website
Check your network tab in console.

<!-- your code is fine-->

try this first  https

try this then http


问:
load more functionality symfony 2.8
So, I have entity, called Task.php, from which I get all chat messages from database and render on current page. Here how I get them in entity:

```<code>/**
 * @return \Doctrine\Common\Collections\Collection|static
 */
public function getDisplayedActivity()
{
    $limit = 15;
    $criteria = Criteria::create();
    $criteria->orderBy(['createdAt' => 'DESC']);
    $criteria->setMaxResults($limit);
    $criteria->where(Criteria::expr()->isNull('parent'));
    return $this->activity->matching($criteria);
}
</code>```

After I render them in twig file, like this:

```<code>{% for a in displayedActivity %}
...
{% endfor %}
</code>```

There are now limit - only 15 messages shows on a page.
And I need button "Load More" that will load another 15 massages in the end of message block each time I will press it. But I have no idea how to do this.

Any help will be appreciated.

答:
you can combine setMaxResults with setFirstResult for example:

```<code>$start = 0;
$limit = 15;
$criteria = Criteria::create();
$criteria->orderBy(['createdAt' => 'DESC']);
$criteria->setFirstResult($start);
$criteria->setMaxResults($limit);
$criteria->where(Criteria::expr()->isNull('parent'));
return $this->activity->matching($criteria);
</code>```

In this way you can take from record 0 to 15

If you want to take record from 30 to 45 you need to change start  variable to 30.

So if you need to paginate you can pass the pageNumber for example page=1

```<code>$page = 1;
$limit = 15;
$start = ($page * limit) - $limit;
$criteria = Criteria::create();
$criteria->orderBy(['createdAt' => 'DESC']);
$criteria->setFirstResult($start);
$criteria->setMaxResults($limit);
return $this->activity->matching($criteria);
</code>```

Title: load more functionality symfony 2.8

Body:
So, I have entity, called Task.php, from which I get all chat messages from database and render on current page. Here how I get them in entity:

/**
 * @return \Doctrine\Common\Collections\Collection|static
 */
public function getDisplayedActivity()
{
    $limit = 15;
    $criteria = Criteria::create();
    $criteria->orderBy(['createdAt' => 'DESC']);
    $criteria->setMaxResults($limit);
    $criteria->where(Criteria::expr()->isNull('parent'));
    return $this->activity->matching($criteria);
}

After I render them in twig file, like this:

{% for a in displayedActivity %}
...
{% endfor %}

There are now limit - only 15 messages shows on a page.
And I need button "Load More" that will load another 15 massages in the end of message block each time I will press it. But I have no idea how to do this.

Any help will be appreciated.

Body:
you can combine setMaxResults with setFirstResult for example:

$start = 0;
$limit = 15;
$criteria = Criteria::create();
$criteria->orderBy(['createdAt' => 'DESC']);
$criteria->setFirstResult($start);
$criteria->setMaxResults($limit);
$criteria->where(Criteria::expr()->isNull('parent'));
return $this->activity->matching($criteria);

In this way you can take from record 0 to 15

If you want to take record from 30 to 45 you need to change start  variable to 30.

So if you need to paginate you can pass the pageNumber for example page=1

$page = 1;
$limit = 15;
$start = ($page * limit) - $limit;
$criteria = Criteria::create();
$criteria->orderBy(['createdAt' => 'DESC']);
$criteria->setFirstResult($start);
$criteria->setMaxResults($limit);
return $this->activity->matching($criteria);


答:
Are you sure you need ints?

If not, you could do

```<code>char ac[1000000];
uint8_t *ai = (uint8_t*)ac;
</code>```

if the reason you want them to be ints is because a function takes an int as argument and you need to pass some of the values of the array to it, then there is no problem with this method, as they will be implicitly casted to ints.

I think that converting them to ints just makes you use more memory than you actually need.

EDIT:

If you actually DO need an int array, here is a workaround that does not store more than it needs.

You can make a helper function that just extracts the char value casted to an int from the newly created int array, hence behaving like an int array.

```<code>// Endianness test to extract the char number
constexpr bool endianness() {
    return *(int*)const_cast<char*>("\x00\x01") & 1;
}

// Get char value casted to int from the int array
int getVal(int *i, int idx) {
    int iidx = idx / sizeof(int);
    int rem = idx % sizeof(int);
    if(endianness()) rem = sizeof(int) - rem - 1;
    return (i[iidx] & (0xff << 8*rem)) >> 8*rem;
}
</code>```

To use this you just convert the char array to an int pointer and just use it, like so.

```<code>char ac[1000000];
int *ai = (int*)ac;
cout << getVal(ai, 0);
</code>```

This will print the value of the first element casted into an int and is actually portable.

Title: How to convert an array of char to array of int

Body:
Is there a way to convert an array of char to array of int32 without iterating every member.

I need to convert a huge amount of data so I'm looking for some faster than:

char ac[1000000];
int32_t ai[1000000];
for(int i=0;i<1000000;i++) {
    ai[i]=ac[i];
}

Notes:

I'm not asking about how to convert '3' to 0x03, I'm talking about convert 0x03 (one byte) to 0x00000003 (to  4 bytes)

Not portable is not a problem (platform linux AMD64).

The proposed method is slow.

looking for a library that use SSE instructions or similar.
I need it to feed a math function that works with int32 numbers and my original data is in 8 bits size, so I need to convert it, and obviously I can't cast because is an memory area not a value.

Body:
Are you sure you need ints?

If not, you could do

char ac[1000000];
uint8_t *ai = (uint8_t*)ac;

if the reason you want them to be ints is because a function takes an int as argument and you need to pass some of the values of the array to it, then there is no problem with this method, as they will be implicitly casted to ints.

I think that converting them to ints just makes you use more memory than you actually need.

EDIT:

If you actually DO need an int array, here is a workaround that does not store more than it needs.

You can make a helper function that just extracts the char value casted to an int from the newly created int array, hence behaving like an int array.

// Endianness test to extract the char number
constexpr bool endianness() {
    return *(int*)const_cast<char*>("\x00\x01") & 1;
}

// Get char value casted to int from the int array
int getVal(int *i, int idx) {
    int iidx = idx / sizeof(int);
    int rem = idx % sizeof(int);
    if(endianness()) rem = sizeof(int) - rem - 1;
    return (i[iidx] & (0xff << 8*rem)) >> 8*rem;
}

To use this you just convert the char array to an int pointer and just use it, like so.

char ac[1000000];
int *ai = (int*)ac;
cout << getVal(ai, 0);

This will print the value of the first element casted into an int and is actually portable.


问:
Better ways to identify objects not getting garbage collected?

In a nutshell

I have a program that is gradually using more and more memory over time. I am using jmap and jhat to try and diagnose it but am still not quite there.

Background

The program is a long-running server backed by an hbase datastore providing a thrift service to a bunch of other stuff. However, after running for a few days, it will eventually hit the allocated heap limit, and thrash back and forth with nearly all time spent in garbage collection. It would seem references are getting kept to a lot of data somewhere

What I've done so far

After fiddling about with jstat and jconsole some I ended up taking heapdumps with jmap of the running process, and run it through jhat, and the numbers simple don't add up to anywhere near the memory utilisation

jmap -F -dump:live,format=b,file=heap.dump 12765

jmap -F -dump:format=b,file=heap.all 12765

Some stuff off the top of the histogram

```<code>Class   Instance Count  Total Size
class [B     7493    228042570
class java.util.HashMap$Entry    2833152     79328256
class [Ljava.util.HashMap$Entry;     541     33647856
class [Ljava.lang.Object;    303698  29106440
class java.lang.Long     2851889     22815112
class org.apache.hadoop.hbase.KeyValue   303593  13358092
class org.apache.hadoop.hbase.client.Result  303592  9714944
class [I     14074   9146580
class java.util.LinkedList$Entry     303841  7292184
class [Lorg.apache.hadoop.hbase.KeyValue;    303592  7286208
class org.apache.hadoop.hbase.io.ImmutableBytesWritable  305097  4881552
class java.util.ArrayList    302633  4842128
class [Lorg.apache.hadoop.hbase.client.Result;   297     2433488
class [C     5391    320190
</code>```

While the totals here don't add up to it, at the point that heap dump was taken the process was using over 1gb of memory.

The immediate apparent culprit seems like I'm leaving HBase Result and KeyValue entries all over the place. Trying to trace up the references, I eventually hit

```<code>Object at 0x2aab091e46d0

instance of org.apache.hadoop.hbase.ipc.HBaseClient$Call@0x2aab091e46d0 (53 bytes)

Class:

class org.apache.hadoop.hbase.ipc.HBaseClient$Call
Instance data members:

done (Z) : true
error (L) : <null>
id (I) : 57316
param (L) : org.apache.hadoop.hbase.ipc.HBaseRPC$Invocation@0x2aab091e4678 (48 bytes)
this$0 (L) : org.apache.hadoop.hbase.ipc.HBaseClient@0x2aaabfb78f30 (86 bytes)
value (L) : org.apache.hadoop.hbase.io.HbaseObjectWritable@0x2aab092e31c0 (40 bytes)
References to this object:

Other Queries

Reference Chains from Rootset
Exclude weak refs
Include weak refs
Objects reachable from here
</code>```

Help needed:

There seems to be no references to this final HBaseCLient$Call object(or any of the others like it, each which hold a thousand or so keyvalues with all their internal data). Shouldn't it be getting GCed? Am I just misunderstanding how the gc works or the extent to which jhat will verify references? If so what further can I do to track down my "missing" memory? What other steps can I take to track this down?

答: You can try JProfiler 10 days for free. With JProfiler you will solve this issue in a few minutes.</p>

Body:
In a nutshell

I have a program that is gradually using more and more memory over time. I am using jmap and jhat to try and diagnose it but am still not quite there.

Background

The program is a long-running server backed by an hbase datastore providing a thrift service to a bunch of other stuff. However, after running for a few days, it will eventually hit the allocated heap limit, and thrash back and forth with nearly all time spent in garbage collection. It would seem references are getting kept to a lot of data somewhere

What I've done so far

After fiddling about with jstat and jconsole some I ended up taking heapdumps with jmap of the running process, and run it through jhat, and the numbers simple don't add up to anywhere near the memory utilisation

jmap -F -dump:live,format=b,file=heap.dump 12765

jmap -F -dump:format=b,file=heap.all 12765

Some stuff off the top of the histogram

Class   Instance Count  Total Size
class [B     7493    228042570
class java.util.HashMap$Entry    2833152     79328256
class [Ljava.util.HashMap$Entry;     541     33647856
class [Ljava.lang.Object;    303698  29106440
class java.lang.Long     2851889     22815112
class org.apache.hadoop.hbase.KeyValue   303593  13358092
class org.apache.hadoop.hbase.client.Result  303592  9714944
class [I     14074   9146580
class java.util.LinkedList$Entry     303841  7292184
class [Lorg.apache.hadoop.hbase.KeyValue;    303592  7286208
class org.apache.hadoop.hbase.io.ImmutableBytesWritable  305097  4881552
class java.util.ArrayList    302633  4842128
class [Lorg.apache.hadoop.hbase.client.Result;   297     2433488
class [C     5391    320190

While the totals here don't add up to it, at the point that heap dump was taken the process was using over 1gb of memory.

The immediate apparent culprit seems like I'm leaving HBase Result and KeyValue entries all over the place. Trying to trace up the references, I eventually hit

Object at 0x2aab091e46d0

instance of org.apache.hadoop.hbase.ipc.HBaseClient$Call@0x2aab091e46d0 (53 bytes)

Class:

class org.apache.hadoop.hbase.ipc.HBaseClient$Call
Instance data members:

done (Z) : true
error (L) : <null>
id (I) : 57316
param (L) : org.apache.hadoop.hbase.ipc.HBaseRPC$Invocation@0x2aab091e4678 (48 bytes)
this$0 (L) : org.apache.hadoop.hbase.ipc.HBaseClient@0x2aaabfb78f30 (86 bytes)
value (L) : org.apache.hadoop.hbase.io.HbaseObjectWritable@0x2aab092e31c0 (40 bytes)
References to this object:

Other Queries

Reference Chains from Rootset
Exclude weak refs
Include weak refs
Objects reachable from here

Help needed:

There seems to be no references to this final HBaseCLient$Call object(or any of the others like it, each which hold a thousand or so keyvalues with all their internal data). Shouldn't it be getting GCed? Am I just misunderstanding how the gc works or the extent to which jhat will verify references? If so what further can I do to track down my "missing" memory? What other steps can I take to track this down?


问:
Associate an external application url to jenkins build
I am trying to link or associate an external application url to jenkins job build.
So for every builds, this link or url should be available at the left side and any user can simply click on it to launch the external application.

So far I explored the following plugins for this:

https://wiki.jenkins.io/display/JENKINS/Associated+Files+Plugin -  this associates a file or directory to the build , something similar to the html publisher plugin... not a url

https://wiki.jenkins.io/display/JENKINS/DocLinks+Plugin - similar to above , associate a doc from the build artifact directories

https://wiki.jenkins.io/pages/viewpage.action?pageId=52298023 - this Side bar link plugin can associate a external link to the jenkin project, but not to every builds

for me the external link which I am trying to associate to the build , dynamically changes for each build , basically some of the query parameter in the external link, so it's critical to associate it to every builds for tracking and other purposes . ex: the external link will be a like a small web app
http:hostnamexxx:port/somepage?para1=xxx&para2=yyyy

Please let me know if there is any plugin for this specific purpose or any other ideas

答:
This would be the Anchor Chain plugin. I've played around with it a bit:

The docs state that the icon can be omitted. Then however you need to insert a tab character after the URL.

When inserting a link to an icon, it is always relative to Jenkins base URL.

ContentLicense: CC BY-SA 4.0


问:
Best practises for model classes injection (Angular)
i have read the Angular documentation about the class injection but i can't understand which of these practices are better. To be more specific: if i have the following model class

```<code>export class Documents{
private documentNumber:string;
private countryIssuingDocument:string;
private documentExpirationDate:string;
private documentIssuingOffice:string;

}
</code>```

and i want to inject it

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

import {Documents} from "../../model/document.model";

@Component({
selector: 'document-screen',
templateUrl: 'document-screen.html'
})

export class DocumentScreen {

constructor(private documentData : Documents) {
}

}
</code>```

is it better to do that using the new keyword or by declaring the model class in providers array as above. I think it is better to declare my model class in the providers array because in this way I'll have a singleton architecture. Am i right?

Thank you in advance!

答:
Model objects contain the data of that type. You definitely dont need a single object , you might be having many models of the same type. So its not a good idea to use dependency injection. </p>

<p>Use dependency injection only for services which have logic and sometimes have data which will be shared across components. </p>

Body:
i have read the Angular documentation about the class injection but i can't understand which of these practices are better. To be more specific: if i have the following model class

export class Documents{
private documentNumber:string;
private countryIssuingDocument:string;
private documentExpirationDate:string;
private documentIssuingOffice:string;

}

and i want to inject it

import { Component ,Output,EventEmitter} from '@angular/core';

import {Documents} from "../../model/document.model";

@Component({
selector: 'document-screen',
templateUrl: 'document-screen.html'
})

export class DocumentScreen {

constructor(private documentData : Documents) {
}

}

is it better to do that using the new keyword or by declaring the model class in providers array as above. I think it is better to declare my model class in the providers array because in this way I'll have a singleton architecture. Am i right?

Thank you in advance!

Body:
Model objects contain the data of that type. You definitely dont need a single object , you might be having many models of the same type. So its not a good idea to use dependency injection.

Use dependency injection only for services which have logic and sometimes have data which will be shared across components.


问:
Regex to match punctuation followed by space with some exceptions
I am trying to come up with a regex which matches punctuation (!, ?, and .) followed by a space. I want to NOT match periods which are preceded by salutations like "Mr.", "Mrs.", etc...

Doing the first part is simple enough:
r"[\?|!|\.] "

But I am struggling with the second part. Here is what I have so far:
r"(?<=[^(Mr|Ms)])\. "

The second one does NOT match something like "radar. " or "cups. " or "loom. " which is bad. I am also having trouble combining both those regexes into a single one.

Thanks.

答:
If want to be complete, you would need to exclude Prof, Dr, Miss, Mrs, Ms, Mr etc.

Python's re module does not allow for anything other than fixed width lookbacks; therefor, you would need to do multiple lookbacks for each width:

```<code>r'(?<!\bMr|\bDr)(?<!Mrs)(?<!\bProf|\bMiss)([.,;])(?= |\n|\Z)'
</code>```

Demo

Or use the regex module that would allow variable width lookback assertions. Then you can do:

```<code>r'(?<!\bMr|\bMrs|\bDr|\bMiss|\bProf)([.,;])(?= |\n|\z)'
</code>```

Demo

Side note: Anything inside a character class matches a single character. That is why you get unexpected results with [^(Mr|Ms)] That is negated character class for the individual characters of the set Mrs|()

Demo

Body:
If want to be complete, you would need to exclude Prof, Dr, Miss, Mrs, Ms, Mr etc.

Python's re module does not allow for anything other than fixed width lookbacks; therefor, you would need to do multiple lookbacks for each width:

r'(?<!\bMr|\bDr)(?<!Mrs)(?<!\bProf|\bMiss)([.,;])(?= |\n|\Z)'

Demo

Or use the regex module that would allow variable width lookback assertions. Then you can do:

r'(?<!\bMr|\bMrs|\bDr|\bMiss|\bProf)([.,;])(?= |\n|\z)'

Demo

Side note: Anything inside a character class matches a single character. That is why you get unexpected results with [^(Mr|Ms)] That is negated character class for the individual characters of the set Mrs|()

Demo


问:
Problems with calculating linear regression for individual cells in a column in pandas
I'm trying to implement a linear regression calculation for individual empty cells based on previous data in a column. Since I do not understand how to use the python libraries, I wrote the whole calculation in steps.

This is my dataframe:

```<code>index   value    delta
-52       0      42517
-51       0      42524
-50      216     42531
-49      345     42538
-48      237     42545
...
 -2      367     42862
 -1      310     42869
  0      226     42876
  1      NaN     42883
  2      NaN     42890
...
 49      NaN     43213
 50      NaN     43220
 51      NaN     43227
 52      NaN     43234
</code>```

Values where index = 0 and lower are always 52. Above, there may be a different number, but it is known to me beforehand, in this example their 52.
Unknown values always start where index = 1.

For a single value, I'm counting so (here i count for value in column delta dd = 42883):

```<code>x = dftest['delta']
y = dftest['value']
x_mean= np.mean(x)
y_mean = np.mean(y)
x_std = np.std(x)
y_std = np.std(y)
corr = np.corrcoef(y, x)[1,0]
slope = corr * y_std / x_std
intercept = y_mean - slope * x_mean
n_vl = intercept + slope * dd
</code>```

So he calculates, but I do not understand how to write a loop, so that he does this for all empty cells (beginning with index = 1), while taking into account the previously calculated value.

I tried to use the code that is in the first response here and change it, but it does not work.

Below part of the code:

```<code>vl = dftest['value'].values
delta =  dftest['delta'].values
for index in range(0, vl.shape[0]):
    if np.isnan(vl[index]):
        x = delta.take(range(index-52,index+1),mode='wrap')
        y = vl.take(range(index-52,index+1),mode='wrap')
        y1 = np.nanmean(vl.take(range(index-52,index+1),mode='wrap'))
        y2 = np.nanstd(vl.take(range(index-52,index+1),mode='wrap'))
        x1 = np.nanmean(delta.take(range(index-52,index+1),mode='wrap'))
        x2 = np.nanstd(delta.take(range(index-52,index+1),mode='wrap'))
        corr = np.corrcoef(y, x)[1,0]
        slope = corr * y2 / x2
        intercept = y1 - slope * x1
        n_vl = intercept + slope * dd
print (y)
print (x)
print (y1)
print (y2)
print (x1)
print (x2)
print (corr)
print (slope)
print (intercept)
print (n_vl)
</code>```

But it takes a value below the index = 0, not above. I do not know how to change this and how to write it so that it counts for every empty cell.

That's what I get at the output for one value (from my code with a loop).

```<code>[ 226.   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan]
[42876 42883 42890 42897 42904 42911 42918 42925 42932 42939 42946 42953
 42960 42967 42974 42981 42988 42995 43002 43009 43016 43023 43030 43037
 43044 43051 43058 43065 43072 43079 43086 43093 43100 43107 43108 43115
 43122 43129 43136 43143 43150 43157 43164 43171 43178 43185 43192 43199
 43206 43213 43220 43227 43234]
226.0
0.0
43055.8490566
104.701263481
nan
nan
nan
nan
</code>```

I have been stuck on this for a long time and can not move forward, I really need help.

答:
Just do

```<code>dftest['value'].fillna(52)
</code>```

which will fill all the NaN's in the value column with number 52.
If you need to be extra sure to fill NaN's only if index <= 0 (in other words you expect NaN's in value column for index > 0) then do:

```<code>dftest.loc[index <= 0, 'value'].fillna(52)
</code>```

Remember, that if you feel you need to use loops in Pandas, you most likely doing it wrong.

Body:
I'm trying to implement a linear regression calculation for individual empty cells based on previous data in a column. Since I do not understand how to use the python libraries, I wrote the whole calculation in steps.

This is my dataframe:

index   value    delta
-52       0      42517
-51       0      42524
-50      216     42531
-49      345     42538
-48      237     42545
...
 -2      367     42862
 -1      310     42869
  0      226     42876
  1      NaN     42883
  2      NaN     42890
...
 49      NaN     43213
 50      NaN     43220
 51      NaN     43227
 52      NaN     43234

Values where index = 0 and lower are always 52. Above, there may be a different number, but it is known to me beforehand, in this example their 52.
Unknown values always start where index = 1.

For a single value, I'm counting so (here i count for value in column delta dd = 42883):

x = dftest['delta']
y = dftest['value']
x_mean= np.mean(x)
y_mean = np.mean(y)
x_std = np.std(x)
y_std = np.std(y)
corr = np.corrcoef(y, x)[1,0]
slope = corr * y_std / x_std
intercept = y_mean - slope * x_mean
n_vl = intercept + slope * dd

So he calculates, but I do not understand how to write a loop, so that he does this for all empty cells (beginning with index = 1), while taking into account the previously calculated value.

I tried to use the code that is in the first response here and change it, but it does not work.

Below part of the code:

vl = dftest['value'].values
delta =  dftest['delta'].values
for index in range(0, vl.shape[0]):
    if np.isnan(vl[index]):
        x = delta.take(range(index-52,index+1),mode='wrap')
        y = vl.take(range(index-52,index+1),mode='wrap')
        y1 = np.nanmean(vl.take(range(index-52,index+1),mode='wrap'))
        y2 = np.nanstd(vl.take(range(index-52,index+1),mode='wrap'))
        x1 = np.nanmean(delta.take(range(index-52,index+1),mode='wrap'))
        x2 = np.nanstd(delta.take(range(index-52,index+1),mode='wrap'))
        corr = np.corrcoef(y, x)[1,0]
        slope = corr * y2 / x2
        intercept = y1 - slope * x1
        n_vl = intercept + slope * dd
print (y)
print (x)
print (y1)
print (y2)
print (x1)
print (x2)
print (corr)
print (slope)
print (intercept)
print (n_vl)

But it takes a value below the index = 0, not above. I do not know how to change this and how to write it so that it counts for every empty cell.

That's what I get at the output for one value (from my code with a loop).

[ 226.   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan   nan
nan   nan   nan   nan   nan]
[42876 42883 42890 42897 42904 42911 42918 42925 42932 42939 42946 42953
 42960 42967 42974 42981 42988 42995 43002 43009 43016 43023 43030 43037
 43044 43051 43058 43065 43072 43079 43086 43093 43100 43107 43108 43115
 43122 43129 43136 43143 43150 43157 43164 43171 43178 43185 43192 43199
 43206 43213 43220 43227 43234]
226.0
0.0
43055.8490566
104.701263481
nan
nan
nan
nan

I have been stuck on this for a long time and can not move forward, I really need help.

Body:
Just do

dftest['value'].fillna(52)

which will fill all the NaN's in the value column with number 52.
If you need to be extra sure to fill NaN's only if index <= 0 (in other words you expect NaN's in value column for index > 0) then do:

dftest.loc[index <= 0, 'value'].fillna(52)

Remember, that if you feel you need to use loops in Pandas, you most likely doing it wrong.


问:
How to compile F# library from another F# program
I want to make my Application configuration as F# file wich will be compiled to dll. (like XMonad configuration with xmonad.hs on haskell). I found it more interesting and just better way then using XML serialization.

So is there any way how can I compile single file (or more) to Library with some configuration like

```<code>module RNExcel.Repository

open RNExcel.Model

    type ExpenseReportRepository() =
        member x.GetAll() =
            seq{ yield {Name="User1"
                        Role="someRole"
                        Password = "123321"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="50"}]}
                 yield {Name="User2"
                        Role="Estimator"
                        Password = "123123"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="125"}]}    }
</code>```

my idea was to run shell .... and msbuild the project , but I don't think it will works for every user with .net 4

答: Check out the F# Power Pack, specifically the FSharp.CodeDom library.  You can use this library to compile F# code at run-time and, with a little Reflection thrown in, can likely achieve your goal of code-as-configuration with minimal fuss.</p>

Body:
I want to make my Application configuration as F# file wich will be compiled to dll. (like XMonad configuration with xmonad.hs on haskell). I found it more interesting and just better way then using XML serialization.

So is there any way how can I compile single file (or more) to Library with some configuration like

module RNExcel.Repository

open RNExcel.Model

    type ExpenseReportRepository() =
        member x.GetAll() =
            seq{ yield {Name="User1"
                        Role="someRole"
                        Password = "123321"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="50"}]}
                 yield {Name="User2"
                        Role="Estimator"
                        Password = "123123"
                        ExpenseLineItems =
                            [{ExpenseType="Item1"
                              ExpenseAmount="50"};
                             {ExpenseType="Item2"
                              ExpenseAmount="125"}]}    }

my idea was to run shell .... and msbuild the project , but I don't think it will works for every user with .net 4


问:
T-SQL ORDER BY several clauses
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

```<code> ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |
</code>```

Demo Data Table ProjectData:

```<code> ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |
</code>```

My current result looks like this:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
</code>```

My current query looks like this:

```<code>SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt
</code>```

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |
</code>```

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

答:
You would need to map the order you would want them sorted into. </p>

```<code>SELECT ROW_NUMBER() OVER(
        ORDER BY CASE StatusId
            WHEN 1 THEN 1
            WHEN 2 THEN 2
            WHEN 3 THEN 4
            WHEN 4 THEN 3
            ELSE 5 + StatusId
        END ASC)  AS [RowNumber]
    , *
FROM (SELECT DISTINCT
    [P].ProjectId
  , [P].Label
  , [PD].StatusId
  , [P].ProjectDataId
 FROM [MySchema].[Project] [P]
 INNER JOIN [MyProject].[ProjectData] [PD]
 ON [PD].ProjectDataId = [P].ProjectDataId) dt
</code>```

Title: T-SQL ORDER BY several clauses

Body:
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

 ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |

Demo Data Table ProjectData:

 ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |

My current result looks like this:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |

My current query looks like this:

SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

Body:
You would need to map the order you would want them sorted into.

SELECT ROW_NUMBER() OVER(
        ORDER BY CASE StatusId
            WHEN 1 THEN 1
            WHEN 2 THEN 2
            WHEN 3 THEN 4
            WHEN 4 THEN 3
            ELSE 5 + StatusId
        END ASC)  AS [RowNumber]
    , *
FROM (SELECT DISTINCT
    [P].ProjectId
  , [P].Label
  , [PD].StatusId
  , [P].ProjectDataId
 FROM [MySchema].[Project] [P]
 INNER JOIN [MyProject].[ProjectData] [PD]
 ON [PD].ProjectDataId = [P].ProjectDataId) dt


问:
TypeScript + moment.js: error TS2307: Cannot find module 'moment'
I'm developing a web app, using angular 1.5, typescript 2.4.0, moment: 2.18.1, and gulp for project assembling.

Here is my tsconfig.json:

```<code>{
  "files": [
    "src/app/main.ts",
    "types/**/*.ts"
  ],
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es2015",
    "allowSyntheticDefaultImports": true
  }
}
</code>```

Inside my date-range-picker.component.ts. I'm importing moment lib, as was proposed in the main documentation:

```<code>import * as moment from 'moment';
</code>```

Which works fine for the main gulp project assembling task that relies on tsify plugin.:

```<code>var browserifyIt = browserify({
    basedir: '.',
    debug: true,
    entries: paths.browserifyEntries,
    cache: {},
    packageCache: {}
}).plugin(tsify);

gulp.task('bundle', ['views'], function () {
    return browserifyIt
        .transform('babelify', {
            presets: ['es2015'],
            extensions: ['.ts']
        })
        .bundle()
        .on('error', interceptErrors)
        .pipe(source(fileNames.buildJs))
        .pipe(ngAnnotate())
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write(paths.sourcemapPath))
        .pipe(gulp.dest(paths.build));
});
</code>```

But for the compiling of the tests I decided to use task employing tsProject():

```<code>const testSrcPaths = {
    ....,
    componentTests: 'src/app/components/**/*.test.ts',
    ....
};
gulp.task('component-tests:compile', function () {
       return gulp.src(testSrcPaths.componentTests).pipe(tsProject())
        .on('error', interceptErrors)
        .js.pipe(gulp.dest(`${paths.testsDist}/components`));
});
</code>```

Which leads to the following error:

date-range-picker/date-range-picker.component.ts(2,25): error TS2307:
  Cannot find module 'moment'.

What can be done to fix it?

答:
Finally, adding moduleResolution: "node" to compilerOptions solved my problem. So in the end the following tsconfig.json configuration is employed:

```<code>{
  "files": [
    "src/app/main.ts"
  ],
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es2015",
    "moduleResolution": "node"
  }
}
</code>```

Here is the link one can use to learn more about typescript module resolution approaches.

Body:
I'm developing a web app, using angular 1.5, typescript 2.4.0, moment: 2.18.1, and gulp for project assembling.

Here is my tsconfig.json:

{
  "files": [
    "src/app/main.ts",
    "types/**/*.ts"
  ],
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es2015",
    "allowSyntheticDefaultImports": true
  }
}

Inside my date-range-picker.component.ts. I'm importing moment lib, as was proposed in the main documentation:

import * as moment from 'moment';

Which works fine for the main gulp project assembling task that relies on tsify plugin.:

var browserifyIt = browserify({
    basedir: '.',
    debug: true,
    entries: paths.browserifyEntries,
    cache: {},
    packageCache: {}
}).plugin(tsify);

gulp.task('bundle', ['views'], function () {
    return browserifyIt
        .transform('babelify', {
            presets: ['es2015'],
            extensions: ['.ts']
        })
        .bundle()
        .on('error', interceptErrors)
        .pipe(source(fileNames.buildJs))
        .pipe(ngAnnotate())
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write(paths.sourcemapPath))
        .pipe(gulp.dest(paths.build));
});

But for the compiling of the tests I decided to use task employing tsProject():

const testSrcPaths = {
    ....,
    componentTests: 'src/app/components/**/*.test.ts',
    ....
};
gulp.task('component-tests:compile', function () {
       return gulp.src(testSrcPaths.componentTests).pipe(tsProject())
        .on('error', interceptErrors)
        .js.pipe(gulp.dest(`${paths.testsDist}/components`));
});

Which leads to the following error:

date-range-picker/date-range-picker.component.ts(2,25): error TS2307:
  Cannot find module 'moment'.

What can be done to fix it?

Body:
Finally, adding moduleResolution: "node" to compilerOptions solved my problem. So in the end the following tsconfig.json configuration is employed:

{
  "files": [
    "src/app/main.ts"
  ],
  "compilerOptions": {
    "noImplicitAny": false,
    "target": "es2015",
    "moduleResolution": "node"
  }
}

Here is the link one can use to learn more about typescript module resolution approaches.


问:
Is ActiveSheet.AutoFilter.ApplyFilter necessary? It breaks my code when the sheet is protected, so can I safely omit it?
Upon activating a sheet I'm applying a filter based on a calculated column from the previous sheet.

```<code>Range(Cells(1, 1), LastCell).AutoFilter Field:=Range("filter").Column, Criteria1:="TRUE"

ActiveSheet.AutoFilter.ApplyFilter
</code>```

But is the second line at all necessary?  It seems to work alright without it, and the issue is that with the sheet protected, even with activesheet.protect userinterfaceonly :=true, .applyfilter is throwing up an error, whereas the autofilter line itself isn't.

I have no idea why this should be so, but anyway it seems to me the easiest solution is, if .applyfilter is unnecessary, omit it.

答:
It is rarely necessary. Only if you had applied some AutoFilter then you invoked Sheet1.ShowAllData, which keep the filter "alive" but shows all the rows. So if you did that and you want to "re-apply" the active filter, you can then invoke Sheet.AutoFilter.ApplyFilter.

```<code>Sub Example()
  Sheet1.Range("A1:D20").AutoFilter 3, "x"
  Sheet1.ShowAllData              '<------ keeps filter alive but shows all data
  Sheet1.AutoFilter.ApplyFilter   '<------ applies "again" the same filter
End Sub
</code>```

If you never use ShowAllData in your code, then I guarantee you that ApplyFilter is useless. In your code it obviously has no effect because you just place it immediately after the AutoFilter statement. So remove it and proceed.

Body:
Upon activating a sheet I'm applying a filter based on a calculated column from the previous sheet.

Range(Cells(1, 1), LastCell).AutoFilter Field:=Range("filter").Column, Criteria1:="TRUE"

ActiveSheet.AutoFilter.ApplyFilter

But is the second line at all necessary?  It seems to work alright without it, and the issue is that with the sheet protected, even with activesheet.protect userinterfaceonly :=true, .applyfilter is throwing up an error, whereas the autofilter line itself isn't.

I have no idea why this should be so, but anyway it seems to me the easiest solution is, if .applyfilter is unnecessary, omit it.

Body:
It is rarely necessary. Only if you had applied some AutoFilter then you invoked Sheet1.ShowAllData, which keep the filter "alive" but shows all the rows. So if you did that and you want to "re-apply" the active filter, you can then invoke Sheet.AutoFilter.ApplyFilter.

Sub Example()
  Sheet1.Range("A1:D20").AutoFilter 3, "x"
  Sheet1.ShowAllData              '<------ keeps filter alive but shows all data
  Sheet1.AutoFilter.ApplyFilter   '<------ applies "again" the same filter
End Sub

If you never use ShowAllData in your code, then I guarantee you that ApplyFilter is useless. In your code it obviously has no effect because you just place it immediately after the AutoFilter statement. So remove it and proceed.


问:
Split Controller master table view pushes to master nav stack not detail
I am trying to set up a very basic Split View Controller.  The left side (master) is a table view, which when a row is tapped, I expect to load details into the right side (detail).

I do not know what I'm doing wrong.  I have an example project that functions exactly how I want it to, but I'm missing something in my main project.  I've very carefully scoured the example project and as far as I can tell, everything is done exactly the same in my main project.

The problem I'm having is, when I tap a cell in my table view, the view controller that is invoked, appears in the master (left side), not in the detail (right side).

My question is: what exactly do I have to do to get the right side to display the detail?

I'm testing on an iPhone 7 Plus Simulator in landscape mode.  Portrait mode works fine.

As far as I know I have all the correct delegate setup complete.  Thanks in advance!

答:
Wow!  Okay, I figured out what was wrong.  This has got to be a bug in the storyboard UI, because it does not make sense that this would be the problem.

When I ctrl-dragged from the table view cell to the nav controller so as to create the detail segue, I chose "show".  I then realized that it should actually be "show detail", so I went into the attributes of the segue that I just created and changed "Kind" to "Show Detail (e.g. Replace)", which as far as I know, should end up being the same thing as if I would have selected "Show Detail" when creating the segue.  It is not.

After a great deal of trial-and-error, I discovered that I had to delete the segue I originally created and re-create the segue, selecting "Show Detail".


问:
Slide element 100% up and all subsequent siblings by the same amount?
Consider this document:

```<code><div id="container" class="no-panel">
  <div id="panel">
    <!-- Can be any DOM with arbitrary, variable height.
         120px is hardcoded only for the demo. -->
    <div style="height: 120px">Some Contents</div>
  </div>
  <div id="contents">
    <!-- Can be any DOM with arbitrary, variable height.
         300px is hardcoded only for the demo. -->
    <div style="height: 300px">Some Contents</div>
  </div>
</div>
</code>```

Both #panel and #contents are supposed to be as tall as their contents, and not more (in the example I forced their height using arbitrary child div's - just  for the demo).

I want to apply a class to #container that will make #panel slide all the way up (so it becomes invisible behind the top border of the viewport). At the same time, #contents should slide up by the same amount #panel did. I like that to be animated too (in the demo I used :hover instead of the class).

How can I do that without using JS? It has to work in Chrome / Firefox, but I don't care about other browsers.

I tried setting translateY(-100%), which works fine on #panel, but then #contents would move 100% relative to its height, not to #panel's height, which is way too much.

Absolute positioning wouldn't work as then I'd need to fix the height of #panel which I'm trying not to do (it's contents are supposed to vary).

JSFiddle with an example on how I'd like it to work. - but with hardcoded value which I don't want.

答:
From our conversation in the comments, I came up with a simple approach (see fiddle). The CSS uses translate to hide the #panel and absolute positioning of the #contents for movement relative to its parent (the #container).

Unfortunately this approach to affect the height of the parent.

Note that this only works as long as #panel and #contents are the only children of #container.

#container {
  width: 100%;
  height: 100%;
  position: relative;
}

#panel, #contents {
  transition: all 0.2s ease-in;
}

#panel {
  background-color: tomato;
  width: 100%;
  height: auto; /* Has to be sized to fit its contents, and not more. */
}

#contents {
  position: absolute;
  top: 100%;
  background-color: crimson;
  width: 100%;
}

#container:hover #panel {
  transform: translateY(-100%);
}

#container:hover #contents {
     top: 0;
}

* {
  box-sizing: border-box;
}

html, body {
  padding: 0;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container" class="no-panel">
  <div id="panel">
    <!-- Can be any DOM with arbitrary, variable height.
         120px is hardcoded only for the demo. -->
    <div style="height: auto">Some Contents<br/>Some more contents</div>
  </div>
  <div id="contents">
    <!-- Can be any DOM with arbitrary, variable height.
         300px is hardcoded only for the demo. -->
    <div style="height: auto">Some Contents</div>
  </div>
</div></code>```

Body:
Consider this document:

Some Contents

Some Contents

Both #panel and #contents are supposed to be as tall as their contents, and not more (in the example I forced their height using arbitrary child div's - just  for the demo).

I want to apply a class to #container that will make #panel slide all the way up (so it becomes invisible behind the top border of the viewport). At the same time, #contents should slide up by the same amount #panel did. I like that to be animated too (in the demo I used :hover instead of the class).

How can I do that without using JS? It has to work in Chrome / Firefox, but I don't care about other browsers.

I tried setting translateY(-100%), which works fine on #panel, but then #contents would move 100% relative to its height, not to #panel's height, which is way too much.

Absolute positioning wouldn't work as then I'd need to fix the height of #panel which I'm trying not to do (it's contents are supposed to vary).

JSFiddle with an example on how I'd like it to work. - but with hardcoded value which I don't want.

Body:
From our conversation in the comments, I came up with a simple approach (see fiddle). The CSS uses translate to hide the #panel and absolute positioning of the #contents for movement relative to its parent (the #container).

Unfortunately this approach to affect the height of the parent.

Note that this only works as long as #panel and #contents are the only children of #container.

#container {
  width: 100%;
  height: 100%;
  position: relative;
}

#panel, #contents {
  transition: all 0.2s ease-in;
}

#panel {
  background-color: tomato;
  width: 100%;
  height: auto; /* Has to be sized to fit its contents, and not more. */
}

#contents {
  position: absolute;
  top: 100%;
  background-color: crimson;
  width: 100%;
}

#container:hover #panel {
  transform: translateY(-100%);
}

#container:hover #contents {
     top: 0;
}

* {
  box-sizing: border-box;
}

html, body {
  padding: 0;
  margin: 0;
}

<div id="container" class="no-panel">
  <div id="panel">
    <!-- Can be any DOM with arbitrary, variable height.
         120px is hardcoded only for the demo. -->
    <div style="height: auto">Some Contents<br/>Some more contents</div>
  </div>
  <div id="contents">
    <!-- Can be any DOM with arbitrary, variable height.
         300px is hardcoded only for the demo. -->
    <div style="height: auto">Some Contents</div>
  </div>
</div>


问:
Java FileHandler disable log rotation
I am trying to disable log rotation, for file handler using,

```<code>FileHandler fh = new FileHandler
    ( "path" + "run.log", 1000000, 1, false);
</code>```

What i want is one log, created for each run i do not want rotation or backing up of the old file, but using this initialization i get run.log run.log.1 run.log.2 for each run.

Also

```<code>        logger.setUseParentHandlers(false);
</code>```

is set to false.

答:
Try this:
FileHandler fh = new FileHandler( "path" + "run.log", 1000000, 1, true);

Title: Java FileHandler disable log rotation

Body:
I am trying to disable log rotation, for file handler using,

FileHandler fh = new FileHandler
    ( "path" + "run.log", 1000000, 1, false);

What i want is one log, created for each run i do not want rotation or backing up of the old file, but using this initialization i get run.log run.log.1 run.log.2 for each run.

Also

        logger.setUseParentHandlers(false);

is set to false.


问:
Easeljs: Object added to stage on click has no X value
Trying to following the example at http://www.createjs.com/tutorials/Mouse%20Interaction/ , which shows how to drag and drop a shape. Something is going wrong for me. I add a circle when the stage is clicked, then I try to get it's x location... my alert shows a 0, but the circle appears in the right place. Then I try to drag, and the circle moves around, but at a distance from the mouse pointer.</p>

```<code>var stage = new createjs.Stage("demoCanvas")
stage.on("stagemousedown", function(evt) {
    var corn = new createjs.Shape()
    corn.graphics.beginFill('white').drawCircle(evt.stageX, evt.stageY, 20).endFill()
    stage.addChild(corn)
    stage.update()
    alert(corn.x)

    corn.on("pressmove", function(dragEvent) {
        dragEvent.target.x = dragEvent.stageX;
        dragEvent.target.y = dragEvent.stageY;
        stage.update()
    });
})
</code>```

答:
You are mistaking the shape x/y position with the graphics coordinates. The shape is at [0,0], since you have not changed its x or y position.

Instead, draw the circle at [0,0], and move it to the mouse position.

```<code>var corn = new createjs.Shape()
    .set({x:evt.stageX, y:evt.stageY});
corn.graphics.beginFill('green').drawCircle(0,0,20).endFill();
</code>```

Here is a quick fiddle: http://jsfiddle.net/xnn803sx/

Body:
Trying to following the example at http://www.createjs.com/tutorials/Mouse%20Interaction/ , which shows how to drag and drop a shape. Something is going wrong for me. I add a circle when the stage is clicked, then I try to get it's x location... my alert shows a 0, but the circle appears in the right place. Then I try to drag, and the circle moves around, but at a distance from the mouse pointer.

var stage = new createjs.Stage("demoCanvas")
stage.on("stagemousedown", function(evt) {
    var corn = new createjs.Shape()
    corn.graphics.beginFill('white').drawCircle(evt.stageX, evt.stageY, 20).endFill()
    stage.addChild(corn)
    stage.update()
    alert(corn.x)

    corn.on("pressmove", function(dragEvent) {
        dragEvent.target.x = dragEvent.stageX;
        dragEvent.target.y = dragEvent.stageY;
        stage.update()
    });
})

Body:
You are mistaking the shape x/y position with the graphics coordinates. The shape is at [0,0], since you have not changed its x or y position.

Instead, draw the circle at [0,0], and move it to the mouse position.

var corn = new createjs.Shape()
    .set({x:evt.stageX, y:evt.stageY});
corn.graphics.beginFill('green').drawCircle(0,0,20).endFill();

Here is a quick fiddle: http://jsfiddle.net/xnn803sx/


问:
T-SQL Transaction Logging Issue
It's a long story, but I work for the research department of a school system, and we have beef with our IT department. A while back the IT dept. issued me a server with SQL installed on it and basically told me that I was on my own - they will not help with maintenance of the server or the behind-the-scenes functioning of the SQL database. For the most part this suits me fine, but I am not a DB Admin and I've never been able to solve setting up database backups and transaction logging.

The issue I'm trying to solve for now is transaction logging. Each night I use SSIS to pull in a large amount of records from our master database into my database.  I've chunked this process into 18 individual steps, and step 9 & 15 are to do transaction log backups. Unfortunately my process still crashes regularly due to the transaction log filling up -- sometimes even on Step 10 just after a backup.  I was going to disable logging during my process but have been reading and see that you cannot turn off logging.  I'm hoping there is a simple solution that I just don't know about...

I'm running:

```<code>Microsoft SQL Server 2012 (SP3-GDR) (KB3194721) - 11.0.6248.0 (X64)
Sep 23 2016 15:49:43
Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit)
on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor).
</code>```

Honestly I don't even know what type of transaction logging I'm doing or how to check and find out.

Any help would be greatly appreciated

答:
First, when you say,

Each night I use SSIS to pull in a large amount of records from our master database into my database

I presume this does not literally mean the system master database.  If it does, there should not be user objects in there and it should not be processing or storing any user data there.  If you are, migrate this to a user database.

Second, the short answer to the logging problem is this:
The default recovery model for a database is Full.  As noted in the comments, this means that no logs are overwritten until a back up occurs.  This model works for point in time recovery and makes sense for a transactional system. So there are a few options:

If this is a reporting system, it usually makes sense to put this into simple recovery model and do nightly backups.  Especially if the data is only changing once per day.

If you do require up to the minute point in time recovery, log backups should be performed every 15 min.  I'm guessing that the management and retention of these backups will make no sense for you and you should use option 1.

When processing data in an SSIS dataflow, each buffer is committed one at a time.  If you have not fiddled with the defaults, this means you are committing 10k rows at a maximum.  So everything is already getting nicely chunked up.  The problem then, is not that the batch sizes are too great, it is that you are in the wrong recovery model or that you are not backing up your logs often enough.

Title: T-SQL Transaction Logging Issue

Body:
It's a long story, but I work for the research department of a school system, and we have beef with our IT department. A while back the IT dept. issued me a server with SQL installed on it and basically told me that I was on my own - they will not help with maintenance of the server or the behind-the-scenes functioning of the SQL database. For the most part this suits me fine, but I am not a DB Admin and I've never been able to solve setting up database backups and transaction logging.

The issue I'm trying to solve for now is transaction logging. Each night I use SSIS to pull in a large amount of records from our master database into my database.  I've chunked this process into 18 individual steps, and step 9 & 15 are to do transaction log backups. Unfortunately my process still crashes regularly due to the transaction log filling up -- sometimes even on Step 10 just after a backup.  I was going to disable logging during my process but have been reading and see that you cannot turn off logging.  I'm hoping there is a simple solution that I just don't know about...

I'm running:

Microsoft SQL Server 2012 (SP3-GDR) (KB3194721) - 11.0.6248.0 (X64)
Sep 23 2016 15:49:43
Copyright (c) Microsoft Corporation  Enterprise Edition (64-bit)
on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor).

Honestly I don't even know what type of transaction logging I'm doing or how to check and find out.

Any help would be greatly appreciated


问:
Finding order of objects with OpenCV 3
With a group of friend, we are trying to accomplish a computer vision task on Raspberry Pi, coding with C++ using OpenCV library.

Let me explain the task first.
There is a pattern consisting of 16 seperate squares with each square being red, yellow or blue colored. We are mounting rasperry pi on a quadcopter with its camera module and gathering video feed of the pattern.

We have to detect colors of squares which was easy to accomplish with a little research on web. Tricky part is we have to detect order of the squares as well in order to save the colors in an array in an order.

So far we have accomplished filtering desired colors (red, yellow, blue) to determine squares.

example pattern to recognize and our process so far

In the second image, we know the colors and center points of each square. What we need is a way to write them in an order to a file or on screen.

And to find the order, we tried several OpenCV methods that find corners. With corner points at hand, we compared each point and determined end points so we could draw a boundingrectangle and overcome little distortions.

But since quadcopter gets the video stream, there is always a chance of high distortion. That messes up our corner theory, resulting in wrong order of colors. For example it can capture an image like this:

highly distorted image

It is not right to find order of these squares by comparing their center points. It also won't work finding endpoints to draw a larger rectangle around them to flatten pattern. And then order...

What I ask for is algorithm suggestions. Are we totally going in the wrong direction trying to find corners? Is it possible to determine the order without taking distortion into consideration?

Thanks in advance.

答:
Take the two centers that are the furthest apart and number them 1 and 16. Then find the two centers that are the furthest from the line 1-16, to the left (number 4) and to the right (number 13). Now you have the four corners.

Compute the affine transform that maps the coordinates of the corners 1, 4 and 13 to (0,0), (3,0) and (0,3). Apply this transform to the 16 centers and round to the nearest integers. If all goes well, you will obtain the "logical" coordinates of the squares, in range [0, 3] x [0, 3]. The mapping to the cell indexes is immediate.

Note that because of symmetry, a fourfold undeterminacy will remain, which you can probably lift by checking the color patterns.

This procedure will be very robust to deformations. If there is extreme perspective, you can even exploit the four corners to determine an homographic transform instead of affine. In your case, I doubt this will be useful. You can assess proper working by checking that all expected indexes have been assigned.

Title: Finding order of objects with OpenCV 3


问:
Changing the Value of an Attribute using javascript
Getting my script down to the bare bones, I have followed the example of the w3schools.com ( https://www.w3schools.com/js/js_htmldom_html.asp ) for: document.getElementById(id).attribute = new value. Their example:

```<code><!DOCTYPE html>
<html>
<body>

    <img id="myImage" src="smiley.gif">

<script>
    document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>
</code>```

Here is mine. I get no error messages on the Chrome console.

```<code><body>

    <img id = "indexPhoto" src =
        "newthaiimages/indexPhotos/indexPhoto_320.jpg"
         width="320" height="474" alt="hero sepia toned photo of Thai
         temple next to a river"/>

<script>

    document.getElementById("indexPhoto").scr =
        "newthaiimages/indexPhotos/indexPhoto_450.jpg";

</script>

</body>
</code>```

You can see the result at http://newthaimassage.com/index3.php . Here is the script not stripped down.

```<code><script>

    window.onload = function() {

       var w = window

   var x = w.innerWidth

switch(w.innerWidth){

    case x <= 320:

    break;

    case x <= 768:

        document.getElementById("indexPhoto").scr ="indexPhoto_450.jpg";

    break;

    case x <= 1024:

        document.getElementById("indexPhoto").scr ="indexPhoto_835.jpg";

    break;

    case x <= 1420:

        document.getElementById("indexPhoto").scr ="indexPhoto_1000.jpg";

    break;

    default:

        document.getElementById("indexPhoto").scr ="indexPhoto_1200.jpg";

}}

</script>
</code>```

Currently I am using CSS media queries to show images by window size, but using background images I can not use CSS animation, which is my ultimate goal here. Any help on this would be greatly appreciated.

答: It is syntax error, you should use document.getElementById("indexPhoto").src instead of document.getElementById("indexPhoto").scr, it is only one letter problem.

Body:
Getting my script down to the bare bones, I have followed the example of the w3schools.com ( https://www.w3schools.com/js/js_htmldom_html.asp ) for: document.getElementById(id).attribute = new value. Their example:

<!DOCTYPE html>

Here is mine. I get no error messages on the Chrome console.

You can see the result at http://newthaimassage.com/index3.php . Here is the script not stripped down.

Currently I am using CSS media queries to show images by window size, but using background images I can not use CSS animation, which is my ultimate goal here. Any help on this would be greatly appreciated.