问:
Pimps are not working when used with generics
Consider following code (script) in which the SeqPimps can't be changed:

```<code>import scala.reflect.ClassTag

implicit class SeqPimps[T: ClassTag](s: Seq[T]) {
  def indexOfOpt(e: T): Option[Int] = s.indexOf(e) match {
    case -1 => None
    case idx => Some(idx)
  }
}

class A[T] {
  val fn = (y: T) => List[T]().indexOfOpt(y)
}

object Main extends App {
  val fn = (y: Int) => List[Int]().indexOfOpt(y)

  println(fn(0))
  println((new A[String]).fn(""))
}
Main.main(args)
</code>```

It crashes with:

```<code>xxx/test.scala:11: error: value indexOfOpt is not a member of List[T]
  val fn = (y: T) => List[T]().indexOfOpt(y)
                               ^
one error found
</code>```

My questions:

Why is it working when type is explicitly specified (in Main, after commenting out A and the one println it works fine) and complaining about non-existing member when generic type is used? The call looks same.

How to fix the snippet without modifying SeqPimps (e.g. removing of ClassTag - it is required by other methods in real project)?

答:
Remember that writing class SeqPimps[T: ClassTag](s: Seq[T]) actually tells the compiler to add an implicit parameter like that: class SeqPimps[T](s: Seq[T])(implicit ev: ClassTag[T]).

The compilation fails because the implicit SeqPimps cannot be applied, and this one cannot be applied because no implicit ClassTag[T] is available from within A.

