问:
angular 4 simultaneous animations
I'm trying to port my webapp from AngularJS to Angular 4, and I'm having some issues with animations. For a "Google Images" type of view, I have two animations that need to happen simultaneously when an item is clicked; one div needs its margin-bottom to increase, and a child of that div needs to gradually appear, using ngIf and a transition on its height. Both animations work separately, but if I put both animations on their respective elements, only the first one works.

I've made a minimal plunker to demonstrate what I mean: https://plnkr.co/edit/27EFz3h16icnh3qDzQbY?p=preview

```<code>const animationTiming = '1s ease';
@Component({
  selector: 'my-app',
  animations: [
    trigger('expand',
      [
        state('expanded', style({"margin-bottom": '392px'})),
        state('collapsed', style({"margin-bottom": '0'})),
        transition('* => *', animate(animationTiming))
      ]),
    trigger('visibility',
      [
        transition(
          ':enter', [
            style({'height': '0'}),
            animate(animationTiming, style({'height': '*'}))
          ]
        ),
        transition(
          ':leave', [
            style({'height': '*'}),
            animate(animationTiming, style({'height': '0'}))
          ]
        )
      ])
    ]
  template: `
    <button (click)="toggle()">click</button><br/>
    <div class="container" [@expand]="expanded?'expanded':'collapsed'">
      something here
      <div class="detail" [@visibility] *ngIf="expanded">something else in here</div>
    </div>
    <div class="container">something else</div>
  `,
})
export class App {
  expanded: boolean = false;
  toggle() {
    this.expanded = !this.expanded;
  }
}
</code>```

If you click the button, what should happen is that the new content expands in between "something here" and "something else". What actually happens is that the two frames move away from each other as expected, but the new content just pops up immediately. If I remove the [@expand] animation from the first div, the new content does gradually grow out of nothing but obviously the two container divs don't make room for it.

Is there a trick to make these animations work simultaneously?

答:
I am not sure why this error occurs, but it works if you change your template like this :

```<code><button (click)="toggle()">click</button><br/>
<div class="container" [@expand]="expanded?'expanded':'collapsed'">
something here</div>
<div class="detail" [@visibility] *ngIf="expanded">something else in here</div>
<div class="container">something else</div>
</code>```

The behaviour of the two animations seems to work better, when the second
 is not a sub-div of the first one.

And you can change the css code so the div stays between the other ones (by removing position: absolute) :

```<code>.detail {
  height: 360px;
  display: block;
  border: 1px solid black;
  left: 0px;
  right: 0px;
}
</code>```

Title: angular 4 simultaneous animations

Body:
I'm trying to port my webapp from AngularJS to Angular 4, and I'm having some issues with animations. For a "Google Images" type of view, I have two animations that need to happen simultaneously when an item is clicked; one div needs its margin-bottom to increase, and a child of that div needs to gradually appear, using ngIf and a transition on its height. Both animations work separately, but if I put both animations on their respective elements, only the first one works.

I've made a minimal plunker to demonstrate what I mean: https://plnkr.co/edit/27EFz3h16icnh3qDzQbY?p=preview

const animationTiming = '1s ease';
@Component({
  selector: 'my-app',
  animations: [
    trigger('expand',
      [
        state('expanded', style({"margin-bottom": '392px'})),
        state('collapsed', style({"margin-bottom": '0'})),
        transition('* => *', animate(animationTiming))
      ]),
    trigger('visibility',
      [
        transition(
          ':enter', [
            style({'height': '0'}),
            animate(animationTiming, style({'height': '*'}))
          ]
        ),
        transition(
          ':leave', [
            style({'height': '*'}),
            animate(animationTiming, style({'height': '0'}))
          ]
        )
      ])
    ]
  template: `
    <button (click)="toggle()">click</button>

      something here

something else in here

something else

  `,
})
export class App {
  expanded: boolean = false;
  toggle() {
    this.expanded = !this.expanded;
  }
}

If you click the button, what should happen is that the new content expands in between "something here" and "something else". What actually happens is that the two frames move away from each other as expected, but the new content just pops up immediately. If I remove the [@expand] animation from the first div, the new content does gradually grow out of nothing but obviously the two container divs don't make room for it.

Is there a trick to make these animations work simultaneously?

Body:
I am not sure why this error occurs, but it works if you change your template like this :

<button (click)="toggle()">click</button><br/>
<div class="container" [@expand]="expanded?'expanded':'collapsed'">
something here</div>
<div class="detail" [@visibility] *ngIf="expanded">something else in here</div>
<div class="container">something else</div>

The behaviour of the two animations seems to work better, when the second <div> is not a sub-div of the first one.

And you can change the css code so the div stays between the other ones (by removing position: absolute) :

.detail {
  height: 360px;
  display: block;
  border: 1px solid black;
  left: 0px;
  right: 0px;
}


来源: stackexchange

问:
Switch statement for multiple cases in JavaScript
I need multiple cases in switch statement in JavaScript, Something like:

```<code>switch (varName)
{
   case "afshin", "saeed", "larry":
       alert('Hey');
       break;

   default:
       alert('Default case');
       break;
}
</code>```

How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept.

答:
Adding and clarifying Stefano's answer, you can use expressions to dynamically set the values for the conditions in switch, e.g.:

```<code>var i = 3
switch (i) {
    case ((i>=0 && i<=5) ? i : -1):
        console.log('0-5');
        break;

    case 6: console.log('6');
}
</code>```

So in your problem, you could do something like:

```<code>var varName = "afshin"
switch (varName) {
    case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
      console.log("hey");
      break;

    default:
      console.log('Default case');
}
</code>```

Although it is so much DRY...

ContentLicense: CC BY-SA 4.0

Body:
I need multiple cases in switch statement in JavaScript, Something like:

switch (varName)
{
   case "afshin", "saeed", "larry":
       alert('Hey');
       break;

   default:
       alert('Default case');
       break;
}

How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept.

Body:
Adding and clarifying Stefano's answer, you can use expressions to dynamically set the values for the conditions in switch, e.g.:

var i = 3
switch (i) {
    case ((i>=0 && i<=5) ? i : -1):
        console.log('0-5');
        break;

    case 6: console.log('6');
}

So in your problem, you could do something like:

var varName = "afshin"
switch (varName) {
    case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
      console.log("hey");
      break;

    default:
      console.log('Default case');
}

Although it is so much DRY...


问:
populate spinner with retrofit and moshi
i am beginner in android dev (both java or kotlin). I am trying to populate spinner from json with retrofit and moshi but I have no idea how to populate it into spinner. to be honest I dont know whether the return of Json data is correct or not, since Log.d() return is not detail as dump() laravel or php.

script in activity onCreate (Please read the comment of the script, i put debug result of Log.d() there):

```<code>val task = object : AsyncTask<Void, Void, Response<List<ProductTypeResponse>>>() {
        override fun doInBackground(vararg params: Void): Response<List<ProductTypeResponse>> {

            val typeAPI = RestAPI()
            val callResponse = typeAPI.getNews()
            val response = callResponse.execute()

            return response

        }

        override fun onPostExecute(response: Response<List<ProductTypeResponse>>) {
            if (response.isSuccessful) {
                val news = response.body()
                Log.d("test:", news!![0].data.toString()) //  method 'java.lang.String com.example.mockie.tigaer.api.TypeDataResponse.toString()' on a null object reference
                Log.d("test:", news!!.size.toString()) // it says 67 but the data from the url is 63 array of json object
                Log.d("test:", news!![0].toString()) // com.example.mockie.tigaer.api.ProductTypeResponse@f17fd5e
            }
        }
</code>```

RestApi.kt

```<code>import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

class RestAPI() {

private val tigaerApi: TigaerApi

init {
    val retrofit = Retrofit.Builder()
            .baseUrl("http://app.tigaer.id/laravel/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

    tigaerApi = retrofit.create(TigaerApi::class.java)
}

fun getNews(): Call<List<ProductTypeResponse>> {
    return tigaerApi.getTop()
}
}
</code>```

ApiModel.kt

```<code>package com.example.mockie.tigaer.api

class ProductTypeResponse(val data: TypeDataResponse)

class TypeDataResponse(
    val children: List<ProductTypeChildrenResponse>
 )

 class ProductTypeChildrenResponse(val data: ProductTypeDataResponse)

 class ProductTypeDataResponse(
    val productType: String,
    val readable: String
 )
</code>```

TigaerApi.kt

```<code>import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface  TigaerApi {
@GET("api/type")
fun getTop(): Call<List<ProductTypeResponse>>
}
</code>```

return Json: https://jsoneditoronline.org/?id=ce90c41b859218e746e41d64eddb4c30

so my questions are :

is there any function to debug object/array as detail as in laravel ?

how to populate my json return data into spinner?

答:
Here is code for same, I modified and integrate in your code only:

"MainActivity.kt" class:

```<code> class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var spinner: Spinner = findViewById(R.id.spinner)

    val task = object : AsyncTask<Void, Void, Response<List<ProductTypeDataResponse>>>() {
        override fun doInBackground(vararg params: Void): Response<List<ProductTypeDataResponse>> {

            val typeAPI = RestAPI()
            val callResponse = typeAPI.getNews()
            val response = callResponse.execute()

            return response

        }

        override fun onPostExecute(response: Response<List<ProductTypeDataResponse>>) {
            if (response.isSuccessful) {
                val news: List<ProductTypeDataResponse>? = response.body()

                var adapter: SpinnerAdapter = SpinnerAdapter(this@MainActivity, news!!);

                spinner.adapter=adapter

               }
        }
    }.execute()
}
}
</code>```

Now Layout "activity_main":

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ankitpatidar.checkkotlin.MainActivity">

<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/spinner"></Spinner>
</LinearLayout>
</code>```

Now Spinner Adapter as "SpinnerAdapter":

```<code> class SpinnerAdapter internal constructor(internal var context: Context, internal var list: List<ProductTypeDataResponse>) : BaseAdapter() {
override fun getCount(): Int {
    return list.size
}

override fun getItem(i: Int): Any? {
    return null
}

override fun getItemId(i: Int): Long {
    return 0
}

override fun getView(i: Int, view: View?, viewGroup: ViewGroup): View {
    var view = view
    if (view == null) {
        val inflater = LayoutInflater.from(context)

        view = inflater.inflate(R.layout.item, viewGroup, false)
    }

    val textView = view!!.findViewById<TextView>(R.id.textView)

    textView.text = list[i].productType + " " + list[i].readable

    return textView

}
}
</code>```

Spinner item layout as "item":

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView"/>

</LinearLayout>
</code>```

Now some changes in your existing files:

"ApiModel.kt":

```<code> class TypeDataResponse(
    val children: List<ProductTypeChildrenResponse>
 )

 class ProductTypeChildrenResponse(val data: ProductTypeDataResponse)

 class ProductTypeDataResponse(
    val productType: String,
    val readable: String
 )
</code>```

"RestAPI.kt"

```<code> class RestAPI() {

private val tigaerApi: TigaerApi

init {
    val retrofit = Retrofit.Builder()
            .baseUrl("http://app.tigaer.id/laravel/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

    tigaerApi = retrofit.create(TigaerApi::class.java)
}

fun getNews(): Call<List<ProductTypeDataResponse>> {
    return tigaerApi.getTop()
}
}
</code>```

Hence it will work for you.

ContentLicense: CC BY-SA 3.0

Body:
i am beginner in android dev (both java or kotlin). I am trying to populate spinner from json with retrofit and moshi but I have no idea how to populate it into spinner. to be honest I dont know whether the return of Json data is correct or not, since Log.d() return is not detail as dump() laravel or php.

script in activity onCreate (Please read the comment of the script, i put debug result of Log.d() there):

val task = object : AsyncTask<Void, Void, Response<List<ProductTypeResponse>>>() {
        override fun doInBackground(vararg params: Void): Response<List<ProductTypeResponse>> {

            val typeAPI = RestAPI()
            val callResponse = typeAPI.getNews()
            val response = callResponse.execute()

            return response

        }

        override fun onPostExecute(response: Response<List<ProductTypeResponse>>) {
            if (response.isSuccessful) {
                val news = response.body()
                Log.d("test:", news!![0].data.toString()) //  method 'java.lang.String com.example.mockie.tigaer.api.TypeDataResponse.toString()' on a null object reference
                Log.d("test:", news!!.size.toString()) // it says 67 but the data from the url is 63 array of json object
                Log.d("test:", news!![0].toString()) // com.example.mockie.tigaer.api.ProductTypeResponse@f17fd5e
            }
        }

RestApi.kt

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

class RestAPI() {

private val tigaerApi: TigaerApi

init {
    val retrofit = Retrofit.Builder()
            .baseUrl("http://app.tigaer.id/laravel/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

    tigaerApi = retrofit.create(TigaerApi::class.java)
}

fun getNews(): Call<List<ProductTypeResponse>> {
    return tigaerApi.getTop()
}
}

ApiModel.kt

package com.example.mockie.tigaer.api

class ProductTypeResponse(val data: TypeDataResponse)

class TypeDataResponse(
    val children: List<ProductTypeChildrenResponse>
 )

 class ProductTypeChildrenResponse(val data: ProductTypeDataResponse)

 class ProductTypeDataResponse(
    val productType: String,
    val readable: String
 )

TigaerApi.kt

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface  TigaerApi {
@GET("api/type")
fun getTop(): Call<List<ProductTypeResponse>>
}

return Json: https://jsoneditoronline.org/?id=ce90c41b859218e746e41d64eddb4c30

so my questions are :

is there any function to debug object/array as detail as in laravel ?

how to populate my json return data into spinner?

Body:
Here is code for same, I modified and integrate in your code only:

"MainActivity.kt" class:

 class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var spinner: Spinner = findViewById(R.id.spinner)

    val task = object : AsyncTask<Void, Void, Response<List<ProductTypeDataResponse>>>() {
        override fun doInBackground(vararg params: Void): Response<List<ProductTypeDataResponse>> {

            val typeAPI = RestAPI()
            val callResponse = typeAPI.getNews()
            val response = callResponse.execute()

            return response

        }

        override fun onPostExecute(response: Response<List<ProductTypeDataResponse>>) {
            if (response.isSuccessful) {
                val news: List<ProductTypeDataResponse>? = response.body()

                var adapter: SpinnerAdapter = SpinnerAdapter(this@MainActivity, news!!);

                spinner.adapter=adapter

               }
        }
    }.execute()
}
}

Now Layout "activity_main":

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ankitpatidar.checkkotlin.MainActivity">

<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/spinner"></Spinner>
</LinearLayout>

Now Spinner Adapter as "SpinnerAdapter":

 class SpinnerAdapter internal constructor(internal var context: Context, internal var list: List<ProductTypeDataResponse>) : BaseAdapter() {
override fun getCount(): Int {
    return list.size
}

override fun getItem(i: Int): Any? {
    return null
}

override fun getItemId(i: Int): Long {
    return 0
}

override fun getView(i: Int, view: View?, viewGroup: ViewGroup): View {
    var view = view
    if (view == null) {
        val inflater = LayoutInflater.from(context)

        view = inflater.inflate(R.layout.item, viewGroup, false)
    }

    val textView = view!!.findViewById<TextView>(R.id.textView)

    textView.text = list[i].productType + " " + list[i].readable

    return textView

}
}

Spinner item layout as "item":

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView"/>

</LinearLayout>

Now some changes in your existing files:

"ApiModel.kt":

 class TypeDataResponse(
    val children: List<ProductTypeChildrenResponse>
 )

 class ProductTypeChildrenResponse(val data: ProductTypeDataResponse)

 class ProductTypeDataResponse(
    val productType: String,
    val readable: String
 )

"RestAPI.kt"

 class RestAPI() {

private val tigaerApi: TigaerApi

init {
    val retrofit = Retrofit.Builder()
            .baseUrl("http://app.tigaer.id/laravel/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

    tigaerApi = retrofit.create(TigaerApi::class.java)
}

fun getNews(): Call<List<ProductTypeDataResponse>> {
    return tigaerApi.getTop()
}
}

Hence it will work for you.


问:
Firebase cloud messaging (FCM) in IOS app is not working
I followed the documentation guide in firebase website and did all the following stuff:

1. Implemented the code in AppDelegate.swift.

2. Added the pods to my podfile and installed.

3. Created APN authentication key in Certifictes, Identifiers &
            Profiles in my developer.apple account and Paste it in the FCM settings.

4. Enabled Push Notification in project Capabilities (two v checked).

5. Created Certificate type: Apple Push Services for production

I sent couple of notifications from firebase console and didn't received any in my iPhone (IOS 10.3). Any tips what to check? what did i miss?

Podfile:

```<code>  use_frameworks!

  # Pods for App
  pod 'Firebase/Core'
  pod 'Firebase/Crash'
  pod 'Firebase/Messaging'
</code>```

AppDelegate.swift:

```<code>import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // Use Firebase library to configure APIs.
        FirebaseApp.configure()

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        return true
    }
</code>```

答:
you have to add a few methods.

Just compare your AppDelegate.swift with this one :)

This is the "official" sample from the firebase-guys (I think so :D)

Body:
I followed the documentation guide in firebase website and did all the following stuff:

1. Implemented the code in AppDelegate.swift.

2. Added the pods to my podfile and installed.

3. Created APN authentication key in Certifictes, Identifiers &
            Profiles in my developer.apple account and Paste it in the FCM settings.

4. Enabled Push Notification in project Capabilities (two v checked).

5. Created Certificate type: Apple Push Services for production

I sent couple of notifications from firebase console and didn't received any in my iPhone (IOS 10.3). Any tips what to check? what did i miss?

Podfile:

  use_frameworks!

  # Pods for App
  pod 'Firebase/Core'
  pod 'Firebase/Crash'
  pod 'Firebase/Messaging'

AppDelegate.swift:

import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // Use Firebase library to configure APIs.
        FirebaseApp.configure()

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        return true
    }


问:
How to follow/debug html creation in ASP.net
I'm trying to find out where an extra div is inserted and how I would go about removing it.

In our Index.cshtml file we have this:

```<code><div id="an-id">
    @Html.DisplayFor(m => m.BottomArticleListContentArea, new { ViewName = "_ArticleListBlockNoHeader" })
</div>
</code>```

And in our _ArticleListBlockNoHeader.cshtml view the code looks like this:

```<code>@if (Model != null)
{
    for (int i = 0; i < Model.Items.Count; i++)
    {
        var article = Model.Items[i];
        <div class="item" data-articleid="@article.ArticleId">
        Item @article.ArticleId
        </div>
    }
}
</code>```

BottomArticleListContentArea is a ContentArea and is handled by this DisplayTemplate:

```<code>@model ContentArea
@if (Model != null)
{
    Html.RenderContentArea(Model);
}
</code>```

As you can see, it doesn't really do anything except check if it's null. Oh... Maybe it does more things!

When I look at the generated html it looks like this:

```<code><div id="an-id">
<div><div>

    <div class="item" data-articleid="1">Item 1</div>
    <div class="item" data-articleid="2">Item 2</div>
    <div class="item" data-articleid="3">Item 3</div>
    <div class="item" data-articleid="4">Item 4</div>
    <div class="item" data-articleid="5">Item 5</div>
</div></div>
</div>
</code>```

Notice how on row 2 and 9 there is two divs (

 and

) that are not in the code I just shared above.

My hypothesis is now that these two divs might be added by some extension method somewhere or some handler or something else. I'm not familiar with the entire codebase and I'm fairly new with ASP.net so my knowledge of the insertion points in ASP.net is very limited.

Where could these two divs come from? And how can I start looking for them?

If something is missing in the question, please let me know, tried to be brief so that it would be easier to read and understand

Thanks in advance!

Edit:

Made a mistake while cleaning the code, added back so that the result is what's generated by the code.

The HTML results above is what is returned and captured using fiddler. No JS has started running while the DOM is recorded.

Added the display template used.

答:
This is the current solution that I have right now and I'm going to try out for a while:

(highly EPiServer specific)

Instead of letting it be rendered using RenderContentArea we're taking control over it and creating it the "raw" way with RenderContentData

```<code>foreach (var content in Model.FilteredItems)
{
    Html.RenderContentData(content.GetContent(), false, Model.Tag);
}
</code>```

This gets rid of all the extra divs and make it behave just the way we want it, just the way it seen when we read the code.
Yes, with this we're also loosing the ability to edit the page directly in epi visually. But that's something we need to look into later, for now, it works and I'm happy.

I also wrote this extended version that lets me choose if I want to skip the wrappers or not like this (notice DisableWrapper = true)

```<code>@Html.DisplayFor(m => m.ContentArea, new { DisableWrapper = true, ViewName = "_ArticleList" })
</code>```

That can be done if I instead change the first code snippet to this:

```<code>var disableWrapper = Html.ViewContext.ViewData["DisableWrapper"] as bool?;

if (disableWrapper.GetValueOrDefault())
{
    foreach (var content in Model.FilteredItems)
    {
        Html.RenderContentData(content.GetContent(), false, Model.Tag);
    }
}
else
{
    Html.RenderContentArea(Model);
}
</code>```

This works and seems to produce the results I'm looking for. As stated previously, I haven't worked in this field for that long so if there's any suggestions or tips, I'd love to hear that and be able to improve my solution both here and in the project.

Thanks for the helpful comments that made me finally arrive at this solution!

Body:
I'm trying to find out where an extra div is inserted and how I would go about removing it.

In our Index.cshtml file we have this:

    @Html.DisplayFor(m => m.BottomArticleListContentArea, new { ViewName = "_ArticleListBlockNoHeader" })

And in our _ArticleListBlockNoHeader.cshtml view the code looks like this:

@if (Model != null)
{
    for (int i = 0; i < Model.Items.Count; i++)
    {
        var article = Model.Items[i];

        Item @article.ArticleId

    }
}

BottomArticleListContentArea is a ContentArea and is handled by this DisplayTemplate:

@model ContentArea
@if (Model != null)
{
    Html.RenderContentArea(Model);
}

As you can see, it doesn't really do anything except check if it's null. Oh... Maybe it does more things!

When I look at the generated html it looks like this:

Item 1

Item 2

Item 3

Item 4

Item 5

Notice how on row 2 and 9 there is two divs (

 and

) that are not in the code I just shared above.

My hypothesis is now that these two divs might be added by some extension method somewhere or some handler or something else. I'm not familiar with the entire codebase and I'm fairly new with ASP.net so my knowledge of the insertion points in ASP.net is very limited.

Where could these two divs come from? And how can I start looking for them?

If something is missing in the question, please let me know, tried to be brief so that it would be easier to read and understand

Thanks in advance!

Edit:

Made a mistake while cleaning the code, added back so that the result is what's generated by the code.

The HTML results above is what is returned and captured using fiddler. No JS has started running while the DOM is recorded.

Added the display template used.

Body:
This is the current solution that I have right now and I'm going to try out for a while:

(highly EPiServer specific)

Instead of letting it be rendered using RenderContentArea we're taking control over it and creating it the "raw" way with RenderContentData

foreach (var content in Model.FilteredItems)
{
    Html.RenderContentData(content.GetContent(), false, Model.Tag);
}

This gets rid of all the extra divs and make it behave just the way we want it, just the way it seen when we read the code.
Yes, with this we're also loosing the ability to edit the page directly in epi visually. But that's something we need to look into later, for now, it works and I'm happy.

I also wrote this extended version that lets me choose if I want to skip the wrappers or not like this (notice DisableWrapper = true)

@Html.DisplayFor(m => m.ContentArea, new { DisableWrapper = true, ViewName = "_ArticleList" })

That can be done if I instead change the first code snippet to this:

var disableWrapper = Html.ViewContext.ViewData["DisableWrapper"] as bool?;

if (disableWrapper.GetValueOrDefault())
{
    foreach (var content in Model.FilteredItems)
    {
        Html.RenderContentData(content.GetContent(), false, Model.Tag);
    }
}
else
{
    Html.RenderContentArea(Model);
}

This works and seems to produce the results I'm looking for. As stated previously, I haven't worked in this field for that long so if there's any suggestions or tips, I'd love to hear that and be able to improve my solution both here and in the project.

Thanks for the helpful comments that made me finally arrive at this solution!


问:
How to align the button at the leftmost side in a listbox control?
I am developing window phone 7 application. I am new to the silverlight. I am dynamically creating the button control and binding these all button controls to the listbox.    </p>

```<code><ListBox x:Name="lstButtons" Margin="393,-28,-12,28" Background="Orange">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button Content="{Binding ElementName}" Width="100" HorizontalAlignment="Right"></Button>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
 </ListBox>
</code>```

<p>Now I want to display the button control at the leftmost side means I want to display the button control near to the left border of the listbox. I want to display the button control which is aligned to the left. With my above code the the button control appears in the center in the listbox ? How should I align it to the left ? Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me. </p>

答: This might not be very helpful, but I have found that using expression blend for layout/ui things like this is the easiest way to do it.  You will have to drill into the list template then you can play around with alignments.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am developing window phone 7 application. I am new to the silverlight. I am dynamically creating the button control and binding these all button controls to the listbox.

<ListBox x:Name="lstButtons" Margin="393,-28,-12,28" Background="Orange">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button Content="{Binding ElementName}" Width="100" HorizontalAlignment="Right"></Button>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
 </ListBox>

Now I want to display the button control at the leftmost side means I want to display the button control near to the left border of the listbox. I want to display the button control which is aligned to the left. With my above code the the button control appears in the center in the listbox ? How should I align it to the left ? Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me.


问:
Excel: Insert query throws error message "Operation must use an updateable query"
I am running into an error when trying to insert into an Excel worksheet

This is the layout of my Excel worksheet named Sheet1:

```<code>     id    name
     1     test
     2     apple
     3     pear
</code>```

I want to insert this data into the Excel worksheet:

```<code>     4     pineapple
</code>```

This is my code below:

```<code>try{
            string srcExcel = "C:\\Users\\Desktop\\insertTest.xlsx";
            System.Data.OleDb.OleDbConnection MyConnection;
            System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
            string sql = null;
            MyConnection = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + srcExcel + "; Extended Properties = 'Excel 8.0;HDR=Yes;IMEX=1'");
            MyConnection.Open();
            myCommand.Connection = MyConnection;
            sql = "Insert Into [Sheet1$] (id,name) Values('4','pineapple')";
            myCommand.CommandText = sql;
            myCommand.ExecuteNonQuery();
            MessageBox.Show("Insert Success!");
            MyConnection.Close();
}
        catch (Exception eInnerData)
        {
            MessageBox.Show("Method: getInnerData " + eInnerData.ToString());
        }
</code>```

After running this code an exception is thrown and caught with this error message:

Operation must use an updateable query

I am using Microsoft Excel 2010

答:
Remove the IMEX=1 from the connectionstring. Also make sure the file is not readonly and not currently open in Excel

For what it's worth, I recommend reading and writing the xlsx file with something like the EPPlus library, rather than the Access db driver

Body:
I am running into an error when trying to insert into an Excel worksheet

This is the layout of my Excel worksheet named Sheet1:

     id    name
     1     test
     2     apple
     3     pear

I want to insert this data into the Excel worksheet:

     4     pineapple

This is my code below:

try{
            string srcExcel = "C:\\Users\\Desktop\\insertTest.xlsx";
            System.Data.OleDb.OleDbConnection MyConnection;
            System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
            string sql = null;
            MyConnection = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + srcExcel + "; Extended Properties = 'Excel 8.0;HDR=Yes;IMEX=1'");
            MyConnection.Open();
            myCommand.Connection = MyConnection;
            sql = "Insert Into [Sheet1$] (id,name) Values('4','pineapple')";
            myCommand.CommandText = sql;
            myCommand.ExecuteNonQuery();
            MessageBox.Show("Insert Success!");
            MyConnection.Close();
}
        catch (Exception eInnerData)
        {
            MessageBox.Show("Method: getInnerData " + eInnerData.ToString());
        }

After running this code an exception is thrown and caught with this error message:

Operation must use an updateable query

I am using Microsoft Excel 2010


问:
Range.Value not working for assigning cell contents to variable in VBA
I am writing my first script with VBA and I am having a hard time assigning the value entered into a cell to a String variable, I used Message Boxes to test where the issue is and it showed me I'm in the right workbook and the right sheet but then shows a blank for the value in "A1" even though I have a text value there and made sure I saved the workbook, what I have is below:

```<code>Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String

Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name
Sheets(1).Activate

MsgBox Range("A1").Value        ' Shows blank when debugging
folderName = Range("A1").Value
MsgBox "Here is " & folderName  ' Shows "Here is " when debugging

End Sub
</code>```

** As an additional note, the A1 cell contains 02Nov, and I have tried changing the format of this cell and it hasn't fixed the issue, currently the cell format is Text

答:
Sheets(1)

refers to the first tab in the active workbook.  That tab can be a worksheet, code sheet or chart sheet.

It is better to use WorkSheets() to reference worksheets. To ensure that you always get the correct sheet, regardless of order, use the name:

```<code>WorkSheets("Sheet1")
</code>```

The best method would be to use the CodeName.  This is the name of the sheet that the user cannot change.  It is found in the sheet list in VBA:

The part before the () is the Codename.  So Worksheets("Sheet1") Code Name is Sheet1.  Using the code name we reference the sheet simply by typing it:

```<code>Sheet1
</code>```

This cannot be easily changed by the user, as the name of the sheet can.  This will always refer to the proper sheet regardless of tab position and name of the sheet.

Next:

Do not use .Activate or .Select  They just slow down the code.  Just append the ranges with the correct sheet references:

```<code>Worksheets("Sheet1").Range("A1")
</code>```

Or better with the CodeName:

```<code>Sheet1.Range("A1")
</code>```

Body:
I am writing my first script with VBA and I am having a hard time assigning the value entered into a cell to a String variable, I used Message Boxes to test where the issue is and it showed me I'm in the right workbook and the right sheet but then shows a blank for the value in "A1" even though I have a text value there and made sure I saved the workbook, what I have is below:

Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String

Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name
Sheets(1).Activate

MsgBox Range("A1").Value        ' Shows blank when debugging
folderName = Range("A1").Value
MsgBox "Here is " & folderName  ' Shows "Here is " when debugging

End Sub

** As an additional note, the A1 cell contains 02Nov, and I have tried changing the format of this cell and it hasn't fixed the issue, currently the cell format is Text

Body:
Sheets(1)

refers to the first tab in the active workbook.  That tab can be a worksheet, code sheet or chart sheet.

It is better to use WorkSheets() to reference worksheets. To ensure that you always get the correct sheet, regardless of order, use the name:

WorkSheets("Sheet1")

The best method would be to use the CodeName.  This is the name of the sheet that the user cannot change.  It is found in the sheet list in VBA:

The part before the () is the Codename.  So Worksheets("Sheet1") Code Name is Sheet1.  Using the code name we reference the sheet simply by typing it:

Sheet1

This cannot be easily changed by the user, as the name of the sheet can.  This will always refer to the proper sheet regardless of tab position and name of the sheet.

Next:

Do not use .Activate or .Select  They just slow down the code.  Just append the ranges with the correct sheet references:

Worksheets("Sheet1").Range("A1")

Or better with the CodeName:

Sheet1.Range("A1")


问:
Confluent Kafka: Consumer does not read from beginning for all partitions in a topic
I have a topic with 40 partitions. Settings are such:

```<code>def on_assign (c,ps):
    for p in ps:
        p.offset=0
    print ps
    c.assign(ps)

conf = {'bootstrap.servers': 'localhost:9092'
        'enable.auto.commit' : False,
        'group.id' : 'confluent_consumer',
        'default.topic.config': {'auto.offset.reset': 'earliest'}
        }
consumer = Consumer(**conf)
consumer.subscribe(['topic.source'], on_assign=on_assign)

msg = consumer.poll(timeout=100000)
print "Topic is %s: | Partition is %d: | Offset is : %d | key is :%s " % (msg.topic(), msg.partition(), msg.offset(), msg.key())
</code>```

I want to read from offset 0 for all partitions of the topic topic.source. But I don't see it happening for all partitions. For some partitions it reads from a specific offset which I'm assuming is the committed offset, changing the group.id every time doesn't help either. How can I read from beginning for all partitions of this topic irrespective of the committed offsets?

I printed ps in on_assign() and it printed something like this for all 40 partitions:

```<code>[TopicPartition{topic=topic.source,partition=0,offset=0,error=None},TopicPartition{topic=topic.source,partition=1,offset=0,error=None}....] and so on
</code>```

答:
If you use set group.id to a new value or use a group that has not committed any offset with auto.offset.reset set to earliest then the consumer will start from the beginning of the partition.

That said, the beginning might not be offset 0. Depending on your broker's log retention settings, Kafka can be deleting messages thus the 1st available message in your partitions could be at any offset.

Body:
I have a topic with 40 partitions. Settings are such:

def on_assign (c,ps):
    for p in ps:
        p.offset=0
    print ps
    c.assign(ps)

conf = {'bootstrap.servers': 'localhost:9092'
        'enable.auto.commit' : False,
        'group.id' : 'confluent_consumer',
        'default.topic.config': {'auto.offset.reset': 'earliest'}
        }
consumer = Consumer(**conf)
consumer.subscribe(['topic.source'], on_assign=on_assign)

msg = consumer.poll(timeout=100000)
print "Topic is %s: | Partition is %d: | Offset is : %d | key is :%s " % (msg.topic(), msg.partition(), msg.offset(), msg.key())

I want to read from offset 0 for all partitions of the topic topic.source. But I don't see it happening for all partitions. For some partitions it reads from a specific offset which I'm assuming is the committed offset, changing the group.id every time doesn't help either. How can I read from beginning for all partitions of this topic irrespective of the committed offsets?

I printed ps in on_assign() and it printed something like this for all 40 partitions:

[TopicPartition{topic=topic.source,partition=0,offset=0,error=None},TopicPartition{topic=topic.source,partition=1,offset=0,error=None}....] and so on


问:
operator.setitem problem in python 3
I have a problem when using operator.setitem in python 3.

When I use the code below and run it in python 3.1.

```<code>people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)

>>> {}
</code>```

That just prints out a empty dictionary {}.

But I use the same code to run in python 2.6.
It prints out {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1} .
This is the result I want.

So, can anyone tell me what's the problem when I run this code in python 3?
Thanks in advance.

答:
That's a very unpythonesque way to do it. This is much better (and more efficient):

```<code>people = (('fred','sam','jane','betty'), (1,2,3,4))
p_dict = dict(zip(*people))
</code>```

Works on 2.x and 3.x.

Title: operator.setitem problem in python 3

Body:
I have a problem when using operator.setitem in python 3.

When I use the code below and run it in python 3.1.

people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print (p_dict)

>>> {}

That just prints out a empty dictionary {}.

But I use the same code to run in python 2.6.
It prints out {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1} .
This is the result I want.

So, can anyone tell me what's the problem when I run this code in python 3?
Thanks in advance.

Body:
That's a very unpythonesque way to do it. This is much better (and more efficient):

people = (('fred','sam','jane','betty'), (1,2,3,4))
p_dict = dict(zip(*people))

Works on 2.x and 3.x.


问:
SQL - Turn one date column into FromDate & ToDate columns
I am new to SQL and mostly use the data from Queries in Power BI.

I  to split my date column into two date columns in SQL based on Status. (on The days that status was changed)

I have an SQL query which gives me below straightforward results

```<code>SERIAL NO         ENTITY_CODE COMPANY_NAME      STATUS       TRANSACTION_DATE
AB:CD:EF:GH:IJ:KL FRANCIS     MADICAL           Activation      27-04-12 18:30
AB:CD:EF:GH:IJ:KL DEADPOOL    FAST TRANSPORT    Disconnection   27-12-14 15:01
12345678901       DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:30
12345678901       DEADPOOL    FAST TRANSPORT    Disconnection   17-01-16 16:35
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:31
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Disconnection   02-12-13 13:26
78901234567       BANDHU      BANDHU CABS       Activation      27-04-12 19:12
78901234567       BANDHU      BANDHU CABS       Disconnection   27-10-13 19:42
78901234567       DEADPOOL    FAST TRANSPORT    Reconnection    25-02-14 13:53
78901234567       DEADPOOL    FAST TRANSPORT    Disconnection   08-04-16 17:14
</code>```

This one is simple 'select' query with some conditions and 'Order By'.

In order to find, how many days this Serial No was Active and DisConnected, I need this data in below-mentioned format. Which I need for Power BI.

```<code>SERIAL NO           ENTITY_CODE  COMPANY_NAME   STATUS          FromDate      ToDATE
AB:CD:EF:GH:IJ:KL   FRANCIS      MADICAL        Activation      27-04-12 18:30  27-12-14 15:01
AB:CD:EF:GH:IJ:KL   DEADPOOL     FAST TRANSPORT Disconnection   27-12-14 15:01  TODAY'S DATE
12345678901         DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:30  17-01-16 16:35
12345678901         DEADPOOL     FAST TRANSPORT Disconnection   17-01-16 16:35  TODAY'S DATE
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:31  02-12-13 13:26
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Disconnection   02-12-13 13:26  TODAY'S DATE
78901234567         BANDHU       BANDHU CABS    Activation      27-04-12 19:12  27-10-13 19:42
78901234567         BANDHU       BANDHU CABS    Disconnection   27-10-13 19:42  25-02-14 13:53
78901234567         DEADPOOL     FAST TRANSPORT Reconnection    25-02-14 13:53  08-04-16 17:14
78901234567         DEADPOOL     FAST TRANSPORT Disconnection   08-04-16 17:14  TODAY'S DATE
</code>```

Please note 'Today's Date' in ToDate Column.
This data will ultimately give me Status of every Serial No on Every day of that Number's Life.

I need to divide  'Transaction History' based on every transaction date so that I will be able to find out that certain Serial Number was active from  date1 to date2, and then disconnected from date 2 to date 3, and so on

Can someone help?

答:
It looks like you want to select the min transaction date that is greater than the current transaction date and that has the same Serial No. If there is no match (returns NULL in this example) then return today's date.

I've used a datetime datatype, but it appears the example code selected a varchar or char. I'm assuming you're using the correct datatype.

If you have SQL Server Management Studio you can try this full example:

```<code>DECLARE @mytable TABLE ([SERIAL NO] varchar(100), ENTITY_CODE varchar(100), COMPANY_NAME varchar(100), [STATUS] varchar(100), TRANSACTION_DATE smalldatetime)
INSERT INTO @mytable VALUES
 ('AB:CD:EF:GH:IJ:KL', 'FRANCIS',  'MADICAL',        'Activation',    '2012-04-27 18:30:00')
,('AB:CD:EF:GH:IJ:KL', 'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2014-12-27 15:01:00')
,('12345678901',       'DEADPOOL', 'FAST TRANSPORT', 'Activation',    '2012-04-27 18:30:00')
,('12345678901',       'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2016-01-17 16:35:00')
,('PQ:RS:TU:VW:XY:ZA', 'DEADPOOL', 'FAST TRANSPORT', 'Activation',    '2012-04-27 18:31:00')
,('PQ:RS:TU:VW:XY:ZA', 'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2013-12-02 13:26:00')
,('78901234567',       'BANDHU',   'BANDHU CABS',    'Activation',    '2012-04-27 19:12:00')
,('78901234567',       'BANDHU',   'BANDHU CABS',    'Disconnection', '2013-10-27 19:42:00')
,('78901234567',       'DEADPOOL', 'FAST TRANSPORT', 'Reconnection',  '2014-02-25 13:53:00')
,('78901234567',       'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2016-04-08 17:14:00')

SELECT M1.[SERIAL NO], M1.ENTITY_CODE, M1.COMPANY_NAME, M1.[STATUS], M1.TRANSACTION_DATE AS FromDate
      ,COALESCE(
       (SELECT MIN(TRANSACTION_DATE)
          FROM @mytable M2
         WHERE M2.[SERIAL NO] = M1.[SERIAL NO]
           AND M2.TRANSACTION_DATE > M1.TRANSACTION_DATE
       )
               , getDate()
               ) AS ToDATE
  FROM @mytable M1
</code>```

Body:
I am new to SQL and mostly use the data from Queries in Power BI.

I  to split my date column into two date columns in SQL based on Status. (on The days that status was changed)

I have an SQL query which gives me below straightforward results

SERIAL NO         ENTITY_CODE COMPANY_NAME      STATUS       TRANSACTION_DATE
AB:CD:EF:GH:IJ:KL FRANCIS     MADICAL           Activation      27-04-12 18:30
AB:CD:EF:GH:IJ:KL DEADPOOL    FAST TRANSPORT    Disconnection   27-12-14 15:01
12345678901       DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:30
12345678901       DEADPOOL    FAST TRANSPORT    Disconnection   17-01-16 16:35
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Activation      27-04-12 18:31
PQ:RS:TU:VW:XY:ZA DEADPOOL    FAST TRANSPORT    Disconnection   02-12-13 13:26
78901234567       BANDHU      BANDHU CABS       Activation      27-04-12 19:12
78901234567       BANDHU      BANDHU CABS       Disconnection   27-10-13 19:42
78901234567       DEADPOOL    FAST TRANSPORT    Reconnection    25-02-14 13:53
78901234567       DEADPOOL    FAST TRANSPORT    Disconnection   08-04-16 17:14

This one is simple 'select' query with some conditions and 'Order By'.

In order to find, how many days this Serial No was Active and DisConnected, I need this data in below-mentioned format. Which I need for Power BI.

SERIAL NO           ENTITY_CODE  COMPANY_NAME   STATUS          FromDate      ToDATE
AB:CD:EF:GH:IJ:KL   FRANCIS      MADICAL        Activation      27-04-12 18:30  27-12-14 15:01
AB:CD:EF:GH:IJ:KL   DEADPOOL     FAST TRANSPORT Disconnection   27-12-14 15:01  TODAY'S DATE
12345678901         DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:30  17-01-16 16:35
12345678901         DEADPOOL     FAST TRANSPORT Disconnection   17-01-16 16:35  TODAY'S DATE
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Activation      27-04-12 18:31  02-12-13 13:26
PQ:RS:TU:VW:XY:ZA   DEADPOOL     FAST TRANSPORT Disconnection   02-12-13 13:26  TODAY'S DATE
78901234567         BANDHU       BANDHU CABS    Activation      27-04-12 19:12  27-10-13 19:42
78901234567         BANDHU       BANDHU CABS    Disconnection   27-10-13 19:42  25-02-14 13:53
78901234567         DEADPOOL     FAST TRANSPORT Reconnection    25-02-14 13:53  08-04-16 17:14
78901234567         DEADPOOL     FAST TRANSPORT Disconnection   08-04-16 17:14  TODAY'S DATE

Please note 'Today's Date' in ToDate Column.
This data will ultimately give me Status of every Serial No on Every day of that Number's Life.

I need to divide  'Transaction History' based on every transaction date so that I will be able to find out that certain Serial Number was active from  date1 to date2, and then disconnected from date 2 to date 3, and so on

Can someone help?

Body:
It looks like you want to select the min transaction date that is greater than the current transaction date and that has the same Serial No. If there is no match (returns NULL in this example) then return today's date.

I've used a datetime datatype, but it appears the example code selected a varchar or char. I'm assuming you're using the correct datatype.

If you have SQL Server Management Studio you can try this full example:

DECLARE @mytable TABLE ([SERIAL NO] varchar(100), ENTITY_CODE varchar(100), COMPANY_NAME varchar(100), [STATUS] varchar(100), TRANSACTION_DATE smalldatetime)
INSERT INTO @mytable VALUES
 ('AB:CD:EF:GH:IJ:KL', 'FRANCIS',  'MADICAL',        'Activation',    '2012-04-27 18:30:00')
,('AB:CD:EF:GH:IJ:KL', 'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2014-12-27 15:01:00')
,('12345678901',       'DEADPOOL', 'FAST TRANSPORT', 'Activation',    '2012-04-27 18:30:00')
,('12345678901',       'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2016-01-17 16:35:00')
,('PQ:RS:TU:VW:XY:ZA', 'DEADPOOL', 'FAST TRANSPORT', 'Activation',    '2012-04-27 18:31:00')
,('PQ:RS:TU:VW:XY:ZA', 'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2013-12-02 13:26:00')
,('78901234567',       'BANDHU',   'BANDHU CABS',    'Activation',    '2012-04-27 19:12:00')
,('78901234567',       'BANDHU',   'BANDHU CABS',    'Disconnection', '2013-10-27 19:42:00')
,('78901234567',       'DEADPOOL', 'FAST TRANSPORT', 'Reconnection',  '2014-02-25 13:53:00')
,('78901234567',       'DEADPOOL', 'FAST TRANSPORT', 'Disconnection', '2016-04-08 17:14:00')

SELECT M1.[SERIAL NO], M1.ENTITY_CODE, M1.COMPANY_NAME, M1.[STATUS], M1.TRANSACTION_DATE AS FromDate
      ,COALESCE(
       (SELECT MIN(TRANSACTION_DATE)
          FROM @mytable M2
         WHERE M2.[SERIAL NO] = M1.[SERIAL NO]
           AND M2.TRANSACTION_DATE > M1.TRANSACTION_DATE
       )
               , getDate()
               ) AS ToDATE
  FROM @mytable M1


答:
This error occurs when an access database or excel document is stored in folder were you do not have write write access. You can read the file but you wont be able to make changes to it.

Please ensure you have access to this folder or run your program as an administrator.

You can confirm the write permissions on Windows by checking that you have access under the security tab on file properties.

Title: Excel: Insert query throws error message "Operation must use an updateable query"


问:
C++ Namespaces, comparison to Java packages
I've done a bunch of Java coding recently and have got used to very specific package naming systems, with deep nesting e.g. com.company.project.db. This works fine in Java, AS3/Flex and C#. I've seen the same paradigm applied in C++ too, but I've also heard that it's bad to view C++ namespaces as direct counterparts to Java packages.

Is that true, and why? How are namespaces/packages alike and different? What problems are likely to be seen if you do use deep nested namespaces?

答:
I think there is something missing in the previous answers, and it is one of the reasons I really like C++.

Imagine you are programming a graphical application and suddenly you realize that there is something common among all your widgets. You want all of them to have a new function. What do you do?

1) Edit the base widget class? OK, but most likely you do not have access to it. Maybe there is a licensing problem that prevents you from doing your own modification. Even if you can just do it, if it is something that only makes sense for your project, the authors will not include it in their future release, and upgrading the toolkit will be more painful

2) Create an interface class / multi-inheritance? Depending on your existing code it will be more or less of a pain to update every single class related with a widget. Do this and your code will cost more to maintain because everyone defining a new class must know that they are suppose to inherit from your interface. Becoming dependent of other people discipline is really risky.

The wonderful thing of C++ namespaces here is that you have an extra way to encapsulate stuff within an already existing system. Not only you can encapsulate within already existing libraries that you cannot edit, you can encapsulate similar concepts that you cannot easily insert into your hierarchy of classes/objects.

Java forces you to focus more on a pure OOP design. Sure that I am telling you might be a dirty hack and not elegant, but there are lots of lazy people programming who do not spend time fixing their designs.


问:
python print current GMT time into 13 digit Linux
How can I print the current GMT time into a 13 digit Linux timestamp? I need to submit it as dictionary in header object.</p>

答:
according to python 2.7 documentation :

```<code> `import time`
 `time.gmtine()`
</code>```

will return a time.struct_time object which represent the following:

```<code>Index   Attribute   Values

0   tm_year (for example, 1993)

1   tm_mon  range [1, 12]

2   tm_mday range [1, 31]

3   tm_hour range [0, 23]

4   tm_min  range [0, 59]

5   tm_sec  range [0, 61]; see (2) in strftime() description

6   tm_wday range [0, 6], Monday is 0

7   tm_yday range [1, 366]

8   tm_isdst    0, 1 or -1; see below
</code>```

maybe it will help you.
link to docs: https://docs.python.org/2.7/library/time.html#time.strptime

Body:
according to python 2.7 documentation :

 `import time`
 `time.gmtine()`

will return a time.struct_time object which represent the following:

Index   Attribute   Values

0   tm_year (for example, 1993)

1   tm_mon  range [1, 12]

2   tm_mday range [1, 31]

3   tm_hour range [0, 23]

4   tm_min  range [0, 59]

5   tm_sec  range [0, 61]; see (2) in strftime() description

6   tm_wday range [0, 6], Monday is 0

7   tm_yday range [1, 366]

8   tm_isdst    0, 1 or -1; see below

maybe it will help you.
link to docs: https://docs.python.org/2.7/library/time.html#time.strptime


问:
How to keep my image caption grid floating correctly with different sized text content
I have an issue here where if a caption is too long, if it extends beyond one line it causes the elements following to not float correctly. I would like to have it, so that no matter on the content of the caption, the following row adjusts to the space. I have seen another site achieve something very similar.

I can't work out what else I need.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div></code>```

CSS Tricks say:

The Overflow Method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats

Reading this, I set the container div.project-thumbnail, but no change:

```<code>.project-thumbnail {
  overflow: auto
}
</code>```

jsFiddle

EDIT

As the comment suggests, setting a height to the caption div div.thumb would enable it to float correctly. A fixed height will cut off content that becomes too big for it. Adding overflow: auto to this div will just add a scrollbar to it, this is not what I am after.

EDIT

This site here has a similar system. Items with a width are floated, no row separator, but if the content within their div extends beyond a few lines, the bottom of the div will adjust, aligning the next row neatly.

答:
updated, thanks to @user10089632 for comment

To get the layout you want using float, try adding the clear property to every 4th .column.

example

```<code>.column:nth-child(3n + 4) {
  clear: both;
}
</code>```

This will target every 3rd .column, beginning from the 4th .column (you don't need to apply the rule to the first div in your example)

You can adjust nth-child(n) if you need to change your grid to 4 x 4 or something else.

You can apply this code to article instead, depending on the rest of your site.

fiddle

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}

.column:nth-child(4) {
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div></code>```

Body:
I have an issue here where if a caption is too long, if it extends beyond one line it causes the elements following to not float correctly. I would like to have it, so that no matter on the content of the caption, the following row adjusts to the space. I have seen another site achieve something very similar.

I can't work out what else I need.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}

Box One

Item preview

Box One

Item preview with some content that makes it extend onto another line.

Box One

Item preview

Box One

Item preview

Box One

Item preview

Box One

Item preview

CSS Tricks say:

The Overflow Method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats

Reading this, I set the container div.project-thumbnail, but no change:

.project-thumbnail {
  overflow: auto
}

jsFiddle

EDIT

As the comment suggests, setting a height to the caption div div.thumb would enable it to float correctly. A fixed height will cut off content that becomes too big for it. Adding overflow: auto to this div will just add a scrollbar to it, this is not what I am after.

EDIT

This site here has a similar system. Items with a width are floated, no row separator, but if the content within their div extends beyond a few lines, the bottom of the div will adjust, aligning the next row neatly.

Body:
updated, thanks to @user10089632 for comment

To get the layout you want using float, try adding the clear property to every 4th .column.

example

.column:nth-child(3n + 4) {
  clear: both;
}

This will target every 3rd .column, beginning from the 4th .column (you don't need to apply the rule to the first div in your example)

You can adjust nth-child(n) if you need to change your grid to 4 x 4 or something else.

You can apply this code to article instead, depending on the rest of your site.

fiddle

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}

.column:nth-child(4) {
  clear: both;
}

  <div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div>


问:
Copying text of textarea into div with line breaks
I am tying to make a simple effect using keyup() in jQuery. I just want that when user types into the textarea then the text which user types will copy to another div named .content. When I press enter in textarea a new line is created but in my div the text is showing in the same line. My code is below or you can see demo here: http://jsfiddle.net/Pqygp/

    $('.content:not(.focus)').keyup(function(){
        var value = $(this).val();
        var contentAttr = $(this).attr('name');

        $('.'+contentAttr+'').html(value);
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="mas" rows="15" class="content"></textarea>
    <p> </p>
    <div class="mas" >Texts Comes here</div></code>```

答:
If you use React:</p>

```<code>render() {
  const nbOfTextareaRows = this.state.textareaValue.split('\n').length;

  return (
    <textarea
      value={this.state.textareaValue}
      onChange={e => this.setState({ textareaValue: e.target.value })}
      rows={nbOfTextareaRows}
    />
  );
}
</code>```

Body:
I am tying to make a simple effect using keyup() in jQuery. I just want that when user types into the textarea then the text which user types will copy to another div named .content. When I press enter in textarea a new line is created but in my div the text is showing in the same line. My code is below or you can see demo here: http://jsfiddle.net/Pqygp/

    $('.content:not(.focus)').keyup(function(){
        var value = $(this).val();
        var contentAttr = $(this).attr('name');

        $('.'+contentAttr+'').html(value);
    })

<textarea name="mas" rows="15" class="content"></textarea>

Texts Comes here

Body:
If you use React:

render() {
  const nbOfTextareaRows = this.state.textareaValue.split('\n').length;

  return (
    <textarea
      value={this.state.textareaValue}
      onChange={e => this.setState({ textareaValue: e.target.value })}
      rows={nbOfTextareaRows}
    />
  );
}


问:
Combined lookup and embed in the same MongoDB collection depending on root document structure
I want to make a conditional lookup with Mongo in the following way: a root document contains either a link (customerId) to the customers collection or directly embeds a customer, like this:

```<code>{
  "_id" : 1,
  "item": "item1",
  "customer": { _id: 1, "name": "Jane Doe" }
},
{
   "_id":  2,
   "item": "item2",
   "customerId": 1
}
</code>```

customers collection:

```<code>{ _id: 1, "name": "Jane Johnson" }
</code>```

The customers collection stores the current versions of customers; to maintain consistency, members of the items collection will contain just ids of customer. But if I want to freeze an item so it holds the version of its customer at a certain time, I will embed that customer directly into the item in question.

When searching for items I want them to appear uniformly (i.e. regardless whether customer is looked up or embedded it will appear as embedded field):
e.g.

```<code>[{
  "_id" : 1,
  "item": "item1",
  "customer": { _id: 1, "name": "Jane Doe" } // historical version of Jane (embedded)
},
{
   "_id":  2,
   "item": "item2",
   "customer": { _id: 1, "name": "Jane Johnson" } // current version of Jane by lookup
}]
</code>```

Question 1: is this the right approach and if not what is the best practice for handling cases like this?
Question 2: if my approach is correct, how to best use aggregation framework to achieve this?
Thanks!

答:
The answers:

Yes, you can achieve it with aggregation framework and it is one of the possible solutions (the other possible solution would be to implement it in your program).

Just use $lookup (for data merging from other collection) and $project (for final result generation) pipeline stages.

Query example:

```<code>db.getCollection('items').aggregate([
    {
        $lookup: {
            from: "customers",
            localField: "customerId",
            foreignField: "_id",
            as: "customerData"
        }
    },
    {
        $project: {
            "item": 1,
            "customer": {
                $cond: {
                    if: {$gt: [{$size: "$customerData"}, 0]},
                    then: {$arrayElemAt: ["$customerData", 0]},
                    else: "$customer"
                }
            }
       }
    }
]);
</code>```

Body:
I want to make a conditional lookup with Mongo in the following way: a root document contains either a link (customerId) to the customers collection or directly embeds a customer, like this:

{
  "_id" : 1,
  "item": "item1",
  "customer": { _id: 1, "name": "Jane Doe" }
},
{
   "_id":  2,
   "item": "item2",
   "customerId": 1
}

customers collection:

{ _id: 1, "name": "Jane Johnson" }

The customers collection stores the current versions of customers; to maintain consistency, members of the items collection will contain just ids of customer. But if I want to freeze an item so it holds the version of its customer at a certain time, I will embed that customer directly into the item in question.

When searching for items I want them to appear uniformly (i.e. regardless whether customer is looked up or embedded it will appear as embedded field):
e.g.

[{
  "_id" : 1,
  "item": "item1",
  "customer": { _id: 1, "name": "Jane Doe" } // historical version of Jane (embedded)
},
{
   "_id":  2,
   "item": "item2",
   "customer": { _id: 1, "name": "Jane Johnson" } // current version of Jane by lookup
}]

Question 1: is this the right approach and if not what is the best practice for handling cases like this?
Question 2: if my approach is correct, how to best use aggregation framework to achieve this?
Thanks!

Body:
The answers:

Yes, you can achieve it with aggregation framework and it is one of the possible solutions (the other possible solution would be to implement it in your program).

Just use $lookup (for data merging from other collection) and $project (for final result generation) pipeline stages.

Query example:

db.getCollection('items').aggregate([
    {
        $lookup: {
            from: "customers",
            localField: "customerId",
            foreignField: "_id",
            as: "customerData"
        }
    },
    {
        $project: {
            "item": 1,
            "customer": {
                $cond: {
                    if: {$gt: [{$size: "$customerData"}, 0]},
                    then: {$arrayElemAt: ["$customerData", 0]},
                    else: "$customer"
                }
            }
       }
    }
]);


问:
pandas plot line segments for each row
I have dataframes with columns containing x,y coordinates for multiple points. One row can consist of several points.
I'm trying to find out an easy way to be able to plot lines between each point generating a curve for each row of data.

Here is a simplified example where two lines are represented by two points each.

```<code>line1 = {'p1_x':1, 'p1_y':10, 'p2_x':2, 'p2_y':11 }
line2 = {'p1_x':2, 'p1_y':9, 'p2_x':3, 'p2_y':12 }
df = pd.DataFrame([line1,line2])

df.plot(y=['p1_y','p2_y'], x=['p1_x','p2_x'])
</code>```

when trying to plot them I expect line 1 to start where x=1 and line 2 to start where x=2.
Instead, the x axis contains two value-pairs (1,2) and (2,3) and both lines have the same start and end-point in x-axis.

How do I get around this problem?

Edit:
If using matplotlib, the following hardcoded values generates the plot i'm interested in
    plt.plot([[1,2],[2,3]],[[10,9],[11,12]])

答:
While I'm sure that there should be a more succinct way using pure pandas, here's a simple approach using matplotlib and some derivatives from the original df.(I hope I understood the question correctly)

Assumption: In df, you place x values in even columns and y values in odd columns

Obtain x values

```<code>x = df.loc[:, df.columns[::2]]
x

    p1_x    p2_x
0   1   2
1   2   3
</code>```

Obtain y values

```<code>y = df.loc[:, df.columns[1::2]]
y

    p1_y    p2_y
0   10  11
1   9   12
</code>```

Then plot using a for loop

```<code>for i in range(len(df)):
    plt.plot(x.iloc[i,:], y.iloc[i,:])
</code>```

Title: pandas plot line segments for each row

Body:
I have dataframes with columns containing x,y coordinates for multiple points. One row can consist of several points.
I'm trying to find out an easy way to be able to plot lines between each point generating a curve for each row of data.

Here is a simplified example where two lines are represented by two points each.

line1 = {'p1_x':1, 'p1_y':10, 'p2_x':2, 'p2_y':11 }
line2 = {'p1_x':2, 'p1_y':9, 'p2_x':3, 'p2_y':12 }
df = pd.DataFrame([line1,line2])

df.plot(y=['p1_y','p2_y'], x=['p1_x','p2_x'])

when trying to plot them I expect line 1 to start where x=1 and line 2 to start where x=2.
Instead, the x axis contains two value-pairs (1,2) and (2,3) and both lines have the same start and end-point in x-axis.

How do I get around this problem?

Edit:
If using matplotlib, the following hardcoded values generates the plot i'm interested in
    plt.plot([[1,2],[2,3]],[[10,9],[11,12]])

Body:
While I'm sure that there should be a more succinct way using pure pandas, here's a simple approach using matplotlib and some derivatives from the original df.(I hope I understood the question correctly)

Assumption: In df, you place x values in even columns and y values in odd columns

Obtain x values

x = df.loc[:, df.columns[::2]]
x

    p1_x    p2_x
0   1   2
1   2   3

Obtain y values

y = df.loc[:, df.columns[1::2]]
y

    p1_y    p2_y
0   10  11
1   9   12

Then plot using a for loop

for i in range(len(df)):
    plt.plot(x.iloc[i,:], y.iloc[i,:])


问:
Flexbox: align right several elements
I have an HTML-structure:

```<code>  <div class="parent">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item item--right">4</div>
    <div class="item item--right">5</div>
  </div>
</code>```

And styles:

```<code>.parent {
  display: flex;
  flex-wrap: no-wrap;
  align-content: flex-start;
}

.item {
  width: 50px;
}
</code>```

I want items 1, 2 and 3 to be on the left, and items 4 and 5 on the right.
I was trying to solve this problem using align-self: right:

```<code>.item--right {
  align-self: right;
}
</code>```

But it didn't help.
Here's my fiddle. What am I doing wrong?

答:
Find the first element that needs to be pushed right and apply margin-left:auto

.parent {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.item {
  width: 50px;
}

div:nth-child(4) {
  margin-left: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item item--right">4</div>
  <div class="item item--right">5</div>
</div></code>```

Title: Flexbox: align right several elements

Body:
I have an HTML-structure:

1

2

3

4

5

And styles:

.parent {
  display: flex;
  flex-wrap: no-wrap;
  align-content: flex-start;
}

.item {
  width: 50px;
}

I want items 1, 2 and 3 to be on the left, and items 4 and 5 on the right.
I was trying to solve this problem using align-self: right:

.item--right {
  align-self: right;
}

But it didn't help.
Here's my fiddle. What am I doing wrong?

Body:
Find the first element that needs to be pushed right and apply margin-left:auto

.parent {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.item {
  width: 50px;
}

div:nth-child(4) {
  margin-left: auto;
}

<div class="parent">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item item--right">4</div>
  <div class="item item--right">5</div>
</div>


问:
How to get name of calling function/method in PHP?
I am aware of function debug_backtrace, but I am looking for some ready to use implementation of function like GetCallingMethodName()? It would be perfect if it gave method's class too (if it is indeed a method).

答:
I just wrote a version of this called "get_caller", I hope it helps. Mine is pretty lazy. You can just run get_caller() from a function, you don't have to specify it like this:

```<code>get_caller(__FUNCTION__);
</code>```

Here's the script in full with a quirky test case:

```<code><?php

/* This function will return the name string of the function that called $function. To return the
    caller of your function, either call get_caller(), or get_caller(__FUNCTION__).
*/
function get_caller($function = NULL, $use_stack = NULL) {
    if ( is_array($use_stack) ) {
        // If a function stack has been provided, used that.
        $stack = $use_stack;
    } else {
        // Otherwise create a fresh one.
        $stack = debug_backtrace();
        echo "\nPrintout of Function Stack: \n\n";
        print_r($stack);
        echo "\n";
    }

    if ($function == NULL) {
        // We need $function to be a function name to retrieve its caller. If it is omitted, then
        // we need to first find what function called get_caller(), and substitute that as the
        // default $function. Remember that invoking get_caller() recursively will add another
        // instance of it to the function stack, so tell get_caller() to use the current stack.
        $function = get_caller(__FUNCTION__, $stack);
    }

    if ( is_string($function) && $function != "" ) {
        // If we are given a function name as a string, go through the function stack and find
        // it's caller.
        for ($i = 0; $i < count($stack); $i++) {
            $curr_function = $stack[$i];
            // Make sure that a caller exists, a function being called within the main script
            // won't have a caller.
            if ( $curr_function["function"] == $function && ($i + 1) < count($stack) ) {
                return $stack[$i + 1]["function"];
            }
        }
    }

    // At this stage, no caller has been found, bummer.
    return "";
}

// TEST CASE

function woman() {
    $caller = get_caller(); // No need for get_caller(__FUNCTION__) here
    if ($caller != "") {
        echo $caller , "() called " , __FUNCTION__ , "(). No surprises there.\n";
    } else {
        echo "no-one called ", __FUNCTION__, "()\n";
    }
}

function man() {
    // Call the woman.
    woman();
}

// Don't keep him waiting
man();

// Try this to see what happens when there is no caller (function called from main script)
//woman();

?>
</code>```

man() calls woman(), who calls get_caller(). get_caller() doesn't know who called it yet, because the woman() was cautious and didn't tell it, so it recurses to find out. Then it returns who called woman(). And the printout in source-code mode in a browser shows the function stack:

```<code>Printout of Function Stack:

Array
(
    [0] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 46
            [function] => get_caller
            [args] => Array
                (
                )

        )

    [1] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 56
            [function] => woman
            [args] => Array
                (
                )

        )

    [2] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 60
            [function] => man
            [args] => Array
                (
                )

        )

)

man() called woman(). No surprises there.
</code>```

Body:
I just wrote a version of this called "get_caller", I hope it helps. Mine is pretty lazy. You can just run get_caller() from a function, you don't have to specify it like this:

get_caller(__FUNCTION__);

Here's the script in full with a quirky test case:

<?php

/* This function will return the name string of the function that called $function. To return the
    caller of your function, either call get_caller(), or get_caller(__FUNCTION__).
*/
function get_caller($function = NULL, $use_stack = NULL) {
    if ( is_array($use_stack) ) {
        // If a function stack has been provided, used that.
        $stack = $use_stack;
    } else {
        // Otherwise create a fresh one.
        $stack = debug_backtrace();
        echo "\nPrintout of Function Stack: \n\n";
        print_r($stack);
        echo "\n";
    }

    if ($function == NULL) {
        // We need $function to be a function name to retrieve its caller. If it is omitted, then
        // we need to first find what function called get_caller(), and substitute that as the
        // default $function. Remember that invoking get_caller() recursively will add another
        // instance of it to the function stack, so tell get_caller() to use the current stack.
        $function = get_caller(__FUNCTION__, $stack);
    }

    if ( is_string($function) && $function != "" ) {
        // If we are given a function name as a string, go through the function stack and find
        // it's caller.
        for ($i = 0; $i < count($stack); $i++) {
            $curr_function = $stack[$i];
            // Make sure that a caller exists, a function being called within the main script
            // won't have a caller.
            if ( $curr_function["function"] == $function && ($i + 1) < count($stack) ) {
                return $stack[$i + 1]["function"];
            }
        }
    }

    // At this stage, no caller has been found, bummer.
    return "";
}

// TEST CASE

function woman() {
    $caller = get_caller(); // No need for get_caller(__FUNCTION__) here
    if ($caller != "") {
        echo $caller , "() called " , __FUNCTION__ , "(). No surprises there.\n";
    } else {
        echo "no-one called ", __FUNCTION__, "()\n";
    }
}

function man() {
    // Call the woman.
    woman();
}

// Don't keep him waiting
man();

// Try this to see what happens when there is no caller (function called from main script)
//woman();

?>

man() calls woman(), who calls get_caller(). get_caller() doesn't know who called it yet, because the woman() was cautious and didn't tell it, so it recurses to find out. Then it returns who called woman(). And the printout in source-code mode in a browser shows the function stack:

Printout of Function Stack:

Array
(
    [0] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 46
            [function] => get_caller
            [args] => Array
                (
                )

        )

    [1] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 56
            [function] => woman
            [args] => Array
                (
                )

        )

    [2] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 60
            [function] => man
            [args] => Array
                (
                )

        )

)

man() called woman(). No surprises there.