问:
iPad css3 animation flickers after keyboard use
I'm developing an app for the iPad using HTML5/CSS3. I'm not using any framework and am just using whatever is natively supported on the device. I have created some css3 animations to emulate the typical iOS sliding left or sliding right when navigating between screens. Here's an example of the slide left animation which is taking advantage of the iPad's CSS3 hardware acceleration: (the ipad is running 4.2).

```<code>/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;

}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0%,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0%,0,0); }
}</code>```

I also have this CSS which I've attempted to use to fix the flicker:
```
.incoming,
.outgoing{
 display: block !important;
 -webkit-backface-visibility: hidden;
}
```

This works great until the iPad keyboard is used. After which point all the animations flicker severely.

I've been looking for examples of an iPad HTML5 app that uses the keyboard and doesn't have flickers afterwards, but haven't turned up much. The jqTouch demos exhibit the same behavior on the iPad (although I know they were designed for the iPhone).

I've turned up a few posts/questions of similar questions but have never found a good answer.  I've been through http://css3animator.com/2010/12/fight-the-flicker-making-your-css3-animation-bomb-proof/ and the articles linked there but haven't had any success.

Any other suggestions?

Update 1/13 @ 9am

I've added this css and it helped a lot:
```
.incoming *,
.outgoing *{
 -webkit-backface-visibility: hidden;
 -webkit-transform: translate3d(0,0,0); /* This helps with the flicker a lot. */
}
</code>```

The foreground elements don't seem to flicker anymore, but the backgrounds still do. Still looking for some help or helpful resources on Mobile Safari's memory handling tactics.

Update 1/16 @ 11pm

Increasing the z-index as suggested by anonymous. Didn't seem to make a difference.

Update 1/17 @ 8:30am

I've posted a demo of the problem here.

The transitions between screens work great...until you tap/click inside one of the form fields. After the keyboard slides up and returns, all the transitions flicker. Go to the URL inside the iOS simulator or on an actual iPad to see what I'm talking about.

答:
I agree with Ben, you should probably set transforms on the classes themselves as well:

```<code>/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
 -webkit-transform: translate3d(0,0,0);
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;
 -webkit-transform: translate3d(-100%,0,0);
}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
 -webkit-transform: translate3d(0,0,0);
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0,0,0); }
}
</code>```

If that doesn't work, I'd be curious to test if only translating the X with translateX(-100%) fixes the problem. (Not necessarily a fix, because you don't have hardware acceleration without 3D transforms, but would help narrow down the problem.)

Body:
I'm developing an app for the iPad using HTML5/CSS3. I'm not using any framework and am just using whatever is natively supported on the device. I have created some css3 animations to emulate the typical iOS sliding left or sliding right when navigating between screens. Here's an example of the slide left animation which is taking advantage of the iPad's CSS3 hardware acceleration: (the ipad is running 4.2).

/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;

}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0%,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0%,0,0); }
}

I also have this CSS which I've attempted to use to fix the flicker:

.incoming,
.outgoing{
 display: block !important;
 -webkit-backface-visibility: hidden;
}

This works great until the iPad keyboard is used. After which point all the animations flicker severely.

I've been looking for examples of an iPad HTML5 app that uses the keyboard and doesn't have flickers afterwards, but haven't turned up much. The jqTouch demos exhibit the same behavior on the iPad (although I know they were designed for the iPhone).

I've turned up a few posts/questions of similar questions but have never found a good answer.  I've been through http://css3animator.com/2010/12/fight-the-flicker-making-your-css3-animation-bomb-proof/ and the articles linked there but haven't had any success.

Any other suggestions?

Update 1/13 @ 9am

I've added this css and it helped a lot:

.incoming *,
.outgoing *{
 -webkit-backface-visibility: hidden;
 -webkit-transform: translate3d(0,0,0); /* This helps with the flicker a lot. */
}

The foreground elements don't seem to flicker anymore, but the backgrounds still do. Still looking for some help or helpful resources on Mobile Safari's memory handling tactics.

Update 1/16 @ 11pm

Increasing the z-index as suggested by anonymous. Didn't seem to make a difference.

Update 1/17 @ 8:30am

I've posted a demo of the problem here.

The transitions between screens work great...until you tap/click inside one of the form fields. After the keyboard slides up and returns, all the transitions flicker. Go to the URL inside the iOS simulator or on an actual iPad to see what I'm talking about.

Body:
I agree with Ben, you should probably set transforms on the classes themselves as well:

/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
 -webkit-transform: translate3d(0,0,0);
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;
 -webkit-transform: translate3d(-100%,0,0);
}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
 -webkit-transform: translate3d(0,0,0);
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0,0,0); }
}

If that doesn't work, I'd be curious to test if only translating the X with translateX(-100%) fixes the problem. (Not necessarily a fix, because you don't have hardware acceleration without 3D transforms, but would help narrow down the problem.)


来源: stackexchange

问:
CSS font-spacing issue with Calibri and the letters "ti"
I'm starting a website build for a small business that uses Calibri as the primary font for their branding and I have come across an issue with using this font in certain web browsers.

In Google Chrome and Opera, the letters "ti" appear to be joined.  When I apply some letter-spacing, they will not separate.  This doesn't happen in Mozilla Firefox or Microsoft Edge.

Is there an issue with the font, or is it the browser?
Is there anything I can do to fix it?

I've created a snippet for testing (or you can test at https://codepen.io/whitenoise83/pen/KyXWWL)

#site-title {
  font-family: Calibri, Candara, Segoe, "Segoe UI", Optima,  Arial, sans-serif !important;
  color: #e00b00;
  font-size: 6em;
  font-weight: bold;
  /*letter-spacing: 0.25em;*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="site-title">Audiomation</span> </code>```

答:
You can use font-variant-ligatures: none; in your CSS to prevent the browser using special ligature characters for some combinations of characters/letters.

See also this article: http://www.cssportal.com/css-properties/font-variant-ligatures.php

#site-title {
  font-family: Calibri, Candara, Segoe, "Segoe UI", Optima,  Arial, sans-serif !important;
  font-variant-ligatures: none;
  color: #e00b00;
  font-size: 6em;
  font-weight: bold;
  letter-spacing: 0.05em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="site-title">Audiomation</span></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm starting a website build for a small business that uses Calibri as the primary font for their branding and I have come across an issue with using this font in certain web browsers.

In Google Chrome and Opera, the letters "ti" appear to be joined.  When I apply some letter-spacing, they will not separate.  This doesn't happen in Mozilla Firefox or Microsoft Edge.

Is there an issue with the font, or is it the browser?
Is there anything I can do to fix it?

I've created a snippet for testing (or you can test at https://codepen.io/whitenoise83/pen/KyXWWL)

#site-title {
  font-family: Calibri, Candara, Segoe, "Segoe UI", Optima,  Arial, sans-serif !important;
  color: #e00b00;
  font-size: 6em;
  font-weight: bold;
  /*letter-spacing: 0.25em;*/
}

Audiomation

Body:
You can use font-variant-ligatures: none; in your CSS to prevent the browser using special ligature characters for some combinations of characters/letters.

See also this article: http://www.cssportal.com/css-properties/font-variant-ligatures.php

#site-title {
  font-family: Calibri, Candara, Segoe, "Segoe UI", Optima,  Arial, sans-serif !important;
  font-variant-ligatures: none;
  color: #e00b00;
  font-size: 6em;
  font-weight: bold;
  letter-spacing: 0.05em;
}

<span id="site-title">Audiomation</span>


问:
From png to jpeg, what to do after huffman
I've be trying to code in Python a script that takes as input a png image, and as output I'd like to create a .jpeg version of the same image.
This is for a school project, and the goal is to code every step of the process.
I've done most of the job right now (8x8 blocs, DCT, Quantization, Zigzag, Huffman...) but I find myself stuck at this place.

I've read many papers and tutorials, but I didn't find what am I supposed to do after the Huffman encoding.

Since I'm using the YUV color encoding, I have 2 matrices Cr and Cb and the code corresponding to the Huffman encoding of the Y matrix. What should I do with that ? My guess is I should create a file and write in it the Huffman Table, the Y matrix encoded and the two other matrices, but I can't just store data like that and expect the file to be read by a random image viewer outside the script.

I'm a little bit lost here, I hope I'm still clear... Anyway, some help would be greatly appreciated. Some explanations or even a simple link to a page I've missed.

Thanks in advance.

答:
This is the only book that actually explains the process for programmers without academic mumbo-jumbo

https://www.amazon.com/Compressed-Image-File-Formats-JPEG/dp/0201604434/ref=sr_1_2?ie=UTF


问:
Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?
The indexer into Dictionary throws an exception if the key is missing.  Is there an implementation of IDictionary that instead will return default(T)?

I know about the TryGetValue() method, but that's impossible to use with LINQ.

Would this efficiently do what I need?:

```<code>myDict.FirstOrDefault(a => a.Key == someKeyKalue);
</code>```

I don't think it will as I think it will iterate the keys instead of using a Hash lookup.

答:
Here is a version of @JonSkeet's for the world of C# 7.1 that also allows for an optional default to be passed in:

```<code>public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
</code>```

It may be more efficient to have two functions to optimize the case where you want to return default(TV):

```<code>public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
public static TV GetValueOrDefault2<TK, TV>(this IDictionary<TK, TV> dict, TK key) {
    dict.TryGetValue(key, out TV value);
    return value;
}
</code>```

Unfortunately C# doesn't (yet?) have a comma operator (or the C# 6 proposed semicolon operator) so you have to have an actual function body (gasp!) for one of the overloads.

OwnerDisplayName: TheSoftwareJedi

ContentLicense: CC BY-SA 4.0

Body:
The indexer into Dictionary throws an exception if the key is missing.  Is there an implementation of IDictionary that instead will return default(T)?

I know about the TryGetValue() method, but that's impossible to use with LINQ.

Would this efficiently do what I need?:

myDict.FirstOrDefault(a => a.Key == someKeyKalue);

I don't think it will as I think it will iterate the keys instead of using a Hash lookup.

Body:
Here is a version of @JonSkeet's for the world of C# 7.1 that also allows for an optional default to be passed in:

public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default) => dict.TryGetValue(key, out TV value) ? value : defaultValue;

It may be more efficient to have two functions to optimize the case where you want to return default(TV):

public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue) => dict.TryGetValue(key, out TV value) ? value : defaultValue;
public static TV GetValueOrDefault2<TK, TV>(this IDictionary<TK, TV> dict, TK key) {
    dict.TryGetValue(key, out TV value);
    return value;
}

Unfortunately C# doesn't (yet?) have a comma operator (or the C# 6 proposed semicolon operator) so you have to have an actual function body (gasp!) for one of the overloads.


问:
Indentation issue in RStudio
Like many others, I like writing my codes on several lines and I appreciate the auto-indent feature offered by RStudio. The issue suddenly started when the word undefined showed up in the code editor whenever I pressed Enter as I expected an automatic indentation. It is important to mention that this does not affect the proper running of the code.

```<code>my_fun <- function(xxx){
undefined
}
</code>```

NB: Actually, when I copied and pasted the code here, undefined was not copied to! I had to manually add it. Here is another example.

```<code>library(magrittr)
mtcars %>%
undefinedhead()
</code>```

答:
Basically this is just RStudio telling you that you have not preset your tab spaces, but it is not actually dropping commands into your code.

You have the option of setting tabs to however many spaces you feel is appropriate and it allows teams to work with consistent spacing.

If you go to the main menu and click on Tools > Global Options and on the second tab in the left column click onCode . There you can set the spaces to meet your personal needs (or teams profile) and the undefined message will disappear.

This photgraph shows where you can find the preferences.

Title: Indentation issue in RStudio

Body:
Like many others, I like writing my codes on several lines and I appreciate the auto-indent feature offered by RStudio. The issue suddenly started when the word undefined showed up in the code editor whenever I pressed Enter as I expected an automatic indentation. It is important to mention that this does not affect the proper running of the code.

my_fun <- function(xxx){
undefined
}

NB: Actually, when I copied and pasted the code here, undefined was not copied to! I had to manually add it. Here is another example.

library(magrittr)
mtcars %>%
undefinedhead()


问:
header location does not work in facebook app
I'm trying to redirect users to the permission page in my facebook app if they have not added the app. The problem is that using the following just sends them to a page with a large blue facebook logo that the user has to click to see the permissions.

```<code>$login_url = $facebook->getLoginUrl(array(
    'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos',

));

header("Location: ".$login_url);
</code>```

I am using an iframe app. Any help would be really appreciated.

答:
If you are using FBML then try this

```<code><fb:redirect url="http://apps.facebook.com/myapp/?not_in_group" />
</code>```

Check Documentation

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to redirect users to the permission page in my facebook app if they have not added the app. The problem is that using the following just sends them to a page with a large blue facebook logo that the user has to click to see the permissions.

$login_url = $facebook->getLoginUrl(array(
    'req_perms' => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos',

));

header("Location: ".$login_url);

I am using an iframe app. Any help would be really appreciated.

Body:
If you are using FBML then try this

<fb:redirect url="http://apps.facebook.com/myapp/?not_in_group" />

Check Documentation


问:
Access Laravel site outside of network
I am trying to access my laravel site outside of the network to test functionality, but I am running into some roadblocks I don't quite understand. I have found my computers public IP address, and I have my php artisan serving up my server (for development, won't go into production) yet when I go to the public IP address, it says "this site cannot be reached". I have tried to change my config files (000-default, default-ssl, apache2.conf, etc.) to have the servername be the same as my ip address, but still no luck. I am still a little new at server side things, and could use any help that is offered. Thank you for your help and suggestions!</p>

答:
If you are using mac you can install laravel's own tool valet so that you can have access to feature like site sharing just by running valet share in your command inside laravel project. Of course installing valet is not necessary what so ever.

There is a great tool called ngrok that helps you to share your local server globally. You can use either http or https to share you site.

You can follow the guide here at https://ngrok.com/

Title: Access Laravel site outside of network


问:
How to check if an input string is part of any component of any tuple
I am having issues with using an input string and checking to see if it is part of a tuple in the data list.

```<code>data = [(Mr. John Doe, 345.678.9765, johndoe@gmail.com),
        (Ms. Mary Doe, 345.123.4567, marydoe@gmail.com)]
print("Search for: ")
s = input()
while s:
   for a in data:
    if any(b[0] == s for b in a):
        print(a)
    else:
        print("Not Found")
print("Search for: ")
s = input()
</code>```

If I enter in Mr. as the input it will fail to find the component in the tuple, but if I enter j as the input it will print out:

```<code> (Mr. John Doe, 345.678.9765, johndoe@gmail.com)
</code>```

答:
any(b[0] == s for b in a) will only be True if the user inputs the full name exactly as it is in name string, (e.g. Mr. John Doe). Instead, check if the user input is in any part of the name string using the in operator:

```<code>data = [('Mr. John Doe', '345.678.9765', 'johndoe@gmail.com'),
        ('Ms. Mary Doe', '345.123.4567', 'marydoe@gmail.com')]

print("Search for: ")

s = input()

result = None # set a variable to hold our result

for a in data:
    if any(s in b for b in a): # use in to check if substring 's' is in string 'b'
        result = a[0]  # save the name that contains user input
        break          # exit loop if found
    else:
        result = "Not Found"

print(result)
</code>```

The reason it was failing with Mr. input is because b[0] in b[0] == s for b in a refers to the first letter in each string in the tuple, and a 3-character string will never equal a single character.

Similarly, when we input j, the comparison b[0] == s for b in a does match the first character in the last string of the first tuple (j in johndoe@gmail.com), so it did output that tuple.

Hope this helps.

Body:
I am having issues with using an input string and checking to see if it is part of a tuple in the data list.

data = [(Mr. John Doe, 345.678.9765, johndoe@gmail.com),
        (Ms. Mary Doe, 345.123.4567, marydoe@gmail.com)]
print("Search for: ")
s = input()
while s:
   for a in data:
    if any(b[0] == s for b in a):
        print(a)
    else:
        print("Not Found")
print("Search for: ")
s = input()

If I enter in Mr. as the input it will fail to find the component in the tuple, but if I enter j as the input it will print out:

 (Mr. John Doe, 345.678.9765, johndoe@gmail.com)

Body:
any(b[0] == s for b in a) will only be True if the user inputs the full name exactly as it is in name string, (e.g. Mr. John Doe). Instead, check if the user input is in any part of the name string using the in operator:

data = [('Mr. John Doe', '345.678.9765', 'johndoe@gmail.com'),
        ('Ms. Mary Doe', '345.123.4567', 'marydoe@gmail.com')]

print("Search for: ")

s = input()

result = None # set a variable to hold our result

for a in data:
    if any(s in b for b in a): # use in to check if substring 's' is in string 'b'
        result = a[0]  # save the name that contains user input
        break          # exit loop if found
    else:
        result = "Not Found"

print(result)

The reason it was failing with Mr. input is because b[0] in b[0] == s for b in a refers to the first letter in each string in the tuple, and a 3-character string will never equal a single character.

Similarly, when we input j, the comparison b[0] == s for b in a does match the first character in the last string of the first tuple (j in johndoe@gmail.com), so it did output that tuple.

Hope this helps.


问:
Firebase load related data iOS
What's the best way to load "related" data in swift?

Common setup, if I have a list of users all stored under uid node and contains a list of follows which stores uids, something like:

"users" : {
    "abc123" : {
      "email" : "test@test.com",
      "follows" : {
        "xyz789" : true
      }
    },
    "xyz789" : { ... }
}

What's the most efficient way of loading in the data for all the users one user follows? Is it best to loop through each of the uid's with observeSingleEvent(of: .value)?

This is the solution I've come up with, but feels somewhat cumbersome:

```<code>func loadRelated(user: User, completion: @escaping (Bool, [UserObject]) -> ()) {

  let ref = Database.database().reference(withPath: "users/" + user.uid + "/follows")
  ref.observeSingleEvent(of: .value) { snapshot in

    var uids = [String]()
    for child in snapshot.children {
      let userData = child as! DataSnapshot
      uids.append(userData.key)
    }

    let userRef = Database.database().reference(withPath: "users")
    var users = [UserObject]()
    var count = 0
    uids.forEach { uid in
      userRef.child(uid).observeSingleEvent(of: .value) { snapshot in
        let user: UserObject(from: snapshot)
        users.append(user)
        count += 1
        if count == uids.count {
          completion(true, users)
        }
      }
    }
  }
}
</code>```

I don't really want to go down the denormalization path and store each users data under the top level user.

答:
If you are decided on using Realtime Database, it is best practice to create another root node in your case called user-follows. You can create a follow at the path user-follows/$uid/$fid by setting the value to true, then on your app you would have to observeSingleEvent for each snapshot key ($fid) at user-follows/$uid.

To avoid having to observe each follow separately, instead of setting the value to true, you can just store the data you need about a user in user-follows/$uid. However, a user may change their username for example and so you would need to keep the data inside each user-follows up to date. You can utilise Firebase Cloud Functions to maintain the user-follows when a user changes their information.

Otherwise, I would suggest looking at Firebase Firestore, where some nesting is allowed.

Title: Firebase load related data iOS

Body:
What's the best way to load "related" data in swift?

Common setup, if I have a list of users all stored under uid node and contains a list of follows which stores uids, something like:

"users" : {
    "abc123" : {
      "email" : "test@test.com",
      "follows" : {
        "xyz789" : true
      }
    },
    "xyz789" : { ... }
}

What's the most efficient way of loading in the data for all the users one user follows? Is it best to loop through each of the uid's with observeSingleEvent(of: .value)?

This is the solution I've come up with, but feels somewhat cumbersome:

func loadRelated(user: User, completion: @escaping (Bool, [UserObject]) -> ()) {

  let ref = Database.database().reference(withPath: "users/" + user.uid + "/follows")
  ref.observeSingleEvent(of: .value) { snapshot in

    var uids = [String]()
    for child in snapshot.children {
      let userData = child as! DataSnapshot
      uids.append(userData.key)
    }

    let userRef = Database.database().reference(withPath: "users")
    var users = [UserObject]()
    var count = 0
    uids.forEach { uid in
      userRef.child(uid).observeSingleEvent(of: .value) { snapshot in
        let user: UserObject(from: snapshot)
        users.append(user)
        count += 1
        if count == uids.count {
          completion(true, users)
        }
      }
    }
  }
}

I don't really want to go down the denormalization path and store each users data under the top level user.


问:
How to open dired in another buffer from ido mode?
I usually keep two buffers side by side, say left-buffer and right-buffer.

As I frequently need to check directory structure for the current buffer I am editing (this happens often when I am writing javascript files and need to include another script with relative path), I type C-x C-f to open ido mode and then type Enter to open dired.

Problem is, this way the dired buffer took the place of my current left-buffer which I am working on.

Is there a way to open ido-mode in "the other buffer" (here is the right-buffer)?

EDIT
I also have projectile-mode winner-mode installed. If any of these mode contains ready-command to do so, it will work as well.

答:
Enable opening the pwd in ido:

```<code>(setq ido-show-dot-for-dired t)
</code>```

Then you can do e.g. C-x C-f and one of the options is ., which will open a dired buffer for the pwd.

There's a command find-file-in-other-window, bound to C-x 4 f and C-x 4 C-f by default, that you can use to open any file, including a directory, in another window.

Note that default-directory is the directory that ido looks in, not necessarily the directory of buffer-file-name, though default-directory defaults to that.

Body:
Enable opening the pwd in ido:

(setq ido-show-dot-for-dired t)

Then you can do e.g. C-x C-f and one of the options is ., which will open a dired buffer for the pwd.

There's a command find-file-in-other-window, bound to C-x 4 f and C-x 4 C-f by default, that you can use to open any file, including a directory, in another window.

Note that default-directory is the directory that ido looks in, not necessarily the directory of buffer-file-name, though default-directory defaults to that.


问:
onelogin - get admin privileges via api
We're building a small integration with onelogin to just pull out lists of users and which apps they have. Easy enough via the API.

But we are also wanting to get a list of the administrative privileges like super user, manage accounts, and so on. The docs don't mention those. Is there any way to pull out those details via the API?

Thank you!

答: At this time you can't do that. You are limited to roles and groups.</p>

Title: onelogin - get admin privileges via api


问:
Extract text value from an object to set the text in a listView
I'm trying set the text in my listView to the string value in my FavJokes class.

```<code>class FavJokes {
var index: Int? = null
var string: String? = null
}
</code>```

When ever a user favorites a joke, I create a FavObject instance and assign it values for the index(as the Jokes are stored in an array) and the string value of the joke.

```<code>val newFav = FavJokes()
newFav.index = primaFreeze!!
newFav.string = ("${questionProvider.quesRegistry[primaFreeze!!]}... ${answerProvider.ansRegistry[primaFreeze!!]}")
favorites.add(newFav)
</code>```

When I try to use this array of FavJoke objects as the datasource for my listView what I see is my project id and ".FavJokes@ee8e3e" show up on the listView itself.

I don't think I should populate the listView with just the string value for the joke because for my setOnItemClick{} method, the view I segue to is going to need the index of the joke in order to populate the textView with the correct joke.

I'm new to kotlin/Java started learning it about 3 days ago, but I do have some Swift experience. In Swift I could use an IndexPath object to get/set the values for my tableView. Is there such an object or a method that I can access and set the TextView.text values in Kotlin/Java?

答:
In Android you set an adapter on the list view and then add a setOnItemClickListener, which when called will be provided with the index of the item in the list.

One the simplest adapters is an ArrayAdapter.

Here is a tutorial from a familiar source.

And here is a quick example from some existing code.

in OnCreateView I get my list view.

```<code> override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val rootView = inflater!!.inflate(R.layout.fragment_target_selection, container, false)
        targetList = rootView.findViewById(R.id.names_list) as ListView
        return rootView
    }
</code>```

then in my onResume I receive an array of objects which I then use to create my adapter.

```<code>    disposables.add(telescopeInterface.namesListStream.subscribe {
        println("here is the names list")
        namesList = it
        namesListAdapter = ArrayAdapter(this.context, android.R.layout.simple_list_item_1, namesList?.names)
        println("setting up list view with the updated list")
        setupListView()
    })
</code>```

then in the setupListView() I assign the adapter to the list view and add a listener.

```<code>   private fun setupListView() {
        namesListAdapter?.let { targetList.adapter = it }
        targetList.setOnItemClickListener { adapterView, view, i, l ->
            targetSelectionListenter?.targetSelected()
            val entry = adapterView.getItemAtPosition(i)
            println("item $entry")
            telescopeInterface.sendSelectedTarget(entry as DSOCatalogNameEntry)
        }
    }
</code>```

The full object remains in the list, the adapter is just used to select what is displayed in the list view, then you get the index of the selection, which you then use to extract the full object from your source list.

Body:
I'm trying set the text in my listView to the string value in my FavJokes class.

class FavJokes {
var index: Int? = null
var string: String? = null
}

When ever a user favorites a joke, I create a FavObject instance and assign it values for the index(as the Jokes are stored in an array) and the string value of the joke.

val newFav = FavJokes()
newFav.index = primaFreeze!!
newFav.string = ("${questionProvider.quesRegistry[primaFreeze!!]}... ${answerProvider.ansRegistry[primaFreeze!!]}")
favorites.add(newFav)

When I try to use this array of FavJoke objects as the datasource for my listView what I see is my project id and ".FavJokes@ee8e3e" show up on the listView itself.

I don't think I should populate the listView with just the string value for the joke because for my setOnItemClick{} method, the view I segue to is going to need the index of the joke in order to populate the textView with the correct joke.

I'm new to kotlin/Java started learning it about 3 days ago, but I do have some Swift experience. In Swift I could use an IndexPath object to get/set the values for my tableView. Is there such an object or a method that I can access and set the TextView.text values in Kotlin/Java?

Body:
In Android you set an adapter on the list view and then add a setOnItemClickListener, which when called will be provided with the index of the item in the list.

One the simplest adapters is an ArrayAdapter.

Here is a tutorial from a familiar source.

And here is a quick example from some existing code.

in OnCreateView I get my list view.

 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val rootView = inflater!!.inflate(R.layout.fragment_target_selection, container, false)
        targetList = rootView.findViewById(R.id.names_list) as ListView
        return rootView
    }

then in my onResume I receive an array of objects which I then use to create my adapter.

    disposables.add(telescopeInterface.namesListStream.subscribe {
        println("here is the names list")
        namesList = it
        namesListAdapter = ArrayAdapter(this.context, android.R.layout.simple_list_item_1, namesList?.names)
        println("setting up list view with the updated list")
        setupListView()
    })

then in the setupListView() I assign the adapter to the list view and add a listener.

   private fun setupListView() {
        namesListAdapter?.let { targetList.adapter = it }
        targetList.setOnItemClickListener { adapterView, view, i, l ->
            targetSelectionListenter?.targetSelected()
            val entry = adapterView.getItemAtPosition(i)
            println("item $entry")
            telescopeInterface.sendSelectedTarget(entry as DSOCatalogNameEntry)
        }
    }

The full object remains in the list, the adapter is just used to select what is displayed in the list view, then you get the index of the selection, which you then use to extract the full object from your source list.


问:
DB2 SQL point in time data on a transactional table
I am trying to extract point in time information from a history table.  The table contains fld_nbr which maps to attributes such as job codes, employee status, work location, etc.  How can I find what an employee's status is as of a particular date.  The data might show

```<code>Employee# fld_nbr beg_date value
1234      19      10/1/16  AA
1234      14      10/1/16  40
1234      14      1/6/17   46
1234      19      9/15/17  LA
</code>```

I need to find what the status (fld_nbr 19) and location (fld_nbr 14) was on 1/1/17.  I would expect my result set to be fld_nbr 19 = AA and fld_nbr 14 = 40.

EDIT Here is what I ended up with:

```<code>WITH MO1 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO1_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31')) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31')
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 365 DAYS AND DATE('2017-10-31')
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE),
MO2 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO2_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31') - 1 MONTH) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31') - 1 MONTH
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 1 MONTH - 365 DAYS AND DATE('2017-10-31') - 1 MONTH
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE)
SELECT MO1.AFFILIATE, MO1.MO1_HC, MO2.MO2_HC
FROM MO1
INNER JOIN MO2 ON MO2.AFFILIATE = MO1.AFFILIATE
</code>```

答:
I suggest massage the data to reflect date ranges using LEAD() then it becomes simple to isolate which values applied on any single date.

```<code>select
*
from (
    select
        employee
      , fld_nbr
      , beg_date
      , coalesce(lead(beg_date,1) over(partition by Employee, fld_nbr order by beg_date), current date) end_date
    from table1
    ) d
where beg_date <= date('2017-01-01')
and end_date > date('2017-01-01')
</code>```

e.g.

```<code>| employee | fld_nbr |             beg_date |             end_date |
|----------|---------|----------------------|----------------------|
|     1234 |      14 | 2016-10-01T00:00:00Z | 2017-01-06T00:00:00Z |
|     1234 |      19 | 2016-10-01T00:00:00Z | 2017-09-15T00:00:00Z |
</code>```

nb: my example was written using TSQL so my DB2 syntax might be a little off

Demo

Body:
I am trying to extract point in time information from a history table.  The table contains fld_nbr which maps to attributes such as job codes, employee status, work location, etc.  How can I find what an employee's status is as of a particular date.  The data might show

Employee# fld_nbr beg_date value
1234      19      10/1/16  AA
1234      14      10/1/16  40
1234      14      1/6/17   46
1234      19      9/15/17  LA

I need to find what the status (fld_nbr 19) and location (fld_nbr 14) was on 1/1/17.  I would expect my result set to be fld_nbr 19 = AA and fld_nbr 14 = 40.

EDIT Here is what I ended up with:

WITH MO1 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO1_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31')) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31')
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 365 DAYS AND DATE('2017-10-31')
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE),
MO2 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO2_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31') - 1 MONTH) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31') - 1 MONTH
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 1 MONTH - 365 DAYS AND DATE('2017-10-31') - 1 MONTH
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE)
SELECT MO1.AFFILIATE, MO1.MO1_HC, MO2.MO2_HC
FROM MO1
INNER JOIN MO2 ON MO2.AFFILIATE = MO1.AFFILIATE

Body:
I suggest massage the data to reflect date ranges using LEAD() then it becomes simple to isolate which values applied on any single date.

select
*
from (
    select
        employee
      , fld_nbr
      , beg_date
      , coalesce(lead(beg_date,1) over(partition by Employee, fld_nbr order by beg_date), current date) end_date
    from table1
    ) d
where beg_date <= date('2017-01-01')
and end_date > date('2017-01-01')

e.g.

| employee | fld_nbr |             beg_date |             end_date |
|----------|---------|----------------------|----------------------|
|     1234 |      14 | 2016-10-01T00:00:00Z | 2017-01-06T00:00:00Z |
|     1234 |      19 | 2016-10-01T00:00:00Z | 2017-09-15T00:00:00Z |

nb: my example was written using TSQL so my DB2 syntax might be a little off

Demo


问:
Long multiplication in Haskell
How would you implement long multiplication on lists in Haskell. The idea being that if you have two numbers, let's say 112 and 13. These numbers can be represented as lists [1,1,2] and [1,3] and you want to multiply them together to get a list [1,4,5,6]. I want to do this recursively as I want it to work on any size list. My "functionWhichSumsLists" is a function I will define later which will add two lists element-wise.</p>

```<code>longMulti l1 [] = p1
longMulti [] l2 = q1
longMulti (li:l1) (lii:l2) = functionWhichSumsLists [li*lii] (0:(longMulti l1 l2))
</code>```

答:
Rather than converting back and forth to String with show, you can use modular arithmetic.

```<code>toDigits :: Integral a => a -> [a]
toDigits = go [] where
  go acc 0 = acc
  go acc x = let (xs, x') = x `divMod` 10
             in go (x':acc) xs
</code>```

Then fromDigits can be implemented with a foldl.

```<code>import Data.List (foldl')

fromDigits :: Integral a => [a] -> a
fromDigits = foldl' (\acc x -> acc * 10 + x) 0
</code>```

or indeed with zipWith (*)

```<code>-- note: this is significantly slower than above because of the necessary
--       calls to reverse.
fromDigits = sum . reverse . (zipWith (*) [10^i | i <- [0..]]) . reverse
</code>```

What's left is the multiplication itself. Do be careful though, because the naive approach doesn't work here.

```<code>terms = [112, 13]
[xs, ys] = map toDigits terms
wrongAnswer = fromDigits $ zipWith (*) xs ys
-- 13
</code>```

zipWith (*) [1, 1, 2] [1, 3], as above, becomes [1*1, 1*3] which is obviously wrong when you sit down and imagine it. Well then, we have to cross multiply and sum, right?

```<code>alsoWrong = fromDigits $ answerDigits where
  answerDigits = zipWith (+) [map (*y) xs | y <- ys]
-- 448
</code>```

This expands out to

```<code>zipWith (+) [map (*1) [1, 1, 2], map (*3) [1, 1, 2]]
= zipWith (+) [[1, 1, 2], [3, 3, 6]]
= [(1+3), (1+3), (2+6)]
= [4, 4, 8] -- fromDigits yields 448
</code>```

This is equivalent to doing by hand:

```<code>    112
   x 13
   ----
    336
    112  <--- note this should be slid to the left
   ----
    448
</code>```

So instead we can apply a similar technique to the folding fromDigits to each term.

```<code>sum $ map fromDigits $ zipWith (\p xs -> map (*p) xs) tens eachProduct where
  tens        = [10^i | i <- [len-1, len-2..0]]
  eachProduct = [map (*y) xs | y <- ys]
  len         = length eachProduct
</code>```

ending up with:

```<code>longMultiplication :: Integral a => a -> a -> a
longMultiplication x y = sum . map fromDigits . zipWith mapper tens $ eachProduct where
    xs          = toDigits x
    ys          = toDigits y
    mapper      = (\p xs -> map (*p) xs)
    tens        = [10^i | i <- [len-1, len-2..0]]
    len         = length eachProduct
    eachProduct = [map (*y') xs | y' <- ys]
</code>```

Title: Long multiplication in Haskell

Body:
How would you implement long multiplication on lists in Haskell. The idea being that if you have two numbers, let's say 112 and 13. These numbers can be represented as lists [1,1,2] and [1,3] and you want to multiply them together to get a list [1,4,5,6]. I want to do this recursively as I want it to work on any size list. My "functionWhichSumsLists" is a function I will define later which will add two lists element-wise.

longMulti l1 [] = p1
longMulti [] l2 = q1
longMulti (li:l1) (lii:l2) = functionWhichSumsLists [li*lii] (0:(longMulti l1 l2))

Body:
Rather than converting back and forth to String with show, you can use modular arithmetic.

toDigits :: Integral a => a -> [a]
toDigits = go [] where
  go acc 0 = acc
  go acc x = let (xs, x') = x `divMod` 10
             in go (x':acc) xs

Then fromDigits can be implemented with a foldl.

import Data.List (foldl')

fromDigits :: Integral a => [a] -> a
fromDigits = foldl' (\acc x -> acc * 10 + x) 0

or indeed with zipWith (*)

-- note: this is significantly slower than above because of the necessary
--       calls to reverse.
fromDigits = sum . reverse . (zipWith (*) [10^i | i <- [0..]]) . reverse

What's left is the multiplication itself. Do be careful though, because the naive approach doesn't work here.

terms = [112, 13]
[xs, ys] = map toDigits terms
wrongAnswer = fromDigits $ zipWith (*) xs ys
-- 13

zipWith (*) [1, 1, 2] [1, 3], as above, becomes [1*1, 1*3] which is obviously wrong when you sit down and imagine it. Well then, we have to cross multiply and sum, right?

alsoWrong = fromDigits $ answerDigits where
  answerDigits = zipWith (+) [map (*y) xs | y <- ys]
-- 448

This expands out to

zipWith (+) [map (*1) [1, 1, 2], map (*3) [1, 1, 2]]
= zipWith (+) [[1, 1, 2], [3, 3, 6]]
= [(1+3), (1+3), (2+6)]
= [4, 4, 8] -- fromDigits yields 448

This is equivalent to doing by hand:

    112
   x 13
   ----
    336
    112  <--- note this should be slid to the left
   ----
    448

So instead we can apply a similar technique to the folding fromDigits to each term.

sum $ map fromDigits $ zipWith (\p xs -> map (*p) xs) tens eachProduct where
  tens        = [10^i | i <- [len-1, len-2..0]]
  eachProduct = [map (*y) xs | y <- ys]
  len         = length eachProduct

ending up with:

longMultiplication :: Integral a => a -> a -> a
longMultiplication x y = sum . map fromDigits . zipWith mapper tens $ eachProduct where
    xs          = toDigits x
    ys          = toDigits y
    mapper      = (\p xs -> map (*p) xs)
    tens        = [10^i | i <- [len-1, len-2..0]]
    len         = length eachProduct
    eachProduct = [map (*y') xs | y' <- ys]


问:
how to rotate CALayer at one point
how to rotate CALayer at one selected point. </p>

答:
Define your sublayer that you want to rotate;

Set its bounds, position in superlayer and anchorPoint. anchorPoint has relative coordinates and points to an anchorPoint. Your sublayer will rotate around this anchorPoint;

Add transformation.

For example, to rotate a sublayer on its superview top center point around sublayer's bottom center, use this code:

```<code>    // 1
    let rect = CGRect(x: 0,
                      y: 0,
                      width: 20,
                      height: 20)
    let path = UIBezierPath(rect: rect)
    let sublayer = CAShapeLayer()
    sublayer.fillColor = UIColor.green.cgColor
    sublayer.path = path.cgPath
    superlayer.addSublayer(sublayer)

    // 2
    sublayer.bounds = rect
    sublayer.position = CGPoint(x: superlayer.bounds.size.width/2, y: 0)
    sublayer.anchorPoint = CGPoint(x: 0.5, y: 1)

    // 3
    let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotationAnimation.toValue = 2*CGFloat.pi
    rotationAnimation.duration = 3
    rotationAnimation.fillMode = kCAFillModeForwards
    rotationAnimation.isRemovedOnCompletion = false
    sublayer.add(rotationAnimation, forKey: nil)
</code>```

Title: how to rotate CALayer at one point

Body:
Define your sublayer that you want to rotate;

Set its bounds, position in superlayer and anchorPoint. anchorPoint has relative coordinates and points to an anchorPoint. Your sublayer will rotate around this anchorPoint;

Add transformation.

For example, to rotate a sublayer on its superview top center point around sublayer's bottom center, use this code:

    // 1
    let rect = CGRect(x: 0,
                      y: 0,
                      width: 20,
                      height: 20)
    let path = UIBezierPath(rect: rect)
    let sublayer = CAShapeLayer()
    sublayer.fillColor = UIColor.green.cgColor
    sublayer.path = path.cgPath
    superlayer.addSublayer(sublayer)

    // 2
    sublayer.bounds = rect
    sublayer.position = CGPoint(x: superlayer.bounds.size.width/2, y: 0)
    sublayer.anchorPoint = CGPoint(x: 0.5, y: 1)

    // 3
    let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotationAnimation.toValue = 2*CGFloat.pi
    rotationAnimation.duration = 3
    rotationAnimation.fillMode = kCAFillModeForwards
    rotationAnimation.isRemovedOnCompletion = false
    sublayer.add(rotationAnimation, forKey: nil)


问:
Why does this TensorFlow code behave differently when inside a test case?
I have a function (foo below) which is behaving differently when it's run directly vs when it is run inside a tf.test.TestCase.

The code is supposed to create a dataset with elems [1..5] and shuffle it. Then it repeats 3 times: create an iterator from the data and use that to print the 5 elements.

When run on its own it gives output where all the lists are shuffled e.g.:

```<code>[4, 0, 3, 2, 1]
[0, 2, 1, 3, 4]
[2, 3, 4, 0, 1]
</code>```

but when run inside a test case they are always the same, even between runs:

```<code>[0, 4, 2, 3, 1]
[0, 4, 2, 3, 1]
[0, 4, 2, 3, 1]
</code>```

I imagine it's something to do with how test cases handle random seeds but I can't see anything about that in the TensorFlow docs. Thanks for any help!

Code:

```<code>import tensorflow as tf

def foo():
    sess = tf.Session()
    dataset = tf.data.Dataset.range(5)
    dataset = dataset.shuffle(5, reshuffle_each_iteration=False)

    for _ in range(3):
        data_iter = dataset.make_one_shot_iterator()
        next_item = data_iter.get_next()
        with sess.as_default():
            data_new = [next_item.eval() for _ in range(5)]
        print(data_new)

class DatasetTest(tf.test.TestCase):
    def testDataset(self):
        foo()

if __name__ == '__main__':
    foo()
    tf.test.main()
</code>```

I am running it with Python 3.6 and TensorFlow 1.4. No other modules should be needed.

答:
I think you are right; tf.test.TestCase is being setup to use fixed seed.

```<code>class TensorFlowTestCase(googletest.TestCase):
# ...
def setUp(self):
  self._ClearCachedSession()
  random.seed(random_seed.DEFAULT_GRAPH_SEED)
  np.random.seed(random_seed.DEFAULT_GRAPH_SEED)
  ops.reset_default_graph()
  ops.get_default_graph().seed = random_seed.DEFAULT_GRAPH_SEED
</code>```

and
DEFAULT_GRAPH_SEED = 87654321 see this line in tensorflow/tensorflow/python/framework/random_seed.py.

Body:
I have a function (foo below) which is behaving differently when it's run directly vs when it is run inside a tf.test.TestCase.

The code is supposed to create a dataset with elems [1..5] and shuffle it. Then it repeats 3 times: create an iterator from the data and use that to print the 5 elements.

When run on its own it gives output where all the lists are shuffled e.g.:

[4, 0, 3, 2, 1]
[0, 2, 1, 3, 4]
[2, 3, 4, 0, 1]

but when run inside a test case they are always the same, even between runs:

[0, 4, 2, 3, 1]
[0, 4, 2, 3, 1]
[0, 4, 2, 3, 1]

I imagine it's something to do with how test cases handle random seeds but I can't see anything about that in the TensorFlow docs. Thanks for any help!

Code:

import tensorflow as tf

def foo():
    sess = tf.Session()
    dataset = tf.data.Dataset.range(5)
    dataset = dataset.shuffle(5, reshuffle_each_iteration=False)

    for _ in range(3):
        data_iter = dataset.make_one_shot_iterator()
        next_item = data_iter.get_next()
        with sess.as_default():
            data_new = [next_item.eval() for _ in range(5)]
        print(data_new)

class DatasetTest(tf.test.TestCase):
    def testDataset(self):
        foo()

if __name__ == '__main__':
    foo()
    tf.test.main()

I am running it with Python 3.6 and TensorFlow 1.4. No other modules should be needed.

Body:
I think you are right; tf.test.TestCase is being setup to use fixed seed.

class TensorFlowTestCase(googletest.TestCase):
# ...
def setUp(self):
  self._ClearCachedSession()
  random.seed(random_seed.DEFAULT_GRAPH_SEED)
  np.random.seed(random_seed.DEFAULT_GRAPH_SEED)
  ops.reset_default_graph()
  ops.get_default_graph().seed = random_seed.DEFAULT_GRAPH_SEED

and
DEFAULT_GRAPH_SEED = 87654321 see this line in tensorflow/tensorflow/python/framework/random_seed.py.


问:
Efficiently querying one string against multiple regexes
Lets say that I have 10,000 regexes and one string and I want to find out if the string matches any of them and get all the matches.
The trivial way to do it would be to just query the string one by one against all regexes. Is there a faster,more efficient way to do it?

EDIT:
I have tried substituting it with DFA's (lex)
The problem here is that it would only give you one single pattern. If I have a string "hello" and patterns "[H|h]ello" and ".{0,20}ello", DFA will only match one of them, but I want both of them to hit.

答:
Aho-Corasick was the answer for me.

I had 2000 categories of things that each had lists of patterns to match against. String length averaged about 100,000 characters.

Main Caveat:  The patters to match were all language patters not regex patterns e.g. 'cat' vs r'\w+'.

I was using python and so used https://pypi.python.org/pypi/pyahocorasick/.

```<code>import ahocorasick
A = ahocorasick.Automaton()

patterns = [
  [['cat','dog'],'mammals'],
  [['bass','tuna','trout'],'fish'],
  [['toad','crocodile'],'amphibians'],
]

for row in patterns:
    vals = row[0]
    for val in vals:
        A.add_word(val, (row[1], val))

A.make_automaton()

_string = 'tom loves lions tigers cats and bass'

def test():
  vals = []
  for item in A.iter(_string):
      vals.append(item)
  return vals
</code>```

Running %timeit test() on my 2000 categories with about 2-3 traces per category and a _string length of about 100,000 got me 2.09 ms vs 631 ms doing sequential re.search() 315x faster!.

OwnerDisplayName: Sridhar Iyer

LastEditorDisplayName: Sridhar Iyer

Body:
Aho-Corasick was the answer for me.

I had 2000 categories of things that each had lists of patterns to match against. String length averaged about 100,000 characters.

Main Caveat:  The patters to match were all language patters not regex patterns e.g. 'cat' vs r'\w+'.

I was using python and so used https://pypi.python.org/pypi/pyahocorasick/.

import ahocorasick
A = ahocorasick.Automaton()

patterns = [
  [['cat','dog'],'mammals'],
  [['bass','tuna','trout'],'fish'],
  [['toad','crocodile'],'amphibians'],
]

for row in patterns:
    vals = row[0]
    for val in vals:
        A.add_word(val, (row[1], val))

A.make_automaton()

_string = 'tom loves lions tigers cats and bass'

def test():
  vals = []
  for item in A.iter(_string):
      vals.append(item)
  return vals

Running %timeit test() on my 2000 categories with about 2-3 traces per category and a _string length of about 100,000 got me 2.09 ms vs 631 ms doing sequential re.search() 315x faster!.


问:
Reading in related data from table in foreign key relationship in Django REST Framework
Really struggling with this and it seems like it should be really straight forward. Basically, I am just trying to the products associated with a user, and then the short_name for each of those products to be rendered on the FE.

I have a table that has the user_id and prod_id. The table can look like this:

```<code>user_id | prod_id
-----------------
2       | 42
2       | 2
2       | 21
13      | 7
13      | 17
13      | 2
</code>```

The user_id is a models.ForeignKey to the User table and the prod_id is a models.ForeignKey to Products table. Better yet, here is the model:

```<code># ./home/models.py
from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    code = models.CharField(unique=True, max_length=16)
    name = models.CharField(max_length=255, blank=True, null=True)
    short_name = models.CharField(max_length=128)
    updated = models.DateTimeField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.short_name

    class Meta:
        db_table = 'Product'

class UserToProduct(models.Model):
    user = models.ForeignKey(User, related_name='user_name', db_column='user_id', null=True)
    prod = models.ForeignKey(Product, related_name='prod_name', db_column='prod_id', null=True)

    class Meta:
        db_table = 'User_to_Product'
        unique_together = ('user', 'prod')
</code>```

What should be happening is the React front-end sends the user_id based on who is logged in to the Django/DRF back-end. This is happening just fine. Here is the related view:

```<code># ./home/views.py
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from rest_framework.views import APIView

from .serializers import GetProductSerializer
from .models import Home

class GetHomeAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        serializer = GetProductSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            return Response(serializer.data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
</code>```

From there, it should just be pulling the list of products related to them and then reading in the short_name from the Product model, or really just an object where I can parse out the short_name.

Here is the serializer:

```<code># ./home/serializers.py
from rest_framework.serializers import (
    IntegerField,
    ModelSerializer,
    SerializerMethodField,
    StringRelatedField,
)

from .models import *

class GetProductSerializer(ModelSerializer):
    prod_name = StringRelatedField(many=True, required=False)
    product = SerializerMethodField('get_products')

    class Meta:
        model = UserToProduct
        fields = ('user', 'prod', 'prod_name')

    def get_products(self, obj):
        products = UserToProduct.objects.filter(user=data['user'])
        return products
</code>```

This particular variation results in: NameError: name 'data' is not defined.

Change get_products() to have:

```<code># for testing reasons
products = UserToProduct.objects.filter(user=2)
</code>```

This results in: KeyError: 'prod_name'

Anyway, I have spent more hours on this than I care to admit. This is some really basic stuff. I've tried dozens of variations. I'll keep working on it and posting what I've tried and the errors.

Also, this is the documentation I am referencing that I have read through dozens of times:

http://www.django-rest-framework.org/api-guide/relations/

http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/

Referenced countless other SO question/answers regarding this too and just not working.

EDIT: Probably have tried a few dozen more things and able to finally get a serialized response from the server; however, it isn't bringing in the short_name. Only modifications I have made:

```<code># ./home/models.py
class Product(models.Model)
    ...
    users = models.ManyToManyField(User, through='UserToProduct')
</code>```

```<code># ./home/serializers.py
class GetProductSerializer(ModelSerializer):
    user = IntegerField() # have to do this otherwise it returns the username and not the id
    prod = SerializerMethodField()

    class Meta:
        model = UserToProduct
        fields = [
            'user',
            'prod',

        ]

    def get_prod(self, obj):
        prod = UserToProduct.objects.filter(user=obj['user']).values('prod')
        print(prod)
        return prod
</code>```

Also, important to note is just leaving the get_prod() as:

```<code>prod = UserToProduct.objects.filter(user=obj['user'])
</code>```

Results in a : TypeError: Object of type 'UserToProduct' is not JSON serializable. However, it does list the short_name in print(prod).

答:
Ok, finally think I got it working. It is incredibly slow though and takes about 5 seconds to return the information which really doesn't seem right. That is way too long for the amount of data.

Anyway, this is what got it working for me:

```<code># ./home/views.py
...
def post(self, request, *args, **kwargs):
    user = request.data['user']
    serializer = GetProductSerializer(UserToProduct.objects.filter(user=user).prefetch_related('prod'), many=True)
    return Response(serializer.data)
</code>```

```<code># ./home/serializers.py
class GetProductSerializer(ModelSerializer):
    prod = CharField() # otherwise it was using prod_id number

    class Meta:
        model = UserToProduct
        fields = [
            'prod'
        ]
</code>```

Way more simple than I was trying... just got out to sort out the speed issue.

EDIT: Fixed the speed issue thanks to the help of this SO post:

Optimizing database queries in Django REST framework

Modified my query to the following:

```<code>UserToProduct.objects.filter(user=user).prefetch_related('prod')
</code>```

And it went down from 4.75 seconds to 1.5 seconds. Yee-haw.

Body:
Really struggling with this and it seems like it should be really straight forward. Basically, I am just trying to the products associated with a user, and then the short_name for each of those products to be rendered on the FE.

I have a table that has the user_id and prod_id. The table can look like this:

user_id | prod_id
-----------------
2       | 42
2       | 2
2       | 21
13      | 7
13      | 17
13      | 2

The user_id is a models.ForeignKey to the User table and the prod_id is a models.ForeignKey to Products table. Better yet, here is the model:

# ./home/models.py
from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    code = models.CharField(unique=True, max_length=16)
    name = models.CharField(max_length=255, blank=True, null=True)
    short_name = models.CharField(max_length=128)
    updated = models.DateTimeField(blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.short_name

    class Meta:
        db_table = 'Product'

class UserToProduct(models.Model):
    user = models.ForeignKey(User, related_name='user_name', db_column='user_id', null=True)
    prod = models.ForeignKey(Product, related_name='prod_name', db_column='prod_id', null=True)

    class Meta:
        db_table = 'User_to_Product'
        unique_together = ('user', 'prod')

What should be happening is the React front-end sends the user_id based on who is logged in to the Django/DRF back-end. This is happening just fine. Here is the related view:

# ./home/views.py
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from rest_framework.views import APIView

from .serializers import GetProductSerializer
from .models import Home

class GetHomeAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        serializer = GetProductSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            return Response(serializer.data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

From there, it should just be pulling the list of products related to them and then reading in the short_name from the Product model, or really just an object where I can parse out the short_name.

Here is the serializer:

# ./home/serializers.py
from rest_framework.serializers import (
    IntegerField,
    ModelSerializer,
    SerializerMethodField,
    StringRelatedField,
)

from .models import *

class GetProductSerializer(ModelSerializer):
    prod_name = StringRelatedField(many=True, required=False)
    product = SerializerMethodField('get_products')

    class Meta:
        model = UserToProduct
        fields = ('user', 'prod', 'prod_name')

    def get_products(self, obj):
        products = UserToProduct.objects.filter(user=data['user'])
        return products

This particular variation results in: NameError: name 'data' is not defined.

Change get_products() to have:

# for testing reasons
products = UserToProduct.objects.filter(user=2)

This results in: KeyError: 'prod_name'

Anyway, I have spent more hours on this than I care to admit. This is some really basic stuff. I've tried dozens of variations. I'll keep working on it and posting what I've tried and the errors.

Also, this is the documentation I am referencing that I have read through dozens of times:

http://www.django-rest-framework.org/api-guide/relations/

http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/

Referenced countless other SO question/answers regarding this too and just not working.

EDIT: Probably have tried a few dozen more things and able to finally get a serialized response from the server; however, it isn't bringing in the short_name. Only modifications I have made:

# ./home/models.py
class Product(models.Model)
    ...
    users = models.ManyToManyField(User, through='UserToProduct')

# ./home/serializers.py
class GetProductSerializer(ModelSerializer):
    user = IntegerField() # have to do this otherwise it returns the username and not the id
    prod = SerializerMethodField()

    class Meta:
        model = UserToProduct
        fields = [
            'user',
            'prod',

        ]

    def get_prod(self, obj):
        prod = UserToProduct.objects.filter(user=obj['user']).values('prod')
        print(prod)
        return prod

Also, important to note is just leaving the get_prod() as:

prod = UserToProduct.objects.filter(user=obj['user'])

Results in a : TypeError: Object of type 'UserToProduct' is not JSON serializable. However, it does list the short_name in print(prod).

Body:
Ok, finally think I got it working. It is incredibly slow though and takes about 5 seconds to return the information which really doesn't seem right. That is way too long for the amount of data.

Anyway, this is what got it working for me:

# ./home/views.py
...
def post(self, request, *args, **kwargs):
    user = request.data['user']
    serializer = GetProductSerializer(UserToProduct.objects.filter(user=user).prefetch_related('prod'), many=True)
    return Response(serializer.data)

# ./home/serializers.py
class GetProductSerializer(ModelSerializer):
    prod = CharField() # otherwise it was using prod_id number

    class Meta:
        model = UserToProduct
        fields = [
            'prod'
        ]

Way more simple than I was trying... just got out to sort out the speed issue.

EDIT: Fixed the speed issue thanks to the help of this SO post:

Optimizing database queries in Django REST framework

Modified my query to the following:

UserToProduct.objects.filter(user=user).prefetch_related('prod')

And it went down from 4.75 seconds to 1.5 seconds. Yee-haw.


问:
React Native: Customizing TouchableOpacity Animation Speed
According to the TouchableOpacity docs, there is an activeOpacity prop to change the end opacity level and there is a setOpacityTo function to animate the component to any opacity level. There doesn't seem to be anything about changing how fast the animation should take.

How would I go about changing the animation speed? Is there a props for this? Do I need to make my own custom Animated.View?

答:
That'd be the duration part of the method...

```<code>setOpacityTo(value: number, duration: number)
</code>```

React-native is using setOpacityTo in the background to animate the opacity using the setNativeProps with TouchableOpacity.

```<code>setOpacityTo(value) {
  // Redacted: animation related code
  this.refs[CHILD_REF].setNativeProps({
    opacity: value
  });
},
</code>```

So, it looks like you can also just create your own Animated event if you wanted to. Here's how touchable opacity uses setOpacityTo, making sure to set the useNativeDriver to true.

```<code>  setOpacityTo: function(value: number, duration: number) {
    Animated.timing(
      this.state.anim,
      {
        toValue: value,
        duration: duration,
        easing: Easing.inOut(Easing.quad),
        useNativeDriver: true,
      }
    ).start();
  },
</code>```

Body:
That'd be the duration part of the method...

setOpacityTo(value: number, duration: number)

React-native is using setOpacityTo in the background to animate the opacity using the setNativeProps with TouchableOpacity.

setOpacityTo(value) {
  // Redacted: animation related code
  this.refs[CHILD_REF].setNativeProps({
    opacity: value
  });
},

So, it looks like you can also just create your own Animated event if you wanted to. Here's how touchable opacity uses setOpacityTo, making sure to set the useNativeDriver to true.

  setOpacityTo: function(value: number, duration: number) {
    Animated.timing(
      this.state.anim,
      {
        toValue: value,
        duration: duration,
        easing: Easing.inOut(Easing.quad),
        useNativeDriver: true,
      }
    ).start();
  },


问:
Appending ng-repeat into HTML element dynamically
I trying to append ng-repeat into my HTML div on load.
It recognizes  the ng-repeat, however the index value isn't displaying as it should

HTML

```<code><div id="myInnerCarousel"></div>
</code>```

controller:

```<code>var myCarousel = document.getElementById('myInnerCarousel');
var newItem = document.createElement("div");
newItem.setAttribute("class","item");

var newData = document.createElement("div");
newData.setAttribute("class", "col-xs-6 col-sm-6 col-md-3 col-lg-3");
newData.setAttribute("ng-repeat", "mat in " + arr);

//Create individual values seperately
var newMaterialName = document.createElement("h4");
var nameNode = document.createTextNode("{{mat.Name}}");
newMaterialName.appendChild(nameNode);
//Append everything together

newData.appendChild(newMaterialName);
newItem.appendChild(newData);
myCarousel.appendChild(newItem);
</code>```

However the result is this:

https://gyazo.com/00b76c6b910d4c6701059d404783f720

It got the right idea of displaying my array, however angular isn't displaying h4 right.

EDIT: imtrying to achieve this in my html:

```<code><div ng-controller="myController">
<div class="item">
    <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3" ng-repeat="mat in array1">
        <h4>{{mat.Name}}</h4>
    </div>
</div>
<div class="item">
    <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3" ng-repeat="mat in array2">
        <h4>{{mat.Name}}</h4>
    </div>
</div>
</code>```

答:
Lets simply state that this is not the way to do it.

A better and more angular way would be (assuming your apps name is app).

HTML

```<code><div ng-controller="myController">
    <div class="item">
        <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3" ng-repeat="mat in array">
            <h4>{{mat.Name}}</h4>
        </div>
    </div>
</div>
</code>```

Angular Controller

```<code>angular.module('app').controller('myController', function($scope) {
    $scope.array = [{Name: 'abc'}, {Name: 'def'}]; // or whatever your data looks like.
});
</code>```

Body:
I trying to append ng-repeat into my HTML div on load.
It recognizes  the ng-repeat, however the index value isn't displaying as it should

HTML

controller:

var myCarousel = document.getElementById('myInnerCarousel');
var newItem = document.createElement("div");
newItem.setAttribute("class","item");

var newData = document.createElement("div");
newData.setAttribute("class", "col-xs-6 col-sm-6 col-md-3 col-lg-3");
newData.setAttribute("ng-repeat", "mat in " + arr);

//Create individual values seperately
var newMaterialName = document.createElement("h4");
var nameNode = document.createTextNode("{{mat.Name}}");
newMaterialName.appendChild(nameNode);
//Append everything together

newData.appendChild(newMaterialName);
newItem.appendChild(newData);
myCarousel.appendChild(newItem);

However the result is this:

https://gyazo.com/00b76c6b910d4c6701059d404783f720

It got the right idea of displaying my array, however angular isn't displaying h4 right.

EDIT: imtrying to achieve this in my html:

{{mat.Name}}

{{mat.Name}}

Body:
Lets simply state that this is not the way to do it.

A better and more angular way would be (assuming your apps name is app).

HTML

<div ng-controller="myController">
    <div class="item">
        <div class="col-xs-6 col-sm-6 col-md-3 col-lg-3" ng-repeat="mat in array">
            <h4>{{mat.Name}}</h4>
        </div>
    </div>
</div>

Angular Controller

angular.module('app').controller('myController', function($scope) {
    $scope.array = [{Name: 'abc'}, {Name: 'def'}]; // or whatever your data looks like.
});


问:
wait()/wait(timeout)/sleep(timeout)?
What is the difference between wait() and wait(timeout).Anyway wait() needs to wait for a notify call but why we have wait(timeout) ?

So what is the difference between sleep(timeout) and wait(timeout) ?

答:
The difference is that these methods are designed for different purposes. Sleep is used for introducing unconditional delay in thread execution, whilst wait is used for synchronization between threads, e.g.:

If you want to implement countdown, delay, timer you should use sleep(t).

If you have 2 (or more) threads, where 1st is a producer which spawns data randomly, whilst 2nd is consumer which consumes what 1st one provides, you should go for wait()/notify() pattern or consider modern more convenient wrappers for this threads synchronization if it's present on your platform.

If you have case 2, but you want to add a timeout to fire after certain time instead of hanging forever in wait(), you go for wait(t) instead of wait().

In fact if you never notify, wait(t) acts similarly to sleep(t) - it's gonna return after timeout, so you could use it for case 1, but it's much more clunky and ugly.

Title: wait()/wait(timeout)/sleep(timeout)?


问:
Wrong rendering of diacritical characters in JSON file
This thing's been bugging me for the last hour, i have this exposed json file
that should look like this : {
  "bio": {
    "meettheguy": "Meet this guy",
    "occupation": "Musician",
    "bio": "Test with diacritical marks : ááçë;"
  }
}

but instead looks like this : {
  "bio": {
    "meettheguy": "Meet this guy",
    "occupation": "Musician",
    "bio": "Test with diacritical marks : ����;"
  }
}

This is a MVC app hosted on an Azure server and apparently there is something wrong with the encoding during the JSON retrieve.
At this moment I cannot figure it out so any help or pointing at some probable right direction would be highly appreciated.

Thank you

答:
"During the JSON retrieve": Rather, it seems the problem is with the storage or generation, not the retrieval.

Your server says Content-Type: "application/json; charset=utf-8" which is quite normal for JSON. However, the bytes are not UTF-8 encoded text. Perhaps, it is stored or generated incorrectly, causing the wrong thing to be sent.

JSON should be encoded as UTF-8, UTF-16 or UTF-32. RFC7159.

Based on the bytes and the text expected to contain "ááçë", the following encodings are what the source might be incorrectly saved as:

CP1250

CP1252

CP1254

CP1258

CP28591

CP28592

CP28593

CP28599

CP28605

So, go upstream and fix whatever caused JSON to be saved or generated in one of those encodings, chose an encoding appropriate to JSON and make sure your server says which it is.