There are a couple ways you can add a ClassTag there, for example: class A[T : ClassTag] {. Where to pass that implicit ClassTag is up to you and your use case...

Body:
Consider following code (script) in which the SeqPimps can't be changed:

import scala.reflect.ClassTag

implicit class SeqPimps[T: ClassTag](s: Seq[T]) {
  def indexOfOpt(e: T): Option[Int] = s.indexOf(e) match {
    case -1 => None
    case idx => Some(idx)
  }
}

class A[T] {
  val fn = (y: T) => List[T]().indexOfOpt(y)
}

object Main extends App {
  val fn = (y: Int) => List[Int]().indexOfOpt(y)

  println(fn(0))
  println((new A[String]).fn(""))
}
Main.main(args)

It crashes with:

xxx/test.scala:11: error: value indexOfOpt is not a member of List[T]
  val fn = (y: T) => List[T]().indexOfOpt(y)
                               ^
one error found

My questions:

Why is it working when type is explicitly specified (in Main, after commenting out A and the one println it works fine) and complaining about non-existing member when generic type is used? The call looks same.

How to fix the snippet without modifying SeqPimps (e.g. removing of ClassTag - it is required by other methods in real project)?


来源: stackexchange

问:
remove middle octets from an ip until some criteria is met
I have a string of IP and port numbers which is like :  "10.213.110.49.33482;10.213.106.12.20001:"
The two ip's are separated by a semi-colon. Last decimal shows port number.
What I need is to convert the above string which would look like:
"10.213.110.49 20001:".

I want to remove the middle octets and port number of first IP using SHELL SCRIPT only. I want to extract the IP from first part ignoring the port number and from second IP i want the port number only

ContentLicense: CC BY-SA 3.0

Body:
You can just use bash substitution, just takes a couple of steps:

s='10.213.110.49.33482;10.213.106.12.20001:'

port="${s##*.}"

ip="${s%;*}"
ip="${ip%.*}"

echo "$ip $port"


问:
Xamarin iOS app SIGSEGV
I am getting occasional SIGSEGV errors like below in my app (c# Xamarin iOS app with latest version of Xamarin Studio=5.8.3, Xamarin.iOS=8.9.1.3

It looks like in crashed in UIKit and from my own app "ObymobiMobileAppiOS" it's just in "main".

What kind of problem it is?
How can I get more info or debug it?

I can reproduce it by using the app for about 5 mins.

Stacktrace:

```<code>at <unknown> <0xffffffff>
at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain (int,string[],intptr,intptr) <0xffffffff>
at UIKit.UIApplication.Main (string[],intptr,intptr) [0x00005] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:62
at UIKit.UIApplication.Main (string[],string,string) [0x0001c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:45
at Obymobi.Mobile.App.iOS.Application.Main (string[]) [0x000b9] in /Users/billbatchelor/Documents/Mobile Development/AllInOne/Obymobi.Xamarin/Obymobi.Mobile.App.iOS/Main.cs:52
at (wrapper runtime-invoke) object.runtime_invoke_dynamic (intptr,intptr,intptr,intptr) <0xffffffff>
</code>```

Native stacktrace:

```<code>0   ObymobiMobileAppiOS                 0x00000001024ef9ac mono_handle_native_sigsegv + 264
1   ObymobiMobileAppiOS                 0x00000001024f97cc mono_sigsegv_signal_handler + 316
2   libsystem_platform.dylib            0x000000019890895c _sigtramp + 68
3   UIKit                               0x000000018b535540 <redacted> + 216
4   UIKit                               0x000000018b535030 <redacted> + 452
5   UIKit                               0x000000018b534e38 <redacted> + 216
6   UIKit                               0x000000018b534d4c <redacted> + 468
7   UIKit                               0x000000018b48fd8c <redacted> + 264
8   UIKit                               0x000000018b32ca2c <redacted> + 700
9   UIKit                               0x000000018b325f68 <redacted> + 684
10  UIKit                               0x000000018b2f918c <redacted> + 264
11  UIKit                               0x000000018b59a324 <redacted> + 15424
12  UIKit                               0x000000018b2f76a0 <redacted> + 1716
13  CoreFoundation                      0x0000000186870240 <redacted> + 24
14  CoreFoundation                      0x000000018686f4e4 <redacted> + 264
15  CoreFoundation                      0x000000018686d594 <redacted> + 712
16  CoreFoundation                      0x00000001867992d4 CFRunLoopRunSpecific + 396
17  GraphicsServices                    0x000000018ffaf6fc GSEventRunModal + 168
18  UIKit                               0x000000018b35efac UIApplicationMain + 1488
19  ObymobiMobileAppiOS                 0x0000000100b61f28 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr + 344
20  ObymobiMobileAppiOS                 0x00000001005387c0 UIKit_UIApplication_Main_string___intptr_intptr + 48
21  ObymobiMobileAppiOS                 0x000000010053865c UIKit_UIApplication_Main_string___string_string + 188
22  ObymobiMobileAppiOS                 0x000000010009c654 Obymobi_Mobile_App_iOS_Application_Main_string__ + 1508
23  ObymobiMobileAppiOS                 0x0000000101007130 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 160
24  ObymobiMobileAppiOS                 0x00000001024fb88c mono_jit_runtime_invoke + 1260
25  ObymobiMobileAppiOS                 0x00000001025511e0 mono_runtime_invoke + 128
26  ObymobiMobileAppiOS                 0x00000001025553c4 mono_runtime_exec_main + 404
27  ObymobiMobileAppiOS                 0x00000001025c6a50 xamarin_main + 1812
28  ObymobiMobileAppiOS                 0x00000001024b9688 main + 96
29  libdyld.dylib                       0x000000019875aa08 <redacted> + 4

=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries used by your application.
</code>```

Update
Here is another example of SIGSEGVs I get (this was on simulator) which doesn't have "redacted":-

Any more ideas how to find the problem? Or is it a possible bug in Xamarin?

Native stacktrace:

```<code>0   ObymobiMobileAppiOS                 0x0011d4f7 mono_handle_native_sigsegv + 311
1   ObymobiMobileAppiOS                 0x0014c505 mono_sigsegv_signal_handler + 213
2   libsystem_platform.dylib            0x08c8003b _sigtramp + 43
3   ???                                 0xffffffff 0x0 + 4294967295
4   VectorKit                           0x10663fe9 -[VKTileProvider tileSource:didFetchTile:forKey:] + 105
5   VectorKit                           0x1067140e -[VKTileSource fetchedTile:forKey:] + 62
6   VectorKit                           0x106c2617 -[VKTileSetBackedTileSource fetchedTile:forKey:] + 247
7   VectorKit                           0x106705b5 -[VKTileSource _fetchedTile:] + 309
8   VectorKit                           0x10671985 __49-[VKTileSource decodeData:downloadKey:sourceKey:]_block_invoke_2 + 181
9   libdispatch.dylib                   0x08930d8a _dispatch_call_block_and_release + 15
10  libdispatch.dylib                   0x0894decf _dispatch_client_callout + 14
11  libdispatch.dylib                   0x0893602e _dispatch_queue_drain + 411
12  libdispatch.dylib                   0x08935d33 _dispatch_queue_invoke + 197
13  libdispatch.dylib                   0x0893820b _dispatch_root_queue_drain + 428
14  libdispatch.dylib                   0x089393e7 _dispatch_worker_thread3 + 108
15  libsystem_pthread.dylib             0x08c8d1da _pthread_wqthread + 724
16  libsystem_pthread.dylib             0x08c8ae2e start_wqthread + 30
</code>```

答: Are the version of Xamarin equal on OS X and Windows? I had similar error. When I updated Xamarin, everything was fine.</p>

Title: Xamarin iOS app SIGSEGV

Body:
I am getting occasional SIGSEGV errors like below in my app (c# Xamarin iOS app with latest version of Xamarin Studio=5.8.3, Xamarin.iOS=8.9.1.3

It looks like in crashed in UIKit and from my own app "ObymobiMobileAppiOS" it's just in "main".

What kind of problem it is?
How can I get more info or debug it?

I can reproduce it by using the app for about 5 mins.

Stacktrace:

at <unknown> <0xffffffff>
at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain (int,string[],intptr,intptr) <0xffffffff>
at UIKit.UIApplication.Main (string[],intptr,intptr) [0x00005] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:62
at UIKit.UIApplication.Main (string[],string,string) [0x0001c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:45
at Obymobi.Mobile.App.iOS.Application.Main (string[]) [0x000b9] in /Users/billbatchelor/Documents/Mobile Development/AllInOne/Obymobi.Xamarin/Obymobi.Mobile.App.iOS/Main.cs:52
at (wrapper runtime-invoke) object.runtime_invoke_dynamic (intptr,intptr,intptr,intptr) <0xffffffff>

Native stacktrace:

0   ObymobiMobileAppiOS                 0x00000001024ef9ac mono_handle_native_sigsegv + 264
1   ObymobiMobileAppiOS                 0x00000001024f97cc mono_sigsegv_signal_handler + 316
2   libsystem_platform.dylib            0x000000019890895c _sigtramp + 68
3   UIKit                               0x000000018b535540 <redacted> + 216
4   UIKit                               0x000000018b535030 <redacted> + 452
5   UIKit                               0x000000018b534e38 <redacted> + 216
6   UIKit                               0x000000018b534d4c <redacted> + 468
7   UIKit                               0x000000018b48fd8c <redacted> + 264
8   UIKit                               0x000000018b32ca2c <redacted> + 700
9   UIKit                               0x000000018b325f68 <redacted> + 684
10  UIKit                               0x000000018b2f918c <redacted> + 264
11  UIKit                               0x000000018b59a324 <redacted> + 15424
12  UIKit                               0x000000018b2f76a0 <redacted> + 1716
13  CoreFoundation                      0x0000000186870240 <redacted> + 24
14  CoreFoundation                      0x000000018686f4e4 <redacted> + 264
15  CoreFoundation                      0x000000018686d594 <redacted> + 712
16  CoreFoundation                      0x00000001867992d4 CFRunLoopRunSpecific + 396
17  GraphicsServices                    0x000000018ffaf6fc GSEventRunModal + 168
18  UIKit                               0x000000018b35efac UIApplicationMain + 1488
19  ObymobiMobileAppiOS                 0x0000000100b61f28 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr + 344
20  ObymobiMobileAppiOS                 0x00000001005387c0 UIKit_UIApplication_Main_string___intptr_intptr + 48
21  ObymobiMobileAppiOS                 0x000000010053865c UIKit_UIApplication_Main_string___string_string + 188
22  ObymobiMobileAppiOS                 0x000000010009c654 Obymobi_Mobile_App_iOS_Application_Main_string__ + 1508
23  ObymobiMobileAppiOS                 0x0000000101007130 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 160
24  ObymobiMobileAppiOS                 0x00000001024fb88c mono_jit_runtime_invoke + 1260
25  ObymobiMobileAppiOS                 0x00000001025511e0 mono_runtime_invoke + 128
26  ObymobiMobileAppiOS                 0x00000001025553c4 mono_runtime_exec_main + 404
27  ObymobiMobileAppiOS                 0x00000001025c6a50 xamarin_main + 1812
28  ObymobiMobileAppiOS                 0x00000001024b9688 main + 96
29  libdyld.dylib                       0x000000019875aa08 <redacted> + 4

=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries used by your application.

Update
Here is another example of SIGSEGVs I get (this was on simulator) which doesn't have "redacted":-

Any more ideas how to find the problem? Or is it a possible bug in Xamarin?

Native stacktrace:

0   ObymobiMobileAppiOS                 0x0011d4f7 mono_handle_native_sigsegv + 311
1   ObymobiMobileAppiOS                 0x0014c505 mono_sigsegv_signal_handler + 213
2   libsystem_platform.dylib            0x08c8003b _sigtramp + 43
3   ???                                 0xffffffff 0x0 + 4294967295
4   VectorKit                           0x10663fe9 -[VKTileProvider tileSource:didFetchTile:forKey:] + 105
5   VectorKit                           0x1067140e -[VKTileSource fetchedTile:forKey:] + 62
6   VectorKit                           0x106c2617 -[VKTileSetBackedTileSource fetchedTile:forKey:] + 247
7   VectorKit                           0x106705b5 -[VKTileSource _fetchedTile:] + 309
8   VectorKit                           0x10671985 __49-[VKTileSource decodeData:downloadKey:sourceKey:]_block_invoke_2 + 181
9   libdispatch.dylib                   0x08930d8a _dispatch_call_block_and_release + 15
10  libdispatch.dylib                   0x0894decf _dispatch_client_callout + 14
11  libdispatch.dylib                   0x0893602e _dispatch_queue_drain + 411
12  libdispatch.dylib                   0x08935d33 _dispatch_queue_invoke + 197
13  libdispatch.dylib                   0x0893820b _dispatch_root_queue_drain + 428
14  libdispatch.dylib                   0x089393e7 _dispatch_worker_thread3 + 108
15  libsystem_pthread.dylib             0x08c8d1da _pthread_wqthread + 724
16  libsystem_pthread.dylib             0x08c8ae2e start_wqthread + 30


问:
Django Admin list_display product list
I new in django and I trying modifying a project to learn.

I've two classes in a model ('Order' and 'OrderItem'), the class OrderItem stores all items selected in a client order.

models.py

```<code>class Order(models.Model):

    STATUS_CHOICES = (
        (0, 'Waiting Payment'),
        (1, 'Completed'),
        (2, 'Canceled'),
    )

    PAYMENT_OPTION_CHOICES = (
        ('deposit', 'deposit'),
        ('paypal', 'Paypal'),
    )

    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='User')
    status = models.IntegerField(
        'Situation', choices=STATUS_CHOICES, default=0, blank=True
    )
    payment_option = models.CharField(
        'Payment Options', choices=PAYMENT_OPTION_CHOICES, max_length=20,
         default='deposit'
    )

    created = models.DateTimeField('Created in', auto_now_add=True)
    modified = models.DateTimeField('Modified in', auto_now=True)

    objects = OrderManager()

    class Meta:
        verbose_name = 'Order'
        ordering = ('-created',)

    def __str__(self):
        return 'Order #{}'.format(self.pk)

    def products(self):
        products_ids = self.items.values_list('product')
        return Product.objects.filter(pk__in=products_ids)

    def total(self):
        aggregate_queryset = self.items.aggregate(
            total = models.Sum(
                models.F('price') * models.F('quantity'),
                output_field = models.DecimalField()
            )
        )
        return aggregate_queryset['total']

class OrderItem(models.Model):

    order = models.ForeignKey(Order, verbose_name='Order',     related_name='items')
    product = models.ForeignKey('event.Product', verbose_name='Product')
    quantity = models.PositiveIntegerField('Quantity', default=1)
    price = models.DecimalField('Price', decimal_places=2, max_digits=8)

    class Meta:
        verbose_name = 'Order Item'

    def __str__(self):
        return '{}'.format(self.product)
</code>```

In the django admin I can show all Orders and when I click to see more I see all products on this order, but my problem is, I can't list this products of class OrderItem in my list_display, how  can I do that?

admin.py

```<code>class OrderItemInline(admin.StackedInline):
    model = OrderItem
    fields = ['product']
    readonly_fields = ['product',]
    extra = 0
    max_num = 0

class OrderAdmin(admin.ModelAdmin):

    model = Order
    inlines = [ OrderItemInline, ]

    readonly_fieldsets = (
        (None, {
            'fields': ('user','status','order','created')
        }),
    )
    readonly_fields = ['user','status','payment_option']

    search_fields = ['user__name', 'user__email']
    list_filter = ['status', ]

    list_display = ['pk','user','status','created','product']
    ordering = ('-created',)

   admin.site.register(Order, OrderAdmin)
</code>```

答:
That's an easy task. Inside your OrderAdmin class, remove the product from the display_list list and add a string that will be the name of a method/callable, say list_products. Now, list_display will show the returned value of that function.

For example, define a list_products method inside the OrderAdmin class.

```<code>from django.utils.html import mark_safe

class OrderAdmin(admin.ModelAdmin):

    list_display = ['pk', 'user', 'status', 'created', 'list_products']

    def list_products(self, obj):
        # each obj will be an Order obj/instance/row
        to_return = '<ul>'
        # I'm assuming that there is a name field under the event.Product model. If not change accordingly.
        to_return += '\n'.join('<li>{}</li>'.format(pro_name) for prod_name in obj.items.values_list('product__name', flat=True))
        to_return += '</ul>'
        return mark_safe(to_return)
</code>```

Title: Django Admin list_display product list

Body:
I new in django and I trying modifying a project to learn.

I've two classes in a model ('Order' and 'OrderItem'), the class OrderItem stores all items selected in a client order.

models.py

class Order(models.Model):

    STATUS_CHOICES = (
        (0, 'Waiting Payment'),
        (1, 'Completed'),
        (2, 'Canceled'),
    )

    PAYMENT_OPTION_CHOICES = (
        ('deposit', 'deposit'),
        ('paypal', 'Paypal'),
    )

    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='User')
    status = models.IntegerField(
        'Situation', choices=STATUS_CHOICES, default=0, blank=True
    )
    payment_option = models.CharField(
        'Payment Options', choices=PAYMENT_OPTION_CHOICES, max_length=20,
         default='deposit'
    )

    created = models.DateTimeField('Created in', auto_now_add=True)
    modified = models.DateTimeField('Modified in', auto_now=True)

    objects = OrderManager()

    class Meta:
        verbose_name = 'Order'
        ordering = ('-created',)

    def __str__(self):
        return 'Order #{}'.format(self.pk)

    def products(self):
        products_ids = self.items.values_list('product')
        return Product.objects.filter(pk__in=products_ids)

    def total(self):
        aggregate_queryset = self.items.aggregate(
            total = models.Sum(
                models.F('price') * models.F('quantity'),
                output_field = models.DecimalField()
            )
        )
        return aggregate_queryset['total']

class OrderItem(models.Model):

    order = models.ForeignKey(Order, verbose_name='Order',     related_name='items')
    product = models.ForeignKey('event.Product', verbose_name='Product')
    quantity = models.PositiveIntegerField('Quantity', default=1)
    price = models.DecimalField('Price', decimal_places=2, max_digits=8)

    class Meta:
        verbose_name = 'Order Item'

    def __str__(self):
        return '{}'.format(self.product)

In the django admin I can show all Orders and when I click to see more I see all products on this order, but my problem is, I can't list this products of class OrderItem in my list_display, how  can I do that?

admin.py

class OrderItemInline(admin.StackedInline):
    model = OrderItem
    fields = ['product']
    readonly_fields = ['product',]
    extra = 0
    max_num = 0

class OrderAdmin(admin.ModelAdmin):

    model = Order
    inlines = [ OrderItemInline, ]

    readonly_fieldsets = (
        (None, {
            'fields': ('user','status','order','created')
        }),
    )
    readonly_fields = ['user','status','payment_option']

    search_fields = ['user__name', 'user__email']
    list_filter = ['status', ]

    list_display = ['pk','user','status','created','product']
    ordering = ('-created',)

   admin.site.register(Order, OrderAdmin)

Body:
That's an easy task. Inside your OrderAdmin class, remove the product from the display_list list and add a string that will be the name of a method/callable, say list_products. Now, list_display will show the returned value of that function.

For example, define a list_products method inside the OrderAdmin class.

from django.utils.html import mark_safe

class OrderAdmin(admin.ModelAdmin):

    list_display = ['pk', 'user', 'status', 'created', 'list_products']

    def list_products(self, obj):
        # each obj will be an Order obj/instance/row
        to_return = '<ul>'
        # I'm assuming that there is a name field under the event.Product model. If not change accordingly.
        to_return += '\n'.join('<li>{}</li>'.format(pro_name) for prod_name in obj.items.values_list('product__name', flat=True))
        to_return += '</ul>'
        return mark_safe(to_return)


问:
Hibernate Statistics Logging
I am a little stuck interpreting hibernate session logs.
I have the main problem that many queries are kind of slow - based on some TimeWatch loggings I have implemented.
To track down the problem further I have enabled hibernate session logging with the goal of seeing if the time is lost for executing the query or for getting a connection (which would mean a misconfiguration, I guess).

Little bit about the use case - Oracle DB, Spring, Hibernate. At "busy times" there are a max. of 15 threads executing queries against the database. So nothing special, I would guess.

Now I see hibernate session logs like.

```<code>2017-03-30 13:35:13.834+0200 [process-documents-task-6] I [/] o.h.e.i.StatisticalLoggingSessionEventListener - Session Metrics {
    636713687 nanoseconds spent acquiring 1 JDBC connections;
    57993 nanoseconds spent releasing 1 JDBC connections;
    636859879 nanoseconds spent preparing 1 JDBC statements;
    2231526 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    9261 nanoseconds spent executing 1 partial-flushes (flushing a total of 0 entities and 0 collections)
</code>```

or

```<code>2017-03-30 13:35:16.073+0200 [process-documents-task-8] I [/] o.h.e.i.StatisticalLoggingSessionEventListener - Session Metrics {
    2893793341 nanoseconds spent acquiring 1 JDBC connections;
    22196 nanoseconds spent releasing 1 JDBC connections;
    2893869403 nanoseconds spent preparing 1 JDBC statements;
    1509926 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    4056 nanoseconds spent executing 1 partial-flushes (flushing a total of 0 entities and 0 collections)
</code>```

But what exactly does that mean?

What I interpret at the moment

1509926 nanoseconds for executing the query (1.5 ms): Seems ok

2893793341 nanoseconds for acquiring a connection (2.8 sec): Not ok
:(

2893869403 nanoseconds for preparing the statement (2.8 sec): Not ok
:(

What does preparing statement mean?
From what I read from the javadoc it can mean that the query is sent to the database for optimization.
But why is it always around the time acquiring a connection needs?

Any advice on how to track down the problem, root cause even further?

Or any hints on what the problem could be?

Thanks for your help!

Best regards,
Stefan

答:
The default Hibernate statistics are not very informative. We plan on enhancing this aspect in a future version of Hibernate.

However, you can provide your own Statistics implementation that builds on top of Dropwizard Metrics.

In short, assuming you have a TransactionStatistics class that extends org.hibernate.stat.internal.ConcurrentStatisticsImpl:

```<code>public class TransactionStatistics extends ConcurrentStatisticsImpl {

    private static final ThreadLocal<AtomicLong> startNanos = new ThreadLocal<AtomicLong>() {
        @Override protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private static final ThreadLocal<AtomicLong> connectionCounter = new ThreadLocal<AtomicLong>() {
        @Override protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private StatisticsReport report = new StatisticsReport();

    @Override public void connect() {
        connectionCounter.get().incrementAndGet();
        startNanos.get().compareAndSet(0, System.nanoTime());
        super.connect();
    }

    @Override public void endTransaction(boolean success) {
        try {
            report.transactionTime(System.nanoTime() - startNanos.get().get());
            report.connectionsCount(connectionCounter.get().get());
            report.generate();
        } finally {
            startNanos.remove();
            connectionCounter.remove();
        }
        super.endTransaction(success);
    }
}
</code>```

You need to create a StatisticsFactory implementation:

```<code>public class TransactionStatisticsFactory implements StatisticsFactory {

    @Override
    public StatisticsImplementor buildStatistics(SessionFactoryImplementor sessionFactory) {
        return new TransactionStatistics();
    }
}
</code>```

And configure it like this:

```<code><property
    name="hibernate.stats.factory",
    value="com.vladmihalcea.book.hpjp.hibernate.statistics.TransactionStatisticsFactory"
/>
</code>```

Et voilà!

Now you can monitor and export statistics to any format that Dropwizard Metrics supports. And, Dropwizard Metrics uses various Reservoirs, so you can choose the best one for your use case.

To see the real power for Dropwizard Metrics, check out FlexyPool as well.

Title: Hibernate Statistics Logging

Body:
I am a little stuck interpreting hibernate session logs.
I have the main problem that many queries are kind of slow - based on some TimeWatch loggings I have implemented.
To track down the problem further I have enabled hibernate session logging with the goal of seeing if the time is lost for executing the query or for getting a connection (which would mean a misconfiguration, I guess).

Little bit about the use case - Oracle DB, Spring, Hibernate. At "busy times" there are a max. of 15 threads executing queries against the database. So nothing special, I would guess.

Now I see hibernate session logs like.

2017-03-30 13:35:13.834+0200 [process-documents-task-6] I [/] o.h.e.i.StatisticalLoggingSessionEventListener - Session Metrics {
    636713687 nanoseconds spent acquiring 1 JDBC connections;
    57993 nanoseconds spent releasing 1 JDBC connections;
    636859879 nanoseconds spent preparing 1 JDBC statements;
    2231526 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    9261 nanoseconds spent executing 1 partial-flushes (flushing a total of 0 entities and 0 collections)

or

2017-03-30 13:35:16.073+0200 [process-documents-task-8] I [/] o.h.e.i.StatisticalLoggingSessionEventListener - Session Metrics {
    2893793341 nanoseconds spent acquiring 1 JDBC connections;
    22196 nanoseconds spent releasing 1 JDBC connections;
    2893869403 nanoseconds spent preparing 1 JDBC statements;
    1509926 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    4056 nanoseconds spent executing 1 partial-flushes (flushing a total of 0 entities and 0 collections)

But what exactly does that mean?

What I interpret at the moment

1509926 nanoseconds for executing the query (1.5 ms): Seems ok

2893793341 nanoseconds for acquiring a connection (2.8 sec): Not ok
:(

2893869403 nanoseconds for preparing the statement (2.8 sec): Not ok
:(

What does preparing statement mean?
From what I read from the javadoc it can mean that the query is sent to the database for optimization.
But why is it always around the time acquiring a connection needs?

Any advice on how to track down the problem, root cause even further?

Or any hints on what the problem could be?

Thanks for your help!

Best regards,
Stefan

Body:
The default Hibernate statistics are not very informative. We plan on enhancing this aspect in a future version of Hibernate.

However, you can provide your own Statistics implementation that builds on top of Dropwizard Metrics.

In short, assuming you have a TransactionStatistics class that extends org.hibernate.stat.internal.ConcurrentStatisticsImpl:

public class TransactionStatistics extends ConcurrentStatisticsImpl {

    private static final ThreadLocal<AtomicLong> startNanos = new ThreadLocal<AtomicLong>() {
        @Override protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private static final ThreadLocal<AtomicLong> connectionCounter = new ThreadLocal<AtomicLong>() {
        @Override protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private StatisticsReport report = new StatisticsReport();

    @Override public void connect() {
        connectionCounter.get().incrementAndGet();
        startNanos.get().compareAndSet(0, System.nanoTime());
        super.connect();
    }

    @Override public void endTransaction(boolean success) {
        try {
            report.transactionTime(System.nanoTime() - startNanos.get().get());
            report.connectionsCount(connectionCounter.get().get());
            report.generate();
        } finally {
            startNanos.remove();
            connectionCounter.remove();
        }
        super.endTransaction(success);
    }
}

You need to create a StatisticsFactory implementation:

public class TransactionStatisticsFactory implements StatisticsFactory {

    @Override
    public StatisticsImplementor buildStatistics(SessionFactoryImplementor sessionFactory) {
        return new TransactionStatistics();
    }
}

And configure it like this:

<property
    name="hibernate.stats.factory",
    value="com.vladmihalcea.book.hpjp.hibernate.statistics.TransactionStatisticsFactory"
/>

Et voilà!

Now you can monitor and export statistics to any format that Dropwizard Metrics supports. And, Dropwizard Metrics uses various Reservoirs, so you can choose the best one for your use case.

To see the real power for Dropwizard Metrics, check out FlexyPool as well.

ContentLicense: CC BY-SA 4.0


问:
I need horizontal scrolling for GridView
I've got my GridView inside another Panel and I got scrollbars but GridView is to big even with paging. So user needs to scroll down to scroll horizontal (to see horizontal scrollbar).

How can I add any horizontal scrolling trick for my GridView in the Panel. Maybe something from javascript ? My js knowledges is still being poor.

I really hard thinking on what that could be, maybe floating horizontal scrollbar ?

Thank you.

答:
I think this is what you are searching for? :
scrollLeft</p>

ContentLicense: CC BY-SA 2.5


问:
How should a Rebol-structured data file (which contains no code) be written and read?
If you build up a block structure, convert it to a string with MOLD, and write it to a file like this:

```<code>>> write %datafile.dat mold [
    [{Release} 12-Dec-2012]
    [{Conference} [12-Jul-2013 .. 14-Jul-2013]]
]
</code>```

You can LOAD it back in later.  But what about headers?  If a file contains code, it is supposed to start with a header like:

```<code>rebol [
    title: "Local Area Defringer"
    date: 1-Jun-1957
    file: %defringe.r
    purpose: {
        Stabilize the wide area ignition transcriber
        using a double ganged defringing algorithm.
    }
]
</code>```

If you are just writing out data and reading it back in, are you expected to have a rebol [] header, and extend it with any properties you want to add?  Should you come up with your own myformat [] header concept with your own properties?

Also, given that LOAD does binding, does it make sense to use it for data or is there a different operation?

答:
For the case of reading, construct works very well alongside load to prevent evaluation (of code as opposed to data):

```<code>prefs: construct/with load %options.reb default-prefs
</code>```

It is:

Similar to context

```<code>obj: [
    name: "Fred"
    age: 27
    city: "Ukiah"
]

obj-context: context obj
obj-construct: construct obj
</code>```

In this case, the same:

```<code>>> obj-context = obj-construct
== true
</code>```

Different

when it comes to evaluating code:

```<code>obj-eval: [
    name: uppercase "Fred"
    age: 20 + 7
    time: now/time
]

obj-eval-context: context obj-eval
obj-eval-construct: construct obj-eval
</code>```

This time parsing differently:

```<code>>> obj-eval-context = obj-eval-construct
false

>> ?? obj-eval-construct
obj-eval-construct: make object! [
    name: 'uppercase
    age: 20
    time: now/time
]
</code>```

Aside:

This is the point I realize the following code wasn't behaving as I expected:

```<code>obj-eval: [
    title: uppercase "Fred"
    age: 20 + 7
    city: "Ukiah"
    time: now/time
]
</code>```

gives in red (and by extension, rebol2):

```<code>>> obj-eval-construct: construct obj-eval
== make object! [
    title: 'uppercase
    age: 20
    city: "Ukiah"
    time: now/time
]
</code>```

lit-word! and lit-path! is different.
TODO: question

It has also

Useful refinement /with

Which can be used for defaults, similar to make

Body:
If you build up a block structure, convert it to a string with MOLD, and write it to a file like this:

>> write %datafile.dat mold [
    [{Release} 12-Dec-2012]
    [{Conference} [12-Jul-2013 .. 14-Jul-2013]]
]

You can LOAD it back in later.  But what about headers?  If a file contains code, it is supposed to start with a header like:

rebol [
    title: "Local Area Defringer"
    date: 1-Jun-1957
    file: %defringe.r
    purpose: {
        Stabilize the wide area ignition transcriber
        using a double ganged defringing algorithm.
    }
]

If you are just writing out data and reading it back in, are you expected to have a rebol [] header, and extend it with any properties you want to add?  Should you come up with your own myformat [] header concept with your own properties?

Also, given that LOAD does binding, does it make sense to use it for data or is there a different operation?

Body:
For the case of reading, construct works very well alongside load to prevent evaluation (of code as opposed to data):

prefs: construct/with load %options.reb default-prefs

It is:

Similar to context

obj: [
    name: "Fred"
    age: 27
    city: "Ukiah"
]

obj-context: context obj
obj-construct: construct obj

In this case, the same:

>> obj-context = obj-construct
== true

Different

when it comes to evaluating code:

obj-eval: [
    name: uppercase "Fred"
    age: 20 + 7
    time: now/time
]

obj-eval-context: context obj-eval
obj-eval-construct: construct obj-eval

This time parsing differently:

>> obj-eval-context = obj-eval-construct
false

>> ?? obj-eval-construct
obj-eval-construct: make object! [
    name: 'uppercase
    age: 20
    time: now/time
]

Aside:

This is the point I realize the following code wasn't behaving as I expected:

obj-eval: [
    title: uppercase "Fred"
    age: 20 + 7
    city: "Ukiah"
    time: now/time
]

gives in red (and by extension, rebol2):

>> obj-eval-construct: construct obj-eval
== make object! [
    title: 'uppercase
    age: 20
    city: "Ukiah"
    time: now/time
]

lit-word! and lit-path! is different.
TODO: question

It has also

Useful refinement /with

Which can be used for defaults, similar to make


问:
C# generic type : Warning from outer type
I have a controller called UserController with generic type T:

```<code>public class UserController<T> : Controller
{
}
</code>```

And then, inside this class I have a method called Select() with generic typing:

```<code>public override T Select<T>(ushort id)
{
    // UserModel is just a Class where I is an integer typed property
    UserModel.I = 2;
    object result = UserModel.I;

    return (T)Convert.ChangeType(result, typeof(T));
    throw new NotImplementedException();
}
</code>```

Now in another form class I am accessing this method like this:

```<code>// This is so far working
UserController<int> us = new UserController<int>(0);
label1.Text = us.Select<string>(0);
</code>```

Now I am having this warning:

```<code>Severity    Code    Description Project File    Line    Suppression State
Warning CS0693  Type parameter 'T' has the same name as the type
parameter from outer type 'UserController<T>'
</code>```

I am not understanding what it is saying here:

```<code>Type parameter 'T' has the same name as the type
parameter from outer type 'UserController<T>'
</code>```

What am I doing wrong here?

答:
If you want your method to be parameterized with the same type as your class, then you don't include a generic parameter in the method name:

```<code>public override T Select(ushort id) /* Uses T from class */
</code>```

However, from your other sample it looks like you want to use different types - so use a different name for the parameter:

```<code>public override TInner Select<TInner>(ushort id)
{
    // UserModel is just a Class where I is an integer typed property
    UserModel.I = 2;
    object result = UserModel.I;

    return (TInner)Convert.ChangeType(result, typeof(TInner));

    throw new NotImplementedException();
}
</code>```

(In general, try to pick better names than just T or even TInner - just as you should pick good names for other parameters, try to convey the purpose of the type in the type parameter name)

Body:
I have a controller called UserController with generic type T:

public class UserController<T> : Controller
{
}

And then, inside this class I have a method called Select() with generic typing:

public override T Select<T>(ushort id)
{
    // UserModel is just a Class where I is an integer typed property
    UserModel.I = 2;
    object result = UserModel.I;

    return (T)Convert.ChangeType(result, typeof(T));
    throw new NotImplementedException();
}

Now in another form class I am accessing this method like this:

// This is so far working
UserController<int> us = new UserController<int>(0);
label1.Text = us.Select<string>(0);

Now I am having this warning:

Severity    Code    Description Project File    Line    Suppression State
Warning CS0693  Type parameter 'T' has the same name as the type
parameter from outer type 'UserController<T>'

I am not understanding what it is saying here:

Type parameter 'T' has the same name as the type
parameter from outer type 'UserController<T>'

What am I doing wrong here?

Body:
If you want your method to be parameterized with the same type as your class, then you don't include a generic parameter in the method name:

public override T Select(ushort id) /* Uses T from class */

However, from your other sample it looks like you want to use different types - so use a different name for the parameter:

public override TInner Select<TInner>(ushort id)
{
    // UserModel is just a Class where I is an integer typed property
    UserModel.I = 2;
    object result = UserModel.I;

    return (TInner)Convert.ChangeType(result, typeof(TInner));

    throw new NotImplementedException();
}

(In general, try to pick better names than just T or even TInner - just as you should pick good names for other parameters, try to convey the purpose of the type in the type parameter name)


问:
Submit Button is not getting selected..no error also
HTML code:

```<code><button id="welcomeContinue" class="btn btn-primary padlock active-removal" type="submit">
<span class="icon-padlock"></span>
 CONTINUE
</button>
<input class="btn btn-primary padlock disabled" type="hidden" value="" title="Continue" name="continueanonymousSubmit" alt="Continue">
<input type="hidden" value=" " name="_D:continueanonymousSubmit">
</code>```

code:

```<code>driver.findElement(By.id("welcomeContinue")).click();
</code>```

How can i select submit button and proceed to next page

答:
You can try using submit() method on a button instead of clicking.

Also, may be some info should be added for submitting to work: some required fields should be filled. Check this option

There are may be some JS scripts running that prevent submit for working

Body:
HTML code:

<button id="welcomeContinue" class="btn btn-primary padlock active-removal" type="submit">

 CONTINUE
</button>
<input class="btn btn-primary padlock disabled" type="hidden" value="" title="Continue" name="continueanonymousSubmit" alt="Continue">
<input type="hidden" value=" " name="_D:continueanonymousSubmit">

code:

driver.findElement(By.id("welcomeContinue")).click();

How can i select submit button and proceed to next page


问:
Laravel 5.4 detecting variable in developing mode but not in production mode
I am learning laravel and for my practicing purpose I am working on a project. When that app run in local machine it work perfectly but in live server it doesn't. Whats wrong here? I know it's kind of weird but just cant figure it out.

Here is my view

```<code>@foreach($product_details as $product_detail)
    <div data-repeater-item class="mt-repeater-item">
        <div class="mt-repeater-row">
            <div class="col-md-2"></div>
            <div class="col-md-3">
                <label class="control-label">Title</label>
                <input type="hidden" name="indicator_id" value="{{$product_detail->id}}">
                <input name="title" type="text" placeholder="Title" class="form-control" value="{{$product_detail->title}}" /> </div>
            <div class="col-md-6">
                <label class="control-label">Description</label>
                <textarea name="description" type="text" placeholder="Description" class="form-control description content" >{{$product_detail->description}}</textarea> </div>
            <div class="col-md-1">
                <a href="javascript:;" data-repeater-delete class="btn btn-danger mt-repeater-delete">
                    <i class="fa fa-close"></i>
                </a>
            </div>
        </div>
    </div>
@endforeach
</code>```

Here is Controller

```<code>$product_details = IndicatorDetails::where('indicator_id',$id)->get();

return view('admin.indicator.indicator_edit')->with('product_details',$product_details);
</code>```

And Model

```<code>class IndicatorDetails extends Model
{
    protected $fillable = ['title','description','indicator_id'];
    public function indicator()
    {
        return $this->belongsTo(Indicators::class);
    }
}
</code>```

Thanks in advance.

答:
On the live server, you can try do

```<code>php artisan view:clear
</code>```

To clear the view cache.

Also what happened to me before was that every time I deploy to the live server I had to restart php5-fpm.

Body:
I am learning laravel and for my practicing purpose I am working on a project. When that app run in local machine it work perfectly but in live server it doesn't. Whats wrong here? I know it's kind of weird but just cant figure it out.

Here is my view

@foreach($product_details as $product_detail)

                Title
                <input type="hidden" name="indicator_id" value="{{$product_detail->id}}">
                <input name="title" type="text" placeholder="Title" class="form-control" value="{{$product_detail->title}}" />

                Description
                <textarea name="description" type="text" placeholder="Description" class="form-control description content" >{{$product_detail->description}}</textarea>

@endforeach

Here is Controller

$product_details = IndicatorDetails::where('indicator_id',$id)->get();

return view('admin.indicator.indicator_edit')->with('product_details',$product_details);

And Model

class IndicatorDetails extends Model
{
    protected $fillable = ['title','description','indicator_id'];
    public function indicator()
    {
        return $this->belongsTo(Indicators::class);
    }
}

Thanks in advance.

Body:
On the live server, you can try do

php artisan view:clear

To clear the view cache.

Also what happened to me before was that every time I deploy to the live server I had to restart php5-fpm.


问:
How To Register user Form with all dynamic fields name in php
```<code><form method="post">
      User Name : <input type="text" name="values[]"><br/>
      User Mobile: <input type="text" name="values[]"><br/>
      User Email: <input type="text" name="values[]"><br/>
     <input type="submit" name="submit" values="submit">
  </form>
</code>```

My Code/Logic

```<code><?php
    $con=mysql_connect('localhost','root','');
    mysql_query('testing_user',$con);
    if(isset($_POST['submit']))
    {
    $x=$_POST['values'];
    $data_values=array();
    for($i=0;$i<count($x);$i++)
    {
    echo $x[$i]."<br/>";
    array_push($data_values,$x[$i]);
    }
    //print_r($data_values[0]);
    $name=$data_values[0];
    $mobile=$data_values[1];
    $email=$data_values[2];
    mysql_query("insert into user_data values('','$name','$mobile','$email')");

    }
 ?>
</code>```

Check My Logic Please Write New Php Logic to register user record in mysql. i need Your Help !
Thank You

答:
```<code>// Logic One Using For Loop

    <?php
    error_reporting(0);
    $con=mysql_connect('localhost','root','') or die('Not Connect');
    mysql_select_db('multiple',$con);
    if (isset($_POST["submit"])){
    $field_name = $_POST['values'];
    $values = "";
    for ($i = 0; $i < sizeof($field_name); $i++) {
         $values .= "('".$field_name[$i]."')";
       if ($i != sizeof($field_name) - 1) {
           $values .= ", ";
       }
    }
    $sql = mysql_query("INSERT INTO php_test VALUES (" . $values.")");
    }
    }
    ?>

// Logic Two Using Foreach Loop

    <?php
    error_reporting(0);
    $con=mysql_connect('localhost','root','') or die('Not Connect');
    mysql_select_db('multiple',$con);
    if (isset($_POST["submit"])){
    $field_name = $_POST['values'];
    $values = "";
    $i=0;
    foreach($field_name as $searchval) {
      $values.="('".$searchval."')";
      if($i!=sizeof($field_name)-1){
         $values.=", ";
      }
      $i++;
    }
    $query =mysql_query("INSERT INTO php_test VALUES (".$values.")");
    }
    ?>
</code>```

Body:
<form method="post">
      User Name : <input type="text" name="values[]">

      User Mobile: <input type="text" name="values[]">

      User Email: <input type="text" name="values[]">

     <input type="submit" name="submit" values="submit">
  </form>

My Code/Logic

<?php
    $con=mysql_connect('localhost','root','');
    mysql_query('testing_user',$con);
    if(isset($_POST['submit']))
    {
    $x=$_POST['values'];
    $data_values=array();
    for($i=0;$i<count($x);$i++)
    {
    echo $x[$i]."
";
    array_push($data_values,$x[$i]);
    }
    //print_r($data_values[0]);
    $name=$data_values[0];
    $mobile=$data_values[1];
    $email=$data_values[2];
    mysql_query("insert into user_data values('','$name','$mobile','$email')");

    }
 ?>

Check My Logic Please Write New Php Logic to register user record in mysql. i need Your Help !
Thank You


问:
Font and background color not applying to my table
I have a table which I want a black background and white text, some reason it's defaulting to white background and black text. What have I done wrong here?</p>

```<code>#title{
font-family: Arial;
font color:#ffffff
background-color: #000000
}
</code>```

答:
A dash and two semicolons are missing:</p>

```<code>#title{
    font-family: Arial;
    color: #ffffff; // semi-colon here
    background-color: #000000; // semi-colon here
}
</code>```

Body:
I have a table which I want a black background and white text, some reason it's defaulting to white background and black text. What have I done wrong here?

#title{
font-family: Arial;
font color:#ffffff
background-color: #000000
}

Body:
A dash and two semicolons are missing:

#title{
    font-family: Arial;
    color: #ffffff; // semi-colon here
    background-color: #000000; // semi-colon here
}


问:
Php Laravel - How to show xml file in browser
I produced xml file in my directory. I want to show this file in browser using php?

(I want to show that as sitemap)

Here is my code :

```<code>   public function siteMap()
    {
        $test_array = array (
            'bla' => 'blub',
            'foo' => 'bar',
            'another_array' => array (
                'stack' => 'overflow',
            ),
        );

        $xml_template_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");

        $this->array_to_xml($test_array,$xml_template_info);
        $xml_template_info->asXML(dirname(__FILE__)."/sitemap.xml") ;
        header('Content-type: text/xml');
        dd(readfile(dirname(__FILE__)."/sitemap.xml"));
    }

    public function array_to_xml(array $arr, \SimpleXMLElement $xml)
    {
      foreach ($arr as $k => $v) {
          is_array($v)
              ? $this->array_to_xml($v, $xml->addChild($k))
              : $xml->addChild($k, $v);
      }
      return $xml;
   }
</code>```

And here is sitemap.xml:

```<code><?xml version="1.0"?>
<template><bla>blub</bla><foo>bar</foo><another_array><stack>overflow</stack></another_array></template>
</code>```

Here is result :

I want show this xml file in my browser, Any idea for doing this correctly?

EDITED : Here is result with header('Content-type: text/plain');

It consist of some extra reports.

答:
If you want to just show the contents of an xml file in browser same way as they look in xml file,just write name_of_xml_file.xml in url after the base address.

For example:

www.example.com/name_of_xml_file.xml

regardless of where you place it.

It should be in your websites folder and just use a function to redirect to that page if you want to autoload when a certain thing happens.

Body:
I produced xml file in my directory. I want to show this file in browser using php?

(I want to show that as sitemap)

Here is my code :

   public function siteMap()
    {
        $test_array = array (
            'bla' => 'blub',
            'foo' => 'bar',
            'another_array' => array (
                'stack' => 'overflow',
            ),
        );

        $xml_template_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");

        $this->array_to_xml($test_array,$xml_template_info);
        $xml_template_info->asXML(dirname(__FILE__)."/sitemap.xml") ;
        header('Content-type: text/xml');
        dd(readfile(dirname(__FILE__)."/sitemap.xml"));
    }

    public function array_to_xml(array $arr, \SimpleXMLElement $xml)
    {
      foreach ($arr as $k => $v) {
          is_array($v)
              ? $this->array_to_xml($v, $xml->addChild($k))
              : $xml->addChild($k, $v);
      }
      return $xml;
   }

And here is sitemap.xml:

<?xml version="1.0"?>
<template><bla>blub</bla><foo>bar</foo><another_array><stack>overflow</stack></another_array></template>

Here is result :

I want show this xml file in my browser, Any idea for doing this correctly?

EDITED : Here is result with header('Content-type: text/plain');

It consist of some extra reports.


问:
Insert drop caps text in android
I am learning Android and the following is part of an assignment.

I need to write some text in an Android layout with the first letter in drop caps, like the following text:

I looked up the web and did not find many answers. Is there a style option or some property that I could use?

At the moment, I am thinking of the following options. Please suggest what is the best way to do such a thing

Use an image for the first letter

Write the first letter separately in a big font.

Any suggestions would be helpful.

答:
There's a library written by Novoda in which you can add a DropCap https://github.com/novoda/spikes/tree/master/drop-cap
Here's an image from the demo app:

Title: Insert drop caps text in android


问:
Converting string to byte array in C# (CSV)
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

```<code>public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}
</code>```

How could I write a function to convert this string to that byte array again?

答:
I guess that you want to get rid of the ; when converting also. I think you want to do something like this:

```<code>byte[] result = Encoding.UTF8.GetBytes(s.Replace(";",""));
</code>```

This will fail if the original byte array actually contains a ;that is valid data, but in that case you will have lots of problems anyway since your "CSV" file will be wrongly formatted.

Body:
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}

How could I write a function to convert this string to that byte array again?

Body:
I guess that you want to get rid of the ; when converting also. I think you want to do something like this:

byte[] result = Encoding.UTF8.GetBytes(s.Replace(";",""));

This will fail if the original byte array actually contains a ;that is valid data, but in that case you will have lots of problems anyway since your "CSV" file will be wrongly formatted.


问:
Jquery add and remove multiple input count
I am having problems with multiple input count numbers with jQuery. When I read it with barcode, new inputs are formed in the lower and the counter is increasing. But when I remove one of them, the counter does not give the correct number.

I want : when I delete an input, refresh all input counts.

My Fiddle : fiddle

My Code:

$('#giris').keypress(function(e){
  if (e.which == 13) {
  $ney = $(this);
  var neymis = $ney.val();
  if (neymis != '' || neymis != NULL) {
  var wrapper = $('.listele');
  var say = $( "#inputsay input" ).size();
  wrapper.append('
'+say+'	<input class="form-control input-sm duz'+say+' lan" type="text" value="'+neymis+'" name="mlzm[]" id="in_'+say+'" data-id="'+say+'" disabled="true">	<button class="btn btn-primary btn-sm btn-block" id="sil" data-id="'+say+'">Remove</button>
');
  $('#giris').val('');
  $('#say').html(say);
  }
  }
});

$( document ).on( 'click', '#sil', function () {
      var sil_id = $(this).data("id");
      var silinen = $(".duz"+sil_id).val();
      $("#in_"+sil_id).remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inputsay">
<input class="form-control input-lg" type="text" id="giris" placeholder="Seri no.." ng-keydown="keydown($event)">

<div class="table-responsive mb-lg">
  <table class="table table-bordered mb-none">
    <thead>
      <tr>
        <th>#</th>
        <th>Serial Num.</th>
        <th>Delete</th>
      </tr>
    </thead>
    <tbody class="listele"></tbody>
  </table>
</div>
</div></code>```

答:
var say = $( "input" ).size()-2;

//bu şekilde yapacağına inputlara bir class ver

var say = $( ".input_class" ).length

//yaparsan ekleme ve çıkarma da herzaman doğru sonucu alırsın

Body:
I am having problems with multiple input count numbers with jQuery. When I read it with barcode, new inputs are formed in the lower and the counter is increasing. But when I remove one of them, the counter does not give the correct number.

I want : when I delete an input, refresh all input counts.

My Fiddle : fiddle

My Code:

$('#giris').keypress(function(e){
  if (e.which == 13) {
  $ney = $(this);
  var neymis = $ney.val();
  if (neymis != '' || neymis != NULL) {
  var wrapper = $('.listele');
  var say = $( "#inputsay input" ).size();
  wrapper.append('
'+say+'	<input class="form-control input-sm duz'+say+' lan" type="text" value="'+neymis+'" name="mlzm[]" id="in_'+say+'" data-id="'+say+'" disabled="true">	<button class="btn btn-primary btn-sm btn-block" id="sil" data-id="'+say+'">Remove</button>
');
  $('#giris').val('');
  $('#say').html(say);
  }
  }
});

$( document ).on( 'click', '#sil', function () {
      var sil_id = $(this).data("id");
      var silinen = $(".duz"+sil_id).val();
      $("#in_"+sil_id).remove();
});

<input class="form-control input-lg" type="text" id="giris" placeholder="Seri no.." ng-keydown="keydown($event)">

        #
        Serial Num.
        Delete


问:
Lua - understanding setmetatable
I am trying to build a CNN using Torch 7. I am very new to Lua. I was trying to follow this link. I encountered something called setmetatable in the following code block:

```<code>setmetatable(train_set,
{
  __index = function(t, i)
    return {t.data[i], t.label[i]}
  end
});
</code>```

I understand that the second argument acts as the metatable for the table train_set.

1) Is t the metatable or is t just another name for train_set?

2) Whenever a function is used against __index, does the interpreter assume the first argument (t) to be a table (or metatable, depending on answer to first question)? And is the second argument always the key or index?

3) My understanding is that if I use train_set.data[1], it will invoke the __index. The answer here says that __index is invoked when key does not exist in the table. But is t.data[1] same as train_set.data[1]? If so, how does the interpreter know that?

答:
```<code>setmetatable(train_set,
{
  __index = function(t, i)
    return {t.data[i], t.label[i]}
  end
})
</code>```

Here we have some table named train_set. With this function call we set its metatable to

```<code> {
  __index = function(t, i)
      return {t.data[i], t.label[i]}
  end
 }
</code>```

This is an anonymous table. If this is hard to read for you, you could also write:

```<code>local my_metatable = {
  __index = function(t, i)
     return {t.data[i], t.label[i]}
  end
}
setmetatable(train_set, my_metatable)
</code>```

Inside that metatable we implement the metamethod __index. By doing this we tell Lua what to do when someone is indexing a field in train_set that does not exist.

So when we ask Lua to give us the value stored in train_set[4] for example and train_set[4] is nil, Lua will go check if __index is implemented. If so it will call __index(train_set, 4) and give you its return value or otherwise return nil
So the interpreter knows that t.data[1] is the same as train_set.data[1], because he's the one who put train_set into __index.

So when you implement __index it will always be called using the indexed table as first and the index as second argument.

Title: Lua - understanding setmetatable

Body:
I am trying to build a CNN using Torch 7. I am very new to Lua. I was trying to follow this link. I encountered something called setmetatable in the following code block:

setmetatable(train_set,
{
  __index = function(t, i)
    return {t.data[i], t.label[i]}
  end
});

I understand that the second argument acts as the metatable for the table train_set.

1) Is t the metatable or is t just another name for train_set?

2) Whenever a function is used against __index, does the interpreter assume the first argument (t) to be a table (or metatable, depending on answer to first question)? And is the second argument always the key or index?

3) My understanding is that if I use train_set.data[1], it will invoke the __index. The answer here says that __index is invoked when key does not exist in the table. But is t.data[1] same as train_set.data[1]? If so, how does the interpreter know that?

Body:
setmetatable(train_set,
{
  __index = function(t, i)
    return {t.data[i], t.label[i]}
  end
})

Here we have some table named train_set. With this function call we set its metatable to

 {
  __index = function(t, i)
      return {t.data[i], t.label[i]}
  end
 }

This is an anonymous table. If this is hard to read for you, you could also write:

local my_metatable = {
  __index = function(t, i)
     return {t.data[i], t.label[i]}
  end
}
setmetatable(train_set, my_metatable)

Inside that metatable we implement the metamethod __index. By doing this we tell Lua what to do when someone is indexing a field in train_set that does not exist.

So when we ask Lua to give us the value stored in train_set[4] for example and train_set[4] is nil, Lua will go check if __index is implemented. If so it will call __index(train_set, 4) and give you its return value or otherwise return nil
So the interpreter knows that t.data[1] is the same as train_set.data[1], because he's the one who put train_set into __index.

So when you implement __index it will always be called using the indexed table as first and the index as second argument.


问:
favicon.ico won't show up in Rails 4
I have a 16x16 favicon.ico in app/assets/images. When I run

rake assets:clean

and then

rake assets:precompile

I can see that two fingerprinted files; favicon.ico and favicon.ico.gz, are generated in public/assets, as they should, because I am using the asset pipeline.

My application.html.haml contains this line, in the %head section:

```<code>= favicon_link_tag
</code>```

However, no GET requests for favicon.ico appear in the terminal where

rails server

is running. Also, no html for favicon appears on my page when I type 'Ctrl U' to view the page source.

I have tried to put favicon.ico in public/img, and to have it in both locations. I have tried various syntaxes for the line in application.html.haml, such as:

```<code>= favicon_link_tag "favicon.ico"

= favicon_link_tag "app/assets/images/favicon.ico"

%link{:href => "favicon.ico", :type => "image/x-icon"}
</code>```

and so on. Flushing the browser cache is not relevant, since no GET request is made. I have deleted all favicons from the codebase, and put in new ones in various locations. What am I missing?

答:
It turned out the people who were working on this rails app before me had added landing.html.haml, where I needed to put the favicon_link_tag. It had no effect in application.html.haml.

I also had to run

rake assets:clobber

in order for the rails cache to be flushed, and the favicon.ico to get noticed.

I had been running

rake assets:clean

which is for Rails 3, and doesn't do what I expect it to in Rails 4.

Title: favicon.ico won't show up in Rails 4

Body:
I have a 16x16 favicon.ico in app/assets/images. When I run

rake assets:clean

and then

rake assets:precompile

I can see that two fingerprinted files; favicon.ico and favicon.ico.gz, are generated in public/assets, as they should, because I am using the asset pipeline.

My application.html.haml contains this line, in the %head section:

= favicon_link_tag

However, no GET requests for favicon.ico appear in the terminal where

rails server

is running. Also, no html for favicon appears on my page when I type 'Ctrl U' to view the page source.

I have tried to put favicon.ico in public/img, and to have it in both locations. I have tried various syntaxes for the line in application.html.haml, such as:

= favicon_link_tag "favicon.ico"

= favicon_link_tag "app/assets/images/favicon.ico"

%link{:href => "favicon.ico", :type => "image/x-icon"}

and so on. Flushing the browser cache is not relevant, since no GET request is made. I have deleted all favicons from the codebase, and put in new ones in various locations. What am I missing?


问:
PayPal Express Checkout, error when supplying input_fields
I'm using PayPal Express Checkout from JavaScript.

This is the code I have and works (I see the PayPal button, I can click it, and the payment window opens fine):

```<code><div id="paypal-button"></div>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
        paypal.Button.render({

            env: 'sandbox',

            client: {
                sandbox: 'xxxxxx',
                production: 'yyyyyy'
            },

            payment: function () {

                var env = this.props.env;
                var client = this.props.client;

                return paypal.rest.payment.create(env, client, {
                    transactions: [
                        {
                            amount: { total: '1.00', currency: 'USD' }
                        }
                    ]

                });
            },

            commit: true,

            onAuthorize: function (data, actions) {

                return actions.payment.execute().then(function() {
                    document.querySelector('#paypal-button-container').innerText = 'Payment Complete!';
                });
            }

        }, '#paypal-button');

</script>
</code>```

But, if I supply input_fields like the code below, it stops working and throws a console error:

```<code>        paypal.Button.render({

            env: 'sandbox',

            client: {
                sandbox: 'xxxxxx',
                production: 'yyyyyy'
            },

            payment: function () {

                var env = this.props.env;
                var client = this.props.client;

                return paypal.rest.payment.create(env, client, {
                    transactions: [
                        {
                            amount: { total: '1.00', currency: 'USD' }
                        }
                    ]

                }, {
                    input_fields: {
                        no_shipping: 1
                    }
                });
            },

            commit: true,

            onAuthorize: function (data, actions) {
                return actions.payment.execute().then(function() {
                    document.querySelector('#paypal-button-container').innerText = 'Payment Complete!';
                });
            }

        }, '#paypal-button');
</code>```

This is the error detail:

In this last case, I see the PayPal button, the window opens when I click on it, but after a few seconds the window closes itself and gives the console error provided here.

What am I missing?

UPDATE

As @bluepnume pointed out, if I switch from sandbox to production environment, the problem disappears.

But, if I also supply first_name and last_name in input_fields, I get another console error no matter if I'm in sandbox or production environment.

This is the code snippet:

```<code>, {
      input_fields: {
          no_shipping: 1,
          first_name: 'Abc',
          last_name: 'Dfg'
      }
 }
</code>```

And this is the error message:

答:
This is a known issue that's being tracked. For what it's worth, if you run in production mode, the issue should not be present.

EDIT: For the second issue, looks like this is not a valid request format. You should be able to see in your network tab:

Are you looking for the payer_info field for the payments api? https://developer.paypal.com/docs/api/payments/

Body:
I'm using PayPal Express Checkout from JavaScript.

This is the code I have and works (I see the PayPal button, I can click it, and the payment window opens fine):

But, if I supply input_fields like the code below, it stops working and throws a console error:

        paypal.Button.render({

            env: 'sandbox',

            client: {
                sandbox: 'xxxxxx',
                production: 'yyyyyy'
            },

            payment: function () {

                var env = this.props.env;
                var client = this.props.client;

                return paypal.rest.payment.create(env, client, {
                    transactions: [
                        {
                            amount: { total: '1.00', currency: 'USD' }
                        }
                    ]

                }, {
                    input_fields: {
                        no_shipping: 1
                    }
                });
            },

            commit: true,

            onAuthorize: function (data, actions) {
                return actions.payment.execute().then(function() {
                    document.querySelector('#paypal-button-container').innerText = 'Payment Complete!';
                });
            }

        }, '#paypal-button');

This is the error detail:

In this last case, I see the PayPal button, the window opens when I click on it, but after a few seconds the window closes itself and gives the console error provided here.

What am I missing?

UPDATE

As @bluepnume pointed out, if I switch from sandbox to production environment, the problem disappears.

But, if I also supply first_name and last_name in input_fields, I get another console error no matter if I'm in sandbox or production environment.

This is the code snippet:

, {
      input_fields: {
          no_shipping: 1,
          first_name: 'Abc',
          last_name: 'Dfg'
      }
 }

And this is the error message:


问:
SQL Duplicates remove
I've a problem of duplicates in tsql. How can I remove?
This is my output:

```<code>  id          name       ref
----------- ---------- --------------
1           John       null
1           John       RE
2           Smith      null
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null
</code>```

Code:

```<code> SELECT DISTINCT
    u.id,
    u.name,
    c.ref
    FROM users u
    LEFT JOIN con c on c.id=u.id
</code>```

I would like the output to be like this:

```<code>  id          name       ref
----------- ---------- --------------
1           John       RE
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null
</code>```

This is just an example, I've few of them.

thanks

答:
Try below query, this will give you the exact required output:

```<code>DECLARE @SAMPLEDATA TABLE(id INT,        name VARCHAR(100),      ref VARCHAR(100))
INSERT INTO @SAMPLEDATA VALUES
(1,           'John',       null),
(1,           'John',       'RE'),
(2,           'Smith',      null),
(2,           'Smith',      'DOS'),
(3,          'Van',        null),
(4,           'Sam',        'CR'),
(5,           'Bob',        null)
 ;WITH SAMPLEDATA
 AS
 (
 SELECT ROW_NUMBER()OVER (ORDER BY (SELECT 100))SNO,* FROM @SAMPLEDATA
 )
 SELECT ID,NAME,REF FROM(
 SELECT * ,ISNULL((SELECT CASE WHEN T2.ID=T1.id AND T1.ref IS NULL THEN 'R'     ELSE 'NR' END
 FROM SAMPLEDATA T2 WHERE T2.SNO=T1.SNO+1),'NR')COL FROM SAMPLEDATA T1) DATA     WHERE COL='NR'
</code>```

OUTPUT

```<code>------------------
ID  NAME    REF
------------------
1   John    RE
2   Smith   DOS
3   Van     NULL
4   Sam     CR
5   Bob     NULL
------------------
</code>```

Title: SQL Duplicates remove

Body:
I've a problem of duplicates in tsql. How can I remove?
This is my output:

  id          name       ref
----------- ---------- --------------
1           John       null
1           John       RE
2           Smith      null
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null

Code:

 SELECT DISTINCT
    u.id,
    u.name,
    c.ref
    FROM users u
    LEFT JOIN con c on c.id=u.id

I would like the output to be like this:

  id          name       ref
----------- ---------- --------------
1           John       RE
2           Smith      DOS
3           Van        null
4           Sam        CR
5           Bob        null

This is just an example, I've few of them.

thanks

Body:
Try below query, this will give you the exact required output:

DECLARE @SAMPLEDATA TABLE(id INT,        name VARCHAR(100),      ref VARCHAR(100))
INSERT INTO @SAMPLEDATA VALUES
(1,           'John',       null),
(1,           'John',       'RE'),
(2,           'Smith',      null),
(2,           'Smith',      'DOS'),
(3,          'Van',        null),
(4,           'Sam',        'CR'),
(5,           'Bob',        null)
 ;WITH SAMPLEDATA
 AS
 (
 SELECT ROW_NUMBER()OVER (ORDER BY (SELECT 100))SNO,* FROM @SAMPLEDATA
 )
 SELECT ID,NAME,REF FROM(
 SELECT * ,ISNULL((SELECT CASE WHEN T2.ID=T1.id AND T1.ref IS NULL THEN 'R'     ELSE 'NR' END
 FROM SAMPLEDATA T2 WHERE T2.SNO=T1.SNO+1),'NR')COL FROM SAMPLEDATA T1) DATA     WHERE COL='NR'

OUTPUT

------------------
ID  NAME    REF
------------------
1   John    RE
2   Smith   DOS
3   Van     NULL
4   Sam     CR
5   Bob     NULL
------------------


问:
Any better approach for layout design?
just wondering if anyone else has a better suggestion that what I'm coming up with.

The issue is to do with a TabLayout, 5 Tabs all using a single Activity.  Each Tab layout contains quite a few fields so the main parent on each tab is a ScrollView.

What I currently have is a 'Save' & 'Cancel' button sitting outside the scrollviews so theyre always visible and there for the user regardless which tab they're on.  The problem is that since I'm using Tabs and always have these buttons visible when they are editing and the IME is displayed, they'res barely any of the form visible.

So I think the best thing for me to do is to probably show the buttons at the end of each scrollview.  What I don't like about this is as I have 5 tabs, it will mean I have to declare 5 sets of the buttons, and of course define them and bind them in the Activity.. which seems rather messy and inefficient.

So if anyone has any better ideas I sure would love to hear them :-)

Thanks

Rgds,

Dave

答: You could make it that when you're in tab X, the tab button for tab X now becomes X(save), so if they click again on the tab button in the same tab, it saves.  That saves you five buttons, potentially...</p>

Title: Any better approach for layout design?


问:
Convert ascii to hex in Python 3
I try to convert ascii to hex value. But my script sometimes working, sometimes does not work. I wonder why. Code likes below:

ascii_ch = B13515068

```<code>for i in range(50):  #In excel I have 50 row
    ascii_ch = sheet['C%s'%(i+2)].value  #after C2, convert hex
    ascii_to_hex= "".join("{:02x}".format(ord(c)) for c in ascii_ch )
    sheet['I%s'%(i+2)] = ascii_to_hex
    wb.save('a.xlsx')
</code>```

I want to ascii_to_hex= 423133353135303638

Sometimes code works properly, but Generally I get an error like below;

答:
It looks like not all cells actually have values associated with them. When a cell has no value, ascii_ch = sheet['C%s'%(i+2)].value will set ascii_ch to None. In the next line, you iterate over ascii_ch. But it does not make any sense to iterate over None!

You probably want to check for that, like this:

```<code>for i in range(50):  #In excel I have 50 row
    ascii_ch = sheet['C%s'%(i+2)].value  #after C2, convert hex
    if ascii_ch is None:
        # Maybe warn the user that a value is missing?
        continue  # go on to the next cell
</code>```

Title: Convert ascii to hex in Python 3

Body:
I try to convert ascii to hex value. But my script sometimes working, sometimes does not work. I wonder why. Code likes below:

ascii_ch = B13515068

for i in range(50):  #In excel I have 50 row
    ascii_ch = sheet['C%s'%(i+2)].value  #after C2, convert hex
    ascii_to_hex= "".join("{:02x}".format(ord(c)) for c in ascii_ch )
    sheet['I%s'%(i+2)] = ascii_to_hex
    wb.save('a.xlsx')

I want to ascii_to_hex= 423133353135303638

Sometimes code works properly, but Generally I get an error like below;

Body:
It looks like not all cells actually have values associated with them. When a cell has no value, ascii_ch = sheet['C%s'%(i+2)].value will set ascii_ch to None. In the next line, you iterate over ascii_ch. But it does not make any sense to iterate over None!

You probably want to check for that, like this:

for i in range(50):  #In excel I have 50 row
    ascii_ch = sheet['C%s'%(i+2)].value  #after C2, convert hex
    if ascii_ch is None:
        # Maybe warn the user that a value is missing?
        continue  # go on to the next cell


问:
Silex with Doctrine and PHP classes
So, I'm trying to get around in Silex. Just learn the way it works and I'm trying to use Doctrine in it. I can use it on the index.php, but I'd also like to use it in my classes. These lines are used in the normal root file (index.php):

```<code>$images = $app['db']->prepare("SELECT * FROM images");
$images->execute();

$images = $images->fetchAll(\PDO::FETCH_CLASS, \AI\Models\Image::class);
</code>```

So that would give me the ability to do something with the images. But I don't want to work this way. I'd like classes to do it all for me, so that I just script some methods which do all the hard work for me. That would let me just run one line for each Route in index.php

The problem is that I don't know how to connect with Doctrine from inside my classes. Because there is no '$app' in there. I think it would be weird to start the app inside of a class.

So let's say I wanted to create a user class. This SQL would give me all the users: "SELECT * FROM users". But how would I use Doctrine inside the User class?

```<code><?php

namespace Models;

class User {

    public function find($user){
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';

            $sql = "SELECT * FROM users";

            $data = // RUN QUERY $SQL
            if($data->count()) {
                $this->_data = $data->all();
                return true;
            }
        }
        return false;
    }

}
</code>```

答:
You would need to inject those instances in your controller.
I looked through the docs real quick and think I found what you need.

Here is a link to the documentation page : http://silex.sensiolabs.org/doc/2.0/providers/service_controller.html.

the documentation page explains everything you need to know to get what you want to achieve.

Title: Silex with Doctrine and PHP classes

Body:
So, I'm trying to get around in Silex. Just learn the way it works and I'm trying to use Doctrine in it. I can use it on the index.php, but I'd also like to use it in my classes. These lines are used in the normal root file (index.php):

$images = $app['db']->prepare("SELECT * FROM images");
$images->execute();

$images = $images->fetchAll(\PDO::FETCH_CLASS, \AI\Models\Image::class);

So that would give me the ability to do something with the images. But I don't want to work this way. I'd like classes to do it all for me, so that I just script some methods which do all the hard work for me. That would let me just run one line for each Route in index.php

The problem is that I don't know how to connect with Doctrine from inside my classes. Because there is no '$app' in there. I think it would be weird to start the app inside of a class.

So let's say I wanted to create a user class. This SQL would give me all the users: "SELECT * FROM users". But how would I use Doctrine inside the User class?

<?php

namespace Models;

class User {

    public function find($user){
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';

            $sql = "SELECT * FROM users";

            $data = // RUN QUERY $SQL
            if($data->count()) {
                $this->_data = $data->all();
                return true;
            }
        }
        return false;
    }

}