问:
In Python, is there an elegant way to print a list in a custom format without explicit looping?
I know you can do

```<code>print str(myList)
</code>```

to get

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

and you can do

```<code>i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1
</code>```

to get

```<code>0: 1
1: 2
2: 3
</code>```

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

```<code>print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])
</code>```

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

Body:
I know you can do

print str(myList)

to get

[1, 2, 3]

and you can do

i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1

to get

0: 1
1: 2
2: 3

But is there a way similar to the first to get a result similar to the last?

With my limited knowledge of Python (and some help from the documentation), my best is:

print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])

It's not much less verbose, but at least I get a custom string in one (compound) statement.
Can you do better?

Body:
l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])


来源: stackexchange

问:
How to put Wordpress into a subfolder and redirect all specific traffic to it?
I have a website in main folder with urls like:

domain.com/article/one etc.

Also i would like to install Wordpress into folder:

wordpress

But i would like urls to be NOT:

domain.com/wordpress/post/....

But:

domain.com/post/...

I would like to handle with .htaccess or index.php all requests to Wordpress so they are redirected to proper place in wordpress folder, so the main application will be intact.

How to make sure my basic app and wordpress will work together nicely?

答:
change wp-options table value of home url and site url

```<code>what you want like abc.com

and move your content to main directory where you want like public_html/
</code>```

ContentLicense: CC BY-SA 3.0

Body:
change wp-options table value of home url and site url

what you want like abc.com

and move your content to main directory where you want like public_html/


问:
Multiple force-directed graphs in 1 svg (problems with text display)
I want to display multiple force directed graphs. Preferably with only using 1 svg element as well (as I think that increases performance as well as let me make a width and height for whole simulation as this may differ based on data).

My first thought and with some research I just did a for loop, re-evaluated my nodes/edges arrays and put that in a function that generates the force-directed graph.

```<code> for (var i = 0; i < sampleData.length; i++)
{
            var nodes = [];
    var edges = [];

            x = x+100; //update position (i want to show grpahs side by side.)

    root = sampleData[i];

    nodes.push({"name": root, "x": x, "y": y, "fixed": true, "color": "purple"});

        //These 2 recurisve functions generate my nodes and edges array just fine.
     buildParents(childs, parents, test, counter);
     buildChildren(childs, parents, test, counter);

     //apply id to each node
        nodes.forEach((d,i)=>d.generatedId='id'+i);

            //build makes the force-directed layout.
        build(nodes, edges);

}
</code>```

This actually appears to work fine for me with my nodes and links. My issue is the text does not display for all nodes like it does if I only pass in one set of data. I have text defined as so in the force simulation:

```<code>var nodes_text = svg.selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text")
        .attr("class", "nodetext slds-text-heading--label")
        .attr("text-anchor", "middle")
        .attr("dx", -20)
        .attr("dy", 20)
        .text(d=>d.name)
        .attr('opacity',0)
</code>```

I was able to reproduce this error by just making 2 arrays for nodes and 2 arrays for edges and passing it into a simulation. Here is a simple program that reproduces my error:
https://jsfiddle.net/mg8b46aj/9/

I think fixing this JFiddle would give me the right idea on how to put it in my program.

So I just call the build function twice (either order is error). The left node has text but one of them isn't the correct text field. Also dragging it around a little bit makes it "leave" its text behind. The right graph has nothing.

Edit: And clicking the a node on the right graph seems to reset the text positions.

答:
The problem is with the d3 selector use for selecting labels. As you need two separate force layout diagrams, you should use a selector as shown below for labels.

```<code>var nodes_text = svg.append('g') //Append new group for labels in new diagram
        .attr("class", "labels")
        .selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text");
</code>```

Updated Fiddle: https://jsfiddle.net/gilsha/qe7bbnwn/1/

Body:
I want to display multiple force directed graphs. Preferably with only using 1 svg element as well (as I think that increases performance as well as let me make a width and height for whole simulation as this may differ based on data).

My first thought and with some research I just did a for loop, re-evaluated my nodes/edges arrays and put that in a function that generates the force-directed graph.

 for (var i = 0; i < sampleData.length; i++)
{
            var nodes = [];
    var edges = [];

            x = x+100; //update position (i want to show grpahs side by side.)

    root = sampleData[i];

    nodes.push({"name": root, "x": x, "y": y, "fixed": true, "color": "purple"});

        //These 2 recurisve functions generate my nodes and edges array just fine.
     buildParents(childs, parents, test, counter);
     buildChildren(childs, parents, test, counter);

     //apply id to each node
        nodes.forEach((d,i)=>d.generatedId='id'+i);

            //build makes the force-directed layout.
        build(nodes, edges);

}

This actually appears to work fine for me with my nodes and links. My issue is the text does not display for all nodes like it does if I only pass in one set of data. I have text defined as so in the force simulation:

var nodes_text = svg.selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text")
        .attr("class", "nodetext slds-text-heading--label")
        .attr("text-anchor", "middle")
        .attr("dx", -20)
        .attr("dy", 20)
        .text(d=>d.name)
        .attr('opacity',0)

I was able to reproduce this error by just making 2 arrays for nodes and 2 arrays for edges and passing it into a simulation. Here is a simple program that reproduces my error:
https://jsfiddle.net/mg8b46aj/9/

I think fixing this JFiddle would give me the right idea on how to put it in my program.

So I just call the build function twice (either order is error). The left node has text but one of them isn't the correct text field. Also dragging it around a little bit makes it "leave" its text behind. The right graph has nothing.

Edit: And clicking the a node on the right graph seems to reset the text positions.

Body:
The problem is with the d3 selector use for selecting labels. As you need two separate force layout diagrams, you should use a selector as shown below for labels.

var nodes_text = svg.append('g') //Append new group for labels in new diagram
        .attr("class", "labels")
        .selectAll(".nodetext")
        .data(nodes)
        .enter()
        .append("text");

Updated Fiddle: https://jsfiddle.net/gilsha/qe7bbnwn/1/


问:
Ionic Cordova Linking to internal views (pages)
I have an Ionic project. On my home page I want to link to another internal view (page). Specifically when the user clicks an image I want it to navigate to the pray.html page.

Here is my code:

```<code><div style="margin-left: -10px; width: calc(100% + 20px);">
      <a style="display:block;" href="#PrayPage">
        <img src="../assets/img/praycomplinebutton.png" style="display: block; width: 100%; margin-left: auto; margin-right: auto;">
      </a>
    </div>
</code>```

Currently when I try this I get the following error:

```<code>Runtime Error:
Uncaught (in promise): invalid views to insert

Stack:
c@http://localhost:8100/build/polyfills.js:3:13199
http://localhost:8100/build/polyfills.js:3:12547
_fireError@http://localhost:8100/build/main.js:43691:22
_failed@http://localhost:8100/build/main.js:43679:24
onInvoke@http://localhost:8100/build/main.js:4480:43
run@http://localhost:8100/build/polyfills.js:3:4146
http://localhost:8100/build/polyfills.js:3:13734
onInvokeTask@http://localhost:8100/build/main.js:4471:47
runTask@http://localhost:8100/build/polyfills.js:3:4841
o@http://localhost:8100/build/polyfills.js:3:1898
invoke@http://localhost:8100/build/polyfills.js:3:10674
</code>```

I know this can be done.. I just can't find any documentation on how to do it. I'd appreciate any guidance you can provide.

答: Assuming you are using ionic3. You can go through ionic navigation tutorial to understand the pages linking.</p>

Body:
I have an Ionic project. On my home page I want to link to another internal view (page). Specifically when the user clicks an image I want it to navigate to the pray.html page.

Here is my code:

Currently when I try this I get the following error:

Runtime Error:
Uncaught (in promise): invalid views to insert

Stack:
c@http://localhost:8100/build/polyfills.js:3:13199
http://localhost:8100/build/polyfills.js:3:12547
_fireError@http://localhost:8100/build/main.js:43691:22
_failed@http://localhost:8100/build/main.js:43679:24
onInvoke@http://localhost:8100/build/main.js:4480:43
run@http://localhost:8100/build/polyfills.js:3:4146
http://localhost:8100/build/polyfills.js:3:13734
onInvokeTask@http://localhost:8100/build/main.js:4471:47
runTask@http://localhost:8100/build/polyfills.js:3:4841
o@http://localhost:8100/build/polyfills.js:3:1898
invoke@http://localhost:8100/build/polyfills.js:3:10674

I know this can be done.. I just can't find any documentation on how to do it. I'd appreciate any guidance you can provide.


问:
How to get Time offset (diffrence) b/w time.strftime and datetime.datetime?
I am getting time input in unix (milliseconds) and want to get time difference b/w given value and current time for that I did following. 1st convert posix into human readable then tried to minus 2 values but - doesn't go well with str.

```<code>/1000 is for millisecond reduction

t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1496814300000/1000))
k = datetime.datetime.now()

j = k -t
print j
</code>```

答:
Try turning your timestamp into a datetime object directly:</p>

```<code>import datetime
t = datetime.datetime.fromtimestamp(1496814300000/1000)
k = datetime.datetime.now()

j = k - t
print(j)
</code>```

Body:
I am getting time input in unix (milliseconds) and want to get time difference b/w given value and current time for that I did following. 1st convert posix into human readable then tried to minus 2 values but - doesn't go well with str.

/1000 is for millisecond reduction

t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1496814300000/1000))
k = datetime.datetime.now()

j = k -t
print j

Body:
Try turning your timestamp into a datetime object directly:

import datetime
t = datetime.datetime.fromtimestamp(1496814300000/1000)
k = datetime.datetime.now()

j = k - t
print(j)


问:
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail"
TL;DR: I am getting this error and don't know why:

django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field.

I am going through the django-rest-framework tutorial and am currently at a point where function based views (FBV) were switched to class, mixin, and generic based views (CBV, MBV, GBV respectively). After switching to GBV, when I went to test my API, I received this error AssertionError: Expected view SnippetDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the '.lookup_field' attribute on the view correctly.. I did some research and found that lookup_field needs to be set to the in the urlpatterns. Currently, my urls.py look like this:

```<code>from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

# API endpoints
urlpatterns = format_suffix_patterns([
    url(r'^$', views.api_root),
    url(r'^snippets/$',
        views.SnippetList.as_view(),
        name='snippet-list'),
    url(r'^snippets/(?P<id>[0-9]+)/$',
        views.SnippetDetail.as_view(),
        name='snippet-detail'),
    url(r'^users/$',
        views.UserList.as_view(),
        name='user-list'),
    url(r'^users/(?P<id>[0-9]+)/$',
        views.UserDetail.as_view(),
        name='user-detail')
])

# Login and logout views for the browsable API
urlpatterns += [
    url(r'^auth/', include('rest_framework.urls',
                           namespace='rest_framework')),
]
</code>```

and my views.py look like so:

```<code>from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from snippets.permissions import IsOwnerOrReadOnly

from rest_framework import generics
from rest_framework import permissions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse

from django.contrib.auth.models import User

@api_view(['GET'])
def api_root(request, format=None):
    return Response({
        'users': reverse('user-list', request=request, format=format),
        'snippets': reverse('snippet-list', request=request, format=format)
    })

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )
</code>```

when I add lookup_field = 'id' in both UserDetail and SnippetDetail, the exception resolves itself. (Yay!). But, when I visit http://127.0.0.1/users/1/ ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field. is thrown. When I check the console, however, there is a second exception:

django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with
  arguments '()' and keyword arguments '{'pk': 1}' not found. 2
  pattern(s) tried: ['users/(?P[0-9]+)\.(?P[a-z0-9]+)/?$',
  'users/(?P[0-9]+)/$']

During handling of the above exception, another exception occurred:

django.core.exceptions.ImproperlyConfigured: Could not resolve URL for
  hyperlinked relationship using view name "user-detail". You may have
  failed to include the related model in your API, or incorrectly
  configured the 'lookup_field' attribute on this field.

What I find interesting is that the kwargs for the first exception is {'pk': 1}, not {'id':1}. After some help from chat, someone pointed me to this piece of information:

Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.

This is useful as User serializer extends HyperlinkedModelSerializer:

```<code>from rest_framework import serializers

from django.contrib.auth.models import User

from snippets.models import Snippet

class UserSerializer(serializers.HyperlinkedModelSerializer):
    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)

    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'snippets')
</code>```

the User model and serializer has a reverse relationship with Snippet. Now, when I add lookup_field='id' to snippets attribute of UserSerializer (snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True, lookup_field='id')), like it asks me to do so here, the error is persistent.

What am I doing incorrectly? What can I do to fix this? Is it not having anything to do with lookup_id?

I understand that I could replace <id> with <pk> in my urlpatterns, but I would like to understand why this is happening.

答:
I just had the same problem and I found, that the HyperlinkedIdentityField wants to insert some placeholder into your URL. But I had used URLs which did not require any placeholders to be set. A ListCreateAPIView to be precise:

```<code>url(
    r'^users/$',                  #<-- takes no params
    views.UserListView.as_view(), #<-- just prints a list
    name="user-list"              #<-- HyperlinkedIdentityField pointing
),                                #     here complained bitterly.
</code>```

Body:
TL;DR: I am getting this error and don't know why:

django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field.

I am going through the django-rest-framework tutorial and am currently at a point where function based views (FBV) were switched to class, mixin, and generic based views (CBV, MBV, GBV respectively). After switching to GBV, when I went to test my API, I received this error AssertionError: Expected view SnippetDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the '.lookup_field' attribute on the view correctly.. I did some research and found that lookup_field needs to be set to the in the urlpatterns. Currently, my urls.py look like this:

from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

# API endpoints
urlpatterns = format_suffix_patterns([
    url(r'^$', views.api_root),
    url(r'^snippets/$',
        views.SnippetList.as_view(),
        name='snippet-list'),
    url(r'^snippets/(?P<id>[0-9]+)/$',
        views.SnippetDetail.as_view(),
        name='snippet-detail'),
    url(r'^users/$',
        views.UserList.as_view(),
        name='user-list'),
    url(r'^users/(?P<id>[0-9]+)/$',
        views.UserDetail.as_view(),
        name='user-detail')
])

# Login and logout views for the browsable API
urlpatterns += [
    url(r'^auth/', include('rest_framework.urls',
                           namespace='rest_framework')),
]

and my views.py look like so:

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from snippets.permissions import IsOwnerOrReadOnly

from rest_framework import generics
from rest_framework import permissions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse

from django.contrib.auth.models import User

@api_view(['GET'])
def api_root(request, format=None):
    return Response({
        'users': reverse('user-list', request=request, format=format),
        'snippets': reverse('snippet-list', request=request, format=format)
    })

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class SnippetList(generics.ListCreateAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )

when I add lookup_field = 'id' in both UserDetail and SnippetDetail, the exception resolves itself. (Yay!). But, when I visit http://127.0.0.1/users/1/ ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field. is thrown. When I check the console, however, there is a second exception:

django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with
  arguments '()' and keyword arguments '{'pk': 1}' not found. 2
  pattern(s) tried: ['users/(?P[0-9]+)\.(?P[a-z0-9]+)/?$',
  'users/(?P[0-9]+)/$']

During handling of the above exception, another exception occurred:

django.core.exceptions.ImproperlyConfigured: Could not resolve URL for
  hyperlinked relationship using view name "user-detail". You may have
  failed to include the related model in your API, or incorrectly
  configured the 'lookup_field' attribute on this field.

What I find interesting is that the kwargs for the first exception is {'pk': 1}, not {'id':1}. After some help from chat, someone pointed me to this piece of information:

Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.

This is useful as User serializer extends HyperlinkedModelSerializer:

from rest_framework import serializers

from django.contrib.auth.models import User

from snippets.models import Snippet

class UserSerializer(serializers.HyperlinkedModelSerializer):
    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)

    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'snippets')

the User model and serializer has a reverse relationship with Snippet. Now, when I add lookup_field='id' to snippets attribute of UserSerializer (snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True, lookup_field='id')), like it asks me to do so here, the error is persistent.

What am I doing incorrectly? What can I do to fix this? Is it not having anything to do with lookup_id?

I understand that I could replace <id> with <pk> in my urlpatterns, but I would like to understand why this is happening.

Body:
I just had the same problem and I found, that the HyperlinkedIdentityField wants to insert some placeholder into your URL. But I had used URLs which did not require any placeholders to be set. A ListCreateAPIView to be precise:

url(
    r'^users/$',                  #<-- takes no params
    views.UserListView.as_view(), #<-- just prints a list
    name="user-list"              #<-- HyperlinkedIdentityField pointing
),                                #     here complained bitterly.


问:
How to loop indices of .formula/.formulaR1C1
I am stuck with a problem i cannot get my head around currently.

I have a checklist that has to update automatically when adding lines to my excel worksheet so that the checklist is applied to all rows.
I tried to use a "for loop" to modify the formula but excel returns Error 1004, when starting the string with "=".

No error but no functionality as well:

```<code> ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "Wenn(Oder(AB" & firstRow & "=""x"""
</code>```

Returns error 1004:

```<code> ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "=Wenn(Oder(AB" & firstRow & "=""x"""
</code>```

My first solution
Loop FormulaR1C1, or Formula and use nothing but english Function names eg. sum() instead of Summe() and follow english syntax , instead of ;.

Problem
When testing the syntax without a loop and actual indices it works like a charm. As soon as I try to loop it, Excel does not recognize R[i]C as cell anymore but just returns plain text.

no issues:

```<code>ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[1]C = ""x"""
</code>```

issues:

```<code>ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[i]C = ""x"""
</code>```

Splitting it like this did not solve my problem either
    ..R[" & i & "]C =..

Any tips?

// For i=  ... to .. next i
// Excel 2007

答:
Here's the code. It has to be in the corresponding worksheet in the VBA-Editor.
It activates when a cell in Range(A10:A20) has been changed.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("A10:A20")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
        If Target.Count = 1 Then
            If Target.Value = "x" Then
                'Your Code
                'i.e
                MsgBox (Target.Address & "has been changed")
            End If
        Else
            MsgBox ("Please No Copy Pasterino")
        End If
    End If
End Sub
</code>```

EDIT:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Dim i As Integer
Dim fRow As Long, lRow As Long
Dim check As Boolean
Dim sht As Worksheet
Dim Cell As Range

Set sht = Worksheets("Tabelle1")

'Rowcount
fRow = 2
lRow = sht.Cells(sht.Rows.Count, "G").End(xlUp).Row

' check column AB fo "x" and modify header
Set KeyCells = Range("AB" & fRow & ":AI" & lRow)
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
       Is Nothing Then
         For Each Cell In Range(Cells(fRow, Target.Column), Cells(lRow, Target.Column))
            If Cell.Value = "x" Then
                sht.Cells(9, Target.Column).Value = "x"
                Exit For
            Else
                sht.Cells(9, Target.Column).Value = ""
            End If
         Next
End If
End Sub
</code>```

Body:
I am stuck with a problem i cannot get my head around currently.

I have a checklist that has to update automatically when adding lines to my excel worksheet so that the checklist is applied to all rows.
I tried to use a "for loop" to modify the formula but excel returns Error 1004, when starting the string with "=".

No error but no functionality as well:

 ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "Wenn(Oder(AB" & firstRow & "=""x"""

Returns error 1004:

 ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "=Wenn(Oder(AB" & firstRow & "=""x"""

My first solution
Loop FormulaR1C1, or Formula and use nothing but english Function names eg. sum() instead of Summe() and follow english syntax , instead of ;.

Problem
When testing the syntax without a loop and actual indices it works like a charm. As soon as I try to loop it, Excel does not recognize R[i]C as cell anymore but just returns plain text.

no issues:

ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[1]C = ""x"""

issues:

ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[i]C = ""x"""

Splitting it like this did not solve my problem either
    ..R[" & i & "]C =..

Any tips?

// For i=  ... to .. next i
// Excel 2007

Body:
Here's the code. It has to be in the corresponding worksheet in the VBA-Editor.
It activates when a cell in Range(A10:A20) has been changed.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("A10:A20")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
        If Target.Count = 1 Then
            If Target.Value = "x" Then
                'Your Code
                'i.e
                MsgBox (Target.Address & "has been changed")
            End If
        Else
            MsgBox ("Please No Copy Pasterino")
        End If
    End If
End Sub

EDIT:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Dim i As Integer
Dim fRow As Long, lRow As Long
Dim check As Boolean
Dim sht As Worksheet
Dim Cell As Range

Set sht = Worksheets("Tabelle1")

'Rowcount
fRow = 2
lRow = sht.Cells(sht.Rows.Count, "G").End(xlUp).Row

' check column AB fo "x" and modify header
Set KeyCells = Range("AB" & fRow & ":AI" & lRow)
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
       Is Nothing Then
         For Each Cell In Range(Cells(fRow, Target.Column), Cells(lRow, Target.Column))
            If Cell.Value = "x" Then
                sht.Cells(9, Target.Column).Value = "x"
                Exit For
            Else
                sht.Cells(9, Target.Column).Value = ""
            End If
         Next
End If
End Sub


问:
Unable to identify workspaces when running TFS merge command
When I run the command tf workspaces /collection:TeamProjectCollectionUrl, I see that I have three workspaces named Apple, Banana, and Cherry on my local computer.

I change my current directory to the folder that contains the folders for these workspaces, and I run the command tf merge /candidate Apple Banana.

However, I receive the error message Exactly two items (source and target) are required.  Either local or server paths may be used. So I run the merge command again, but this time I specify the full paths to the folders for Apple and Banana respectively. Again, I see the same error message.

What am I doing wrong? How can I merge Apple into Banana through the command line?

答:
The tf merge command is not used to merge 2 workspaces, it is used to merge 2 branches in TFS. To know more about TFS Branch and Merge, please refer to this document.

If you want to merge/combine 2 workspaces (from Apple to Banana), maybe you could follow these steps:

In Visual Studio, switch to Apple workspace first , check in all changes under Apple.

Then switch to Banana workspace, Right-click team project and choose Get Latest Version. Then you will get all changes just submitted from Apple.

If you edit the same files in Apple and Banana, you may get conflicts now. Just use the Merge tool to merge the conflicts.

After you solve the conflicts, the Apple are merged into Banana.


问:
Set and get property directly in delegate
I want to set and get property passed to delegate like this (or should I maintain the state on delegate itself?):</p>

```<code>class Example {
    var p: String by Delegate()
}

class Delegate() {
    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {
        if (prop/*.getValueSomehow()*/){ //<=== is this possible

        } else {
           prop./*setValueSomehow("foo")*/
           return prop./*.getValueSomehow()*/ //<=== is this possible
        }
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
        prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible
    }
}
</code>```

答:
If you want to do some change or checking inside getter and setter, can do like this </p>

```<code>class Example {
    var p: String by Delegate()
}

class Delegate() {
    var localValue: String? = null

    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {

        //This is not possible.
//        if (prop/*.getValueSomehow()*/){ //<=== is this possible
//
//        } else {
//            prop./*setValueSomehow("foo")*/
//                    return prop./*.getValueSomehow()*/ //<=== is this possible
//        }

        if(localValue == null) {
            return ""
        } else {
            return localValue!!
        }
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
        // prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible - this is not possible
        localValue = value
    }
}
</code>```

Body:
I want to set and get property passed to delegate like this (or should I maintain the state on delegate itself?):

class Example {
    var p: String by Delegate()
}

class Delegate() {
    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {
        if (prop/*.getValueSomehow()*/){ //<=== is this possible

        } else {
           prop./*setValueSomehow("foo")*/
           return prop./*.getValueSomehow()*/ //<=== is this possible
        }
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
        prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible
    }
}

Body:
If you want to do some change or checking inside getter and setter, can do like this

class Example {
    var p: String by Delegate()
}

class Delegate() {
    var localValue: String? = null

    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String {

        //This is not possible.
//        if (prop/*.getValueSomehow()*/){ //<=== is this possible
//
//        } else {
//            prop./*setValueSomehow("foo")*/
//                    return prop./*.getValueSomehow()*/ //<=== is this possible
//        }

        if(localValue == null) {
            return ""
        } else {
            return localValue!!
        }
    }

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) {
        // prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible - this is not possible
        localValue = value
    }
}


问:
Windows7+: How to build a C++ Windows Console application that doesn't require any additional/external runtime libraries?
This has probably been asked/answered dozens of times, but even after going/reading through many of these questions, i still can't figure out what to do...

Anyhow: I'm trying to write a standalone X86/32-bit C++ Windows console application using Visual Studio 2017 Community Edition (under Windows 10 x64) that runs some CMD.exe commands.

The problem: When trying to run the application on Windows 7, a dialog box pops up with a message saying that a required runtime library couldn't be found.

As i happen to be fairly new to developing/coding, you can probably understand how overwhelmed i am/was when going through Visual Studio's (project) options.

The goal to reach: I would like to know if there's a way (and how) to make my C++ console application work on Windows 7 and onwards, while ONLY using the operating system's built-in/default shipped libraries (if possible without requiring the .NET framework to run the program).

The application's purpose is really simple and is meant for learning the basics of Visual Studio development.

Hopefully someone can help me out. I know i'm supposed to uncheck any recent SDK's in the Visual Studio Installer, but at the same time it appears that the .NET framework seems to be a required component for writing/compiling CLI applications :S

答: I don't even know why you mention .net for C++. You only need the C++ runtime. That can be statically linked.</p>


问:
how to remove the record from gridview when i click on delete button in vb.net?
how to remove the record from gridview when i click on delete button in vb.net ?</p>

答:
Gridview has an event called 'RowDeleting' which you can use to handle Delete events.
For example:</p>

```<code>Private Sub gridview_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gridview.RowDeleting

   '' Handle your delete here and rebind your datasource if needed

End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Gridview has an event called 'RowDeleting' which you can use to handle Delete events.
For example:

Private Sub gridview_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gridview.RowDeleting

   '' Handle your delete here and rebind your datasource if needed

End Sub


问:
How to read the file without encoding and extract desired urls with python3?
Environment :python3.

There are many files ,some of them encoding with gbk,others encoding with utf-8.
I want to extract all the jpg with regular expression

For s.html encoding with gbk.

```<code>tree = open("/tmp/s.html","r").read()
</code>```

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 135: invalid start byte

```<code>tree = open("/tmp/s.html","r",encoding="gbk").read()
pat = "http://.+\.jpg"
result = re.findall(pat,tree)
print(result)
</code>```

['http://somesite/2017/06/0_56.jpg']

It is a huge job to open all the files with specified encoding,i want a smart way to extract jpg urls in all the files.

答:
I had a similar problem, and how I solved this is as follows.

In get_file_encoding(filename), I first check if there is a BOM (Byte Order Mark) in the file, if so, get the encoding from the BOM. From the function: get_file_bom_encoding(filename)

If that did not return a value, I would get a list from the function: get_all_file_encodings(filename)

This list will have all encodings which the file can be opened in. For the purpose I was doing this, I just needed one, and I did not care about the rest, so I simply choose the first value of the list file_encoding = str(encoding_list[0][0])

This obviously is not accurate a 100% but at least it will give you either the correct encoding from the BOM, or it will give you a list of encodings in which the file can be opened. Or if you do this the same, it will give you one (first value) encoding the file can be opened with without errors.

Here it the code:

```<code># -*- coding: utf-8 -*-
import codecs

def get_file_bom_encoding(filename):
    with open (filename, 'rb') as openfileobject:
        line = str(openfileobject.readline())
        if line[2:14] == str(codecs.BOM_UTF8).split("'")[1]: return 'utf_8'
        if line[2:10] == str(codecs.BOM_UTF16_BE).split("'")[1]: return 'utf_16'
        if line[2:10] == str(codecs.BOM_UTF16_LE).split("'")[1]: return 'utf_16'
        if line[2:18] == str(codecs.BOM_UTF32_BE).split("'")[1]: return 'utf_32'
        if line[2:18] == str(codecs.BOM_UTF32_LE).split("'")[1]: return 'utf_32'
    return ''

def get_all_file_encodings(filename):
    encoding_list = []
    encodings = ('utf_8', 'utf_16', 'utf_16_le', 'utf_16_be',
                 'utf_32', 'utf_32_be', 'utf_32_le',
                 'cp850' , 'cp437', 'cp852', 'cp1252', 'cp1250' , 'ascii',
                 'utf_8_sig', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp500',
                 'cp720', 'cp737', 'cp775', 'cp855', 'cp856', 'cp857',
                 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864',
                 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932',
                 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1251',
                 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257',
                 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213',
                 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp',
                 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004',
                 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1',
                 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5',
                 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9',
                 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
                 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic',
                 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman',
                 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004',
                 'shift_jisx0213'
                 )
    for e in encodings:
        try:
            fh = codecs.open(filename, 'r', encoding=e)
            fh.readlines()
        except UnicodeDecodeError:
            fh.close()
        except UnicodeError:
            fh.close()
        else:
            encoding_list.append([e])
            fh.close()
            continue
    return encoding_list

def get_file_encoding(filename):
        file_encoding = get_file_bom_encoding(filename)
        if file_encoding != '':
            return file_encoding
        encoding_list = get_all_file_encodings(filename)
        file_encoding = str(encoding_list[0][0])
        if file_encoding[-3:] == '_be' or file_encoding[-3:] == '_le':
            file_encoding = file_encoding[:-3]
        return file_encoding

def main():
    print('This Python script is only for import functionality, it does not run interactively')

if __name__ == '__main__':
    main()
</code>```

I am sure that there are modules/packages which can do this more accurately, but this is done with standard packages (which was another requirement I had)

It does mean that you are reading the files multiple times, which is not a very fast way of doing things. You may be able to use this to suite your own particular problem, or even improve on this, especially the "reading multiple times" is something which you could look at, and immediately open the file once one encoding is found.

Body:
Environment :python3.

There are many files ,some of them encoding with gbk,others encoding with utf-8.
I want to extract all the jpg with regular expression

For s.html encoding with gbk.

tree = open("/tmp/s.html","r").read()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 135: invalid start byte

tree = open("/tmp/s.html","r",encoding="gbk").read()
pat = "http://.+\.jpg"
result = re.findall(pat,tree)
print(result)

['http://somesite/2017/06/0_56.jpg']

It is a huge job to open all the files with specified encoding,i want a smart way to extract jpg urls in all the files.

Body:
I had a similar problem, and how I solved this is as follows.

In get_file_encoding(filename), I first check if there is a BOM (Byte Order Mark) in the file, if so, get the encoding from the BOM. From the function: get_file_bom_encoding(filename)

If that did not return a value, I would get a list from the function: get_all_file_encodings(filename)

This list will have all encodings which the file can be opened in. For the purpose I was doing this, I just needed one, and I did not care about the rest, so I simply choose the first value of the list file_encoding = str(encoding_list[0][0])

This obviously is not accurate a 100% but at least it will give you either the correct encoding from the BOM, or it will give you a list of encodings in which the file can be opened. Or if you do this the same, it will give you one (first value) encoding the file can be opened with without errors.

Here it the code:

# -*- coding: utf-8 -*-
import codecs

def get_file_bom_encoding(filename):
    with open (filename, 'rb') as openfileobject:
        line = str(openfileobject.readline())
        if line[2:14] == str(codecs.BOM_UTF8).split("'")[1]: return 'utf_8'
        if line[2:10] == str(codecs.BOM_UTF16_BE).split("'")[1]: return 'utf_16'
        if line[2:10] == str(codecs.BOM_UTF16_LE).split("'")[1]: return 'utf_16'
        if line[2:18] == str(codecs.BOM_UTF32_BE).split("'")[1]: return 'utf_32'
        if line[2:18] == str(codecs.BOM_UTF32_LE).split("'")[1]: return 'utf_32'
    return ''

def get_all_file_encodings(filename):
    encoding_list = []
    encodings = ('utf_8', 'utf_16', 'utf_16_le', 'utf_16_be',
                 'utf_32', 'utf_32_be', 'utf_32_le',
                 'cp850' , 'cp437', 'cp852', 'cp1252', 'cp1250' , 'ascii',
                 'utf_8_sig', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp500',
                 'cp720', 'cp737', 'cp775', 'cp855', 'cp856', 'cp857',
                 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864',
                 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932',
                 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1251',
                 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257',
                 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213',
                 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp',
                 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004',
                 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1',
                 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5',
                 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9',
                 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
                 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic',
                 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman',
                 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004',
                 'shift_jisx0213'
                 )
    for e in encodings:
        try:
            fh = codecs.open(filename, 'r', encoding=e)
            fh.readlines()
        except UnicodeDecodeError:
            fh.close()
        except UnicodeError:
            fh.close()
        else:
            encoding_list.append([e])
            fh.close()
            continue
    return encoding_list

def get_file_encoding(filename):
        file_encoding = get_file_bom_encoding(filename)
        if file_encoding != '':
            return file_encoding
        encoding_list = get_all_file_encodings(filename)
        file_encoding = str(encoding_list[0][0])
        if file_encoding[-3:] == '_be' or file_encoding[-3:] == '_le':
            file_encoding = file_encoding[:-3]
        return file_encoding

def main():
    print('This Python script is only for import functionality, it does not run interactively')

if __name__ == '__main__':
    main()

I am sure that there are modules/packages which can do this more accurately, but this is done with standard packages (which was another requirement I had)

It does mean that you are reading the files multiple times, which is not a very fast way of doing things. You may be able to use this to suite your own particular problem, or even improve on this, especially the "reading multiple times" is something which you could look at, and immediately open the file once one encoding is found.

ContentLicense: CC BY-SA 4.0


问:
Convert a date format in epoch
I have a string with a date format such as

```<code>Jun 13 2003 23:11:52.454 UTC
</code>```

containing millisec... which I want to convert in epoch.
Is there an utility in Java I can use to do this conversion?

答:
Create Common Method to Convert String to Date format

```<code>public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}
</code>```

Title: Convert a date format in epoch

Body:
I have a string with a date format such as

Jun 13 2003 23:11:52.454 UTC

containing millisec... which I want to convert in epoch.
Is there an utility in Java I can use to do this conversion?

Body:
Create Common Method to Convert String to Date format

public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}


问:
php code for displaying Featured Article in joomla
I am new in using joomla.

I want to display Featured Articles on my site but I've searched on different tutorials but none of them has a code-wise instruction on how to display the featured articles.

and is displaying articles by category any different from displaying featured articles?

thanks in advanced!

答: When you make a menu for your site, you have to choose the menu type like:


问:
in d3js bar chart i want to have fixed bar width
http://bl.ocks.org/d3noob/8952219

I want to have bar size width to be fixed..

from above example i have changed the code from

```<code> svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });
</code>```

to

```<code>svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", 50)
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });
</code>```

but the labels are not moving to proper place also bars are getting overlapped

答:
You have to change the range() of your x scale, to fit with your bar width value:

```<code>var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
</code>```

to (if you want 50px as bar width)

```<code>var x = d3.scale.ordinal().range([0, data.length * 50]);
</code>```

The range() method is used to define the display space for your scale.

Body:
http://bl.ocks.org/d3noob/8952219

I want to have bar size width to be fixed..

from above example i have changed the code from

 svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });

to

svg.selectAll("bar")
      .data(data)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", 50)
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });

but the labels are not moving to proper place also bars are getting overlapped

Body:
You have to change the range() of your x scale, to fit with your bar width value:

var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);

to (if you want 50px as bar width)

var x = d3.scale.ordinal().range([0, data.length * 50]);

The range() method is used to define the display space for your scale.


问:
TestNG/Surefire: How to generate an XML report after each test?
We have a large number of complex integration tests that run for several hours.
How do I receive TestNG XML reports while the tests are running, not after the run?</p>

答: You can build a TestNG listener which extends org.testng.TestListenerAdapter and override its org.testng.TestListenerAdapter#onFinish wherein you can build the logic to push the results of a <test> tag after its run to a data source of your own. You can also try making it more real-time by building an implementation of the listener interface org.testng.IInvokedMethodListener and within org.testng.IInvokedMethodListener#afterInvocation check if a method is a test method and if yes, start recording the results to a data source of your choice.


问:
Get the day change point(s) between two UNIX timestamps
I have the date range (two UNIX timestamps) and I need to find point(s) at 23:59:59 if exists.
How I can do it with Perl?

P.S. I think for() is not good idea because I can have very big range. Anything another variants?

答:
I would use Date::Calc.  Suppose your two timestamps are located in $ts1 and $ts2:

```<code>use Date::Calc qw(Time_to_Date Date_to_Time Delta_Days Add_Delta_Days);

my @date1 = (Time_to_Date($ts1))[0..2];
my @date2 = (Time_to_Date($ts2))[0..2];
my @midnights;

for (my $i = 0; $i < Delta_Days(@date1, @date2); ++$i) {
    push @midnights, Date_to_Time(Add_Delta_Days(@date1, $i), 23, 59, 59);
}
</code>```

@midnights now contains the UNIX timestamps (epoch seconds) of all 23:59:59 point(s) between the two given timestamps.

Disclaimer: Of course you could also do it with DateTime.

Body:
I would use Date::Calc.  Suppose your two timestamps are located in $ts1 and $ts2:

use Date::Calc qw(Time_to_Date Date_to_Time Delta_Days Add_Delta_Days);

my @date1 = (Time_to_Date($ts1))[0..2];
my @date2 = (Time_to_Date($ts2))[0..2];
my @midnights;

for (my $i = 0; $i < Delta_Days(@date1, @date2); ++$i) {
    push @midnights, Date_to_Time(Add_Delta_Days(@date1, $i), 23, 59, 59);
}

@midnights now contains the UNIX timestamps (epoch seconds) of all 23:59:59 point(s) between the two given timestamps.

Disclaimer: Of course you could also do it with DateTime.


问:
Will Boost.Asio's async_read_some the whole message?
I am trying to receive a package via http in my C++ program. I am using Boost.Asio for that purpose.

In my handleAccept method I have this code to read the package:

    // m_buffer is declared as: std::array<char, 8192> m_buffer;
    auto buf = boost::asio::buffer(m_buffer);
    newConnection->getSocket().async_read_some(
        buf,
        boost::bind(&TcpServer::handleRead, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
    );
```

Is this enough to get any package? How do I make sure that it will get packages that are bigger than 8192 bytes?

答:
async_read_some reads a received message up to the size of the buffer that you give it. The number of bytes in a received message is returned in the bytes_transferred placeholder of the callback function, see basic_stream_socket::async_read_some

If you know the maximum size of the messages that you expect to receive, you can simply use a buffer that is large enough for that message. Otherwise, you'll have to copy the contents of the async_read_some buffer elsewhere and build up the whole received message there.

Body:
I am trying to receive a package via http in my C++ program. I am using Boost.Asio for that purpose.

In my handleAccept method I have this code to read the package:

    // m_buffer is declared as: std::array<char, 8192> m_buffer;
    auto buf = boost::asio::buffer(m_buffer);
    newConnection->getSocket().async_read_some(
        buf,
        boost::bind(&TcpServer::handleRead, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
    );

Is this enough to get any package? How do I make sure that it will get packages that are bigger than 8192 bytes?


问:
jsx style with condition
I know I can do condition with className but how about style?

```<code><span style={{float:'right'}}>Something</span>
</code>```

Like for above jsx, I want to float right if obj.name is equal to 'active'

答:
You may also want to set this in the render method of the component. I personally think that this is a more readable solution overall:

```<code>render() {
    let customStyles = obj.name === 'active' ? { float: 'right' } : {};
    return (<span style={customStyles}>Something</span>);
}
</code>```

You'll need to have obj in scope for this to work of course.

Title: jsx style with condition

Body:
I know I can do condition with className but how about style?

Something

Like for above jsx, I want to float right if obj.name is equal to 'active'

Body:
You may also want to set this in the render method of the component. I personally think that this is a more readable solution overall:

render() {
    let customStyles = obj.name === 'active' ? { float: 'right' } : {};
    return (<span style={customStyles}>Something</span>);
}

You'll need to have obj in scope for this to work of course.


问:
How do I change date format in Android
I am displaying the date and time in Android with this format:
07-06-2017

How can I change it to the following format?
07/06/2017

答:
You can use this method to change the date format</p>

```<code>public String changeDateFormat(String dateInString, String outputFormat) {
       String inputFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        SimpleDateFormat inputFormat = new SimpleDateFormat(inputFormat, Locale.ENGLISH);
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputFormat, Locale.ENGLISH);
        Date date;
        String str = null;
        try {
            date = inputFormat.parse(dateInString);
            str = outputFormat.format(date);
        } catch (ParseException e) {
            LogManager.e(e.getMessage());
        }
        return str;
    }
</code>```

Title: How do I change date format in Android

Body:
You can use this method to change the date format

public String changeDateFormat(String dateInString, String outputFormat) {
       String inputFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        SimpleDateFormat inputFormat = new SimpleDateFormat(inputFormat, Locale.ENGLISH);
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputFormat, Locale.ENGLISH);
        Date date;
        String str = null;
        try {
            date = inputFormat.parse(dateInString);
            str = outputFormat.format(date);
        } catch (ParseException e) {
            LogManager.e(e.getMessage());
        }
        return str;
    }


问:
Can't hide soft keyboard in Android Studio project, why?
I'm trying to hide the soft keyboard in an Android Studio project. The View in the hideKeyboard() method keeps coming up as null... I can't figure out why... Please advise. </p>

```<code>  @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rewashlog_options);

    luxuryCountTextView = (TextView) findViewById(R.id.luxuryCountTextView);
    fullCountTextView = (TextView) findViewById(R.id.fullCountTextView);
    quickCountTextView = (TextView) findViewById(R.id.quickCountTextView);
    totalCountTextView = (TextView) findViewById(R.id.totalCountTextView);
    emailRecipient = (EditText) findViewById(R.id.emailRecipient);

    instantiateMonthSpinner();
    instantiateYearSpinner();
    getEntireRewashList();
    updateListView();
    hideKeyboard();

}

 private void hideKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}
</code>```

答:
Update your InputMethodManager :</p>

```<code>InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
</code>```

Body:
I'm trying to hide the soft keyboard in an Android Studio project. The View in the hideKeyboard() method keeps coming up as null... I can't figure out why... Please advise.

  @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rewashlog_options);

    luxuryCountTextView = (TextView) findViewById(R.id.luxuryCountTextView);
    fullCountTextView = (TextView) findViewById(R.id.fullCountTextView);
    quickCountTextView = (TextView) findViewById(R.id.quickCountTextView);
    totalCountTextView = (TextView) findViewById(R.id.totalCountTextView);
    emailRecipient = (EditText) findViewById(R.id.emailRecipient);

    instantiateMonthSpinner();
    instantiateYearSpinner();
    getEntireRewashList();
    updateListView();
    hideKeyboard();

}

 private void hideKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

}

Body:
Update your InputMethodManager :

InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);


问:
What is the difference b/w onReceivedHttpError and onReceivedError for WebView Client
I am trying to understand the difference b/w https://developer.android.com/reference/android/webkit/WebViewClient.html

onRecievedHttpError and onRecievedError.

For me I always get both of these callbacks for all errors in my webpage?
Why we have two callbacks then.

答:
onReceivedError()

Report web resource loading error to the host application. These errors usually indicate inability to connect to the server.

It's about network/server errors. The errors are not HTTP errors but are
unrecoverable resource errors (file not found, no network connection, server not found for the main resource,
etc.). If there is a network error, there cannot be a HTTP error code transmitted.

onReceivedHttpError()

Notify the host application that an HTTP error has been received from the server while loading a resource. HTTP errors have status codes >= 400.


问:
Controling button/hbox sizes in gtk
I am writing an app in python using getk and I've come across a problem. I am using an hbox to hold the buttons that go on my tool bar (new, open, save, etc) but the hbox seems to be expanding to take up a particular portion of the screen and the buttons are doing so as well making them really tall and ugly. How do I get them to stay at adecent size? I have already tried setting the expand and fill values to false and I can't find any methods to control the size of ether a button or an hbox. Here is the code for my new button:</p>

```<code>img = gtk.Image()
img.set_from_stock(gtk.STOCK_NEW,gtk.ICON_SIZE_SMALL_TOOLBAR)
newButt = gtk.Button()
newButt.set_image(img)
newButt.show()
self.hBox4.pack_start(newButt, False, False, 0)
</code>```

答:
Child widgets will assume the allocation size that they parent widgets can give. You should set the size of the hbox or the button.

See here the size_request method of PyGTK to get more information.

Title: Controling button/hbox sizes in gtk

Body:
I am writing an app in python using getk and I've come across a problem. I am using an hbox to hold the buttons that go on my tool bar (new, open, save, etc) but the hbox seems to be expanding to take up a particular portion of the screen and the buttons are doing so as well making them really tall and ugly. How do I get them to stay at adecent size? I have already tried setting the expand and fill values to false and I can't find any methods to control the size of ether a button or an hbox. Here is the code for my new button:

img = gtk.Image()
img.set_from_stock(gtk.STOCK_NEW,gtk.ICON_SIZE_SMALL_TOOLBAR)
newButt = gtk.Button()
newButt.set_image(img)
newButt.show()
self.hBox4.pack_start(newButt, False, False, 0)


问:
How can i get ongoing project count in each month using MYSQL?
I have the table like this

```<code>Title    | start_date |end_date   |
------   | ---------- |---------  |
Test_pro1 | 2017-06-06 |2017-08-06 |
Test_pro2 | 2017-07-06 |2017-11-06 |
</code>```

I need the ongoing project count in each month.

```<code>Example 1 : 2017-06-06 project count = 1
Example 2 : 2017-07-06 project count = 2
Example 3 : 2017-11-06 project count = 0
</code>```

How can i write a query in MYSQL?

答:
You could do something like this:</p>

```<code>SELECT MONTH(start_date),count(title)
from projects
group by month(start_date)
</code>```

Body:
I have the table like this

Title    | start_date |end_date   |
------   | ---------- |---------  |
Test_pro1 | 2017-06-06 |2017-08-06 |
Test_pro2 | 2017-07-06 |2017-11-06 |

I need the ongoing project count in each month.

Example 1 : 2017-06-06 project count = 1
Example 2 : 2017-07-06 project count = 2
Example 3 : 2017-11-06 project count = 0

How can i write a query in MYSQL?

Body:
You could do something like this:

SELECT MONTH(start_date),count(title)
from projects
group by month(start_date)


问:
Joining tables depends on activity and activity id
i need to do a search query whitch will look for result in 2 separated tables depending on activity.
The problem is, they are joining the same id. Right now its not working properly..

Table log

```<code>id     activity     activityid
1       news          155
2       prod          232
3       news          412
</code>```

Table news

```<code>id       title
155      Something
412      Something
</code>```

Table product

```<code>id       intro
232      Something

SELECT *
FROM log l
INNER JOIN product p ON l.activityid=p.id and l.activity='prod'
INNER JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE p.title like '%something%' or n.intro like '%something%'
</code>```

What am i missing?

答:
May be Use Left Join and alias names are mismatched n.title and p.intro.

```<code>SELECT *
FROM log l
LEFT JOIN product p ON l.activityid=p.id and l.activity='prod'
LEFT JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE n.title like '%something%'
    or p.intro like '%something%'
</code>```

Body:
i need to do a search query whitch will look for result in 2 separated tables depending on activity.
The problem is, they are joining the same id. Right now its not working properly..

Table log

id     activity     activityid
1       news          155
2       prod          232
3       news          412

Table news

id       title
155      Something
412      Something

Table product

id       intro
232      Something

SELECT *
FROM log l
INNER JOIN product p ON l.activityid=p.id and l.activity='prod'
INNER JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE p.title like '%something%' or n.intro like '%something%'

What am i missing?

Body:
May be Use Left Join and alias names are mismatched n.title and p.intro.

SELECT *
FROM log l
LEFT JOIN product p ON l.activityid=p.id and l.activity='prod'
LEFT JOIN news n ON l.activityid=n.id and l.activity='news'
WHERE n.title like '%something%'
    or p.intro like '%something%'


问:
'NoneType' object has no attribute error in Binary Tree implementation in python
I wrote the following code to simply implement a binary tree in python. I get "AttributeError: 'NoneType' object has no attribute 'data'" when I am calling the "find_Node" method. I know what this error is, but I cannot find out why it just appears when I call "find_Node" method. Any clue would be appreciated.

Here is my code:

```<code>#!/usr/bin/env python2

class BinaryTree:

    class Node:

        def __init__(self,data,left=None,right=None):
            self.data=data
            self.left=left
            self.right=right

        def get_RightChild(self):
            return self.right

        def get_LeftChilld(self):
            return self.left

        def get_Nodedata(self):
            return self.data

        def set_NodeData(self,data):
            self.data=data

    def __init__(self,rootdata):
        self.root=self.Node(rootdata)
        self.size=1

    def get_Root(self):
        return self.root

    def get_Size(self):
        return self.size

    def insert_LeftNode(self,data,root):
        if root.left==None:
            root.left=self.Node(data)
        else:
            self.insert_LeftNode(data,root.left)
        self.size+=1

    def insert_RightNode(self,data,root):
        if root.right==None:
            root.right=self.Node(data)
        else:
            self.insert_RightNode(data,root.right)
        self.size+=1

    #needs revision - does not work properly
    def find_Node(self,data,root):
        if root.data == data:
            return 1
        self.find_Node(data,root.right)
        self.find_Node(data,root.left)
        return 0

    def preorder_Traverse(self,root):
        if root != None:
            print root.data,
            self.preorder_Traverse(root.left)
            self.preorder_Traverse(root.right)

    def inorder_Traverse(self,root):
        if root!=None:
            self.inorder_Traverse(root.left)
            print root.data,
            self.inorder_Traverse(root.right)

    def postorder_Traverse(self,root):
        if root!=None:
            self.postorder_Traverse(root.left)
            self.postorder_Traverse(root.right)
            print root.data,

if __name__=="__main__":
    mybinary=BinaryTree(314)
    mybinary.insert_LeftNode(6,mybinary.get_Root())
    mybinary.insert_RightNode(7,mybinary.get_Root())
    mybinary.insert_LeftNode(2,mybinary.root.left)
    mybinary.insert_RightNode(4,mybinary.root.left)

    mybinary.inorder_Traverse(mybinary.get_Root())

    print

    if mybinary.find_Node(7,mybinary.get_Root()):
        print "found"
    else:
        print "Not Found!"
</code>```

答:
Check is root is None, also root.left or root.right could be None, change your find_Node method to the code below

```<code>def find_Node(self,data,root):
    if(root is None):
        return 0
    if root.data == data:
        return 1
    return self.find_Node(data,root.right) or self.find_Node(data,root.left)
</code>```

Body:
I wrote the following code to simply implement a binary tree in python. I get "AttributeError: 'NoneType' object has no attribute 'data'" when I am calling the "find_Node" method. I know what this error is, but I cannot find out why it just appears when I call "find_Node" method. Any clue would be appreciated.

Here is my code:

#!/usr/bin/env python2

class BinaryTree:

    class Node:

        def __init__(self,data,left=None,right=None):
            self.data=data
            self.left=left
            self.right=right

        def get_RightChild(self):
            return self.right

        def get_LeftChilld(self):
            return self.left

        def get_Nodedata(self):
            return self.data

        def set_NodeData(self,data):
            self.data=data

    def __init__(self,rootdata):
        self.root=self.Node(rootdata)
        self.size=1

    def get_Root(self):
        return self.root

    def get_Size(self):
        return self.size

    def insert_LeftNode(self,data,root):
        if root.left==None:
            root.left=self.Node(data)
        else:
            self.insert_LeftNode(data,root.left)
        self.size+=1

    def insert_RightNode(self,data,root):
        if root.right==None:
            root.right=self.Node(data)
        else:
            self.insert_RightNode(data,root.right)
        self.size+=1

    #needs revision - does not work properly
    def find_Node(self,data,root):
        if root.data == data:
            return 1
        self.find_Node(data,root.right)
        self.find_Node(data,root.left)
        return 0

    def preorder_Traverse(self,root):
        if root != None:
            print root.data,
            self.preorder_Traverse(root.left)
            self.preorder_Traverse(root.right)

    def inorder_Traverse(self,root):
        if root!=None:
            self.inorder_Traverse(root.left)
            print root.data,
            self.inorder_Traverse(root.right)

    def postorder_Traverse(self,root):
        if root!=None:
            self.postorder_Traverse(root.left)
            self.postorder_Traverse(root.right)
            print root.data,

if __name__=="__main__":
    mybinary=BinaryTree(314)
    mybinary.insert_LeftNode(6,mybinary.get_Root())
    mybinary.insert_RightNode(7,mybinary.get_Root())
    mybinary.insert_LeftNode(2,mybinary.root.left)
    mybinary.insert_RightNode(4,mybinary.root.left)

    mybinary.inorder_Traverse(mybinary.get_Root())

    print

    if mybinary.find_Node(7,mybinary.get_Root()):
        print "found"
    else:
        print "Not Found!"

Body:
Check is root is None, also root.left or root.right could be None, change your find_Node method to the code below

def find_Node(self,data,root):
    if(root is None):
        return 0
    if root.data == data:
        return 1
    return self.find_Node(data,root.right) or self.find_Node(data,root.left)


问:
Spring boot not logging CQL queries
I am using Spring Boot Data Cassandra in my spring boot project, I am trying to log CQL queries but setting spring.jpa.show-sql to true is not working.
here is my application.properties

```<code>spring.data.cassandra.keyspace-name=sample
spring.data.cassandra.contact-points=127.0.0.1
spring.data.cassandra.port=9042
spring.data.cassandra.schema-action=CREATE_IF_NOT_EXISTS
spring.jpa.show-sql=true
</code>```

答:
Not sure what are you expecting from a JPA property.

According to the current boot docs, there is no such property which can show you the executed queries.

However, you can go with the native logging implementation explained here.

Title: Spring boot not logging CQL queries

Body:
I am using Spring Boot Data Cassandra in my spring boot project, I am trying to log CQL queries but setting spring.jpa.show-sql to true is not working.
here is my application.properties

spring.data.cassandra.keyspace-name=sample
spring.data.cassandra.contact-points=127.0.0.1
spring.data.cassandra.port=9042
spring.data.cassandra.schema-action=CREATE_IF_NOT_EXISTS
spring.jpa.show-sql=true


问:
Cakephp read() on a non-object in session when I call another Controller
I'm working with Cakephp and I get a error with sessions when I call a method from another Controller.

Error
Error: Call to a member function read() on a non-object

Controller Hotels

```<code>App::import('Controller', 'Reports');
$Report = new ReportsController;
$Report->hotelsActivity($cabecera, $data, "Actividad Hotels Report");
</code>```

Method of Controller Reports

```<code>function hotelsActivity($cabecera, $data, $nombre){
  $this->layout = false;
  $this->autoRender = false;
  $size = parent::excel($cabecera, $data, $nombre);

  $this->set('filesize',CakeNumber::toReadableSize($size));
  $this->set('counter',count($data));

  $this->render('new_reports');
}
</code>```

Header appController

```<code>App::uses('Controller', 'Controller');

class AppController extends Controller {
    public $components = array(
      'Session'
    );

    public $helpers = array(
        'Session'
    );

    public function beforeFilter() {
        parent::beforeFilter();

        //$this->Auth->allow();
        //$this->Auth->allow("*");
    }

    public function breadcump(){

        $model = $this->name;

        $breadcump = Array();
        foreach($_GET as $key => $value){
            switch($key){
              case "hotels_id":
                $breadcump_model = "Hotel";
                $breadcump_name = "Hotel";
                $breadcump_field = "name";
              break;
              case "medics_id":
                $breadcump_model = "Medic";
                $breadcump_name = "Médico";
                $breadcump_field = "name";
              break;
              case "users_id":
                $breadcump_model = "User";
                $breadcump_name = "Usuario";
                $breadcump_field = "user_name";
              break;
              case "manager_id":
                $breadcump_model = "User";
                $breadcump_name = "Manager";
                $breadcump_field = "user_name";
              break;
              case "group_id":
                $breadcump_model = "Group";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "nightusers_id":
                $breadcump_model = "User";
                $breadcump_name = "Responsable de noche";
                $breadcump_field = "user_name";
              break;
              case "hotelstypes_id":
                $breadcump_model = "Hotelstype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "hotelsgroups_id":
                $breadcump_model = "Hotelsgroup";
                $breadcump_name = "Cadena";
                $breadcump_field = "name";
              break;
              case "regions_id":
                $breadcump_model = "Region";
                $breadcump_name = "Region";
                $breadcump_field = "name";
              break;
              case "zones_id":
                $breadcump_model = "Zone";
                $breadcump_name = "Zona";
                $breadcump_field = "name";
              break;
              case "subzones_id":
                $breadcump_model = "Subzone";
                $breadcump_name = "Subzona";
                $breadcump_field = "name";
              break;
              case "centres_id":
                $breadcump_model = "Centre";
                $breadcump_name = "Centro";
                $breadcump_field = "name";
              break;
              case "ttoos_id":
                $breadcump_model = "Ttoo";
                $breadcump_name = "Tour Operador";
                $breadcump_field = "name";
              break;
              case "incidencestypes_id":
                $breadcump_model = "Incidencestype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "origins_id":
                $breadcump_model = "Origin";
                $breadcump_name = "Origen";
                $breadcump_field = "name";
              break;
              case "ttoogroups_id":
                $breadcump_model = "Ttoogroup";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "ttoonationalities_id":
                $breadcump_model = "Ttoonationality";
                $breadcump_name = "Nacionalidad";
                $breadcump_field = "name";
              break;
              default:
                $breadcump_model = null;
            }

            // Condición para las búsquedas belongsto
            if($breadcump_model){
              if($value != ""){
                $breadcump[$key] = $value;
                $this->loadModel($breadcump_model);
                $conditions = array('conditions' => array($breadcump_model.'.id =' => $value), 'fields' => array($breadcump_model.'.'.$breadcump_field));
                $hotel = $this->$breadcump_model->find('all', $conditions);
                if($breadcump_name == "Responsable de noche"){
                  $breadcump[$breadcump_model."2"]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model."2"]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model."2"]['id'] = $value;
                }
                else{
                  $breadcump[$breadcump_model]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model]['id'] = $value;
                }
              }
            }
            // Condición para las búsquedas fijas tipo fecha inicio, fecha fin, status..
            else{
              if($value != ""){
                if($key == "status"){
                    if ($model=="Incidences") {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Activa"; break;
                          case 2: $value = "Finalizada"; break;
                        }
                    } else {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Aceptada"; break;
                          case 2: $value = "Asignada"; break;
                          case 3: $value = "Registrada"; break;
                          case 4: $value = "Anulada"; break;
                        }
                    }
                }
                if($key == "colaborator"){
                  switch($value){
                    case 'y': $value = "Sí"; break;
                    case 'n': $value = "No"; break;
                  }
                }
                if($key == "priority"){
                  $key = "Prioridad médico";
                }
                if($key =="dpd1"){
                    $key = "Fecha Inicio";
                }
                if($key =="dpd2"){
                    $key = "Fecha Fin";
                }

                $breadcump[$key] = $value;
                $breadcump[$key] = array('data_name' => $key, 'data' => $value);
              }
            }
        }

        return $breadcump;
    }

    public function excel($cabecera, $data, $report_type){

      $counter = count($data);
      $celdas = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

      // Importamos la clase PHPExcel
      App::import('Vendor', 'Classes/PHPExcel');
      App::uses('CakeTime', 'Utility');
      App::uses('CakeNumber', 'Utility');

      $objPHPExcel = new PHPExcel();
      $objPHPExcel->setActiveSheetIndex(0);

      $session = $this->request->session();
      $session->read('auth_user.User.user_name');

      // Set properties
      $objPHPExcel->getProperties()->setCreator($session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setLastModifiedBy($this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setTitle("FreepApp ".$report_type);
      $objPHPExcel->getProperties()->setSubject("Autogenerated Excel File");
      $objPHPExcel->getProperties()->setDescription("This is an automated excel file generated by IMS FreepApp Application");

      $filename = WWW_ROOT.'/files/tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx';

      $this->set('filename','tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx');

      //Sheet rename
      $objPHPExcel->getActiveSheet()->setTitle($report_type);

      //Creating Header
      $objPHPExcel->getActiveSheet()->SetCellValue('A1', Configure::read('title') . ' ' . Configure::read('Ver') . ' Report System');
      $objPHPExcel->getActiveSheet()->SetCellValue('A2', 'Type');
      $objPHPExcel->getActiveSheet()->SetCellValue('B2', $report_type);
      $objPHPExcel->getActiveSheet()->SetCellValue('A3', 'Records');
      $objPHPExcel->getActiveSheet()->SetCellValue('B3', $counter);
      $objPHPExcel->getActiveSheet()->SetCellValue('A4', 'Date');
      $objPHPExcel->getActiveSheet()->SetCellValue('B4', date('d/m/Y H:i:s', time()));
      $objPHPExcel->getActiveSheet()->SetCellValue('A5', 'User');
      $objPHPExcel->getActiveSheet()->SetCellValue('B5', $this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getActiveSheet()->mergeCells('A1:X1');
      $objPHPExcel->getActiveSheet()->mergeCells('B2:X2');
      $objPHPExcel->getActiveSheet()->mergeCells('B3:X3');
      $objPHPExcel->getActiveSheet()->mergeCells('B4:X4');
      $objPHPExcel->getActiveSheet()->mergeCells('B5:X5');

      //Header styles
      $style1 = array(
          'font' => array(
              'bold' => true,
              'size' => '18',
              'color' => array('rgb' => 'ffffff')

          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $style2 = array(
          'font' => array(
              'bold' => true,
              'size' => '14',
              'color' => array('rgb' => 'ffffff')
          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle('A1:X1')->applyFromArray($style1);
      $objPHPExcel->getActiveSheet()->getStyle('A2:B5')->applyFromArray($style2);

      //Title Bars
      for ($i=0; $i < count($cabecera); $i++) {
        if($i == 0){ $primeraCelda = "$celdas[$i]7"; }
        elseif( $i == (count($cabecera)-1) ){ $ultimaCelda = "$celdas[$i]7"; }
        $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$i]7", "$cabecera[$i]");
      }

      $header = "$primeraCelda:$ultimaCelda";
      $style = array(
          'font' => array('bold' => true,),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => 'E0E0E0')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle($header)->applyFromArray($style);
      $objPHPExcel->getActiveSheet()->setAutoFilter("$primeraCelda:$ultimaCelda");

      $rowCount = 8;
      for ($i=0; $i < count($data); $i++) {
        $contadorCeldas = 0;
        foreach ($data[$i] as $key => $arrayFinal) {
          $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$contadorCeldas]$rowCount", $data[$i][$key]);
              $contadorCeldas++;
        }
        $rowCount++;
      }

      //Set column autosize
      for($col = 'A'; $col !== 'AA'; $col++) {
          $objPHPExcel->getActiveSheet()
              ->getColumnDimension($col)
              ->setAutoSize(true);
      }
      $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
      $objWriter->save($filename);

      $f = fopen($filename, 'r+');
      $stat = fstat($f);
      return $size = $stat['size'];

    }

}
</code>```

Line on get the error in parent Controller

```<code>$this->Session->read('auth_user.User.user_name')
</code>```

答:
Try this please:

Add the component  into your controller

```<code>public $components = array('Session');
</code>```

And inside your action:

```<code>$session = $this->request->session();
$session->read('auth_user.User.user_name');
</code>```

Body:
I'm working with Cakephp and I get a error with sessions when I call a method from another Controller.

Error
Error: Call to a member function read() on a non-object

Controller Hotels

App::import('Controller', 'Reports');
$Report = new ReportsController;
$Report->hotelsActivity($cabecera, $data, "Actividad Hotels Report");

Method of Controller Reports

function hotelsActivity($cabecera, $data, $nombre){
  $this->layout = false;
  $this->autoRender = false;
  $size = parent::excel($cabecera, $data, $nombre);

  $this->set('filesize',CakeNumber::toReadableSize($size));
  $this->set('counter',count($data));

  $this->render('new_reports');
}

Header appController

App::uses('Controller', 'Controller');

class AppController extends Controller {
    public $components = array(
      'Session'
    );

    public $helpers = array(
        'Session'
    );

    public function beforeFilter() {
        parent::beforeFilter();

        //$this->Auth->allow();
        //$this->Auth->allow("*");
    }

    public function breadcump(){

        $model = $this->name;

        $breadcump = Array();
        foreach($_GET as $key => $value){
            switch($key){
              case "hotels_id":
                $breadcump_model = "Hotel";
                $breadcump_name = "Hotel";
                $breadcump_field = "name";
              break;
              case "medics_id":
                $breadcump_model = "Medic";
                $breadcump_name = "Médico";
                $breadcump_field = "name";
              break;
              case "users_id":
                $breadcump_model = "User";
                $breadcump_name = "Usuario";
                $breadcump_field = "user_name";
              break;
              case "manager_id":
                $breadcump_model = "User";
                $breadcump_name = "Manager";
                $breadcump_field = "user_name";
              break;
              case "group_id":
                $breadcump_model = "Group";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "nightusers_id":
                $breadcump_model = "User";
                $breadcump_name = "Responsable de noche";
                $breadcump_field = "user_name";
              break;
              case "hotelstypes_id":
                $breadcump_model = "Hotelstype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "hotelsgroups_id":
                $breadcump_model = "Hotelsgroup";
                $breadcump_name = "Cadena";
                $breadcump_field = "name";
              break;
              case "regions_id":
                $breadcump_model = "Region";
                $breadcump_name = "Region";
                $breadcump_field = "name";
              break;
              case "zones_id":
                $breadcump_model = "Zone";
                $breadcump_name = "Zona";
                $breadcump_field = "name";
              break;
              case "subzones_id":
                $breadcump_model = "Subzone";
                $breadcump_name = "Subzona";
                $breadcump_field = "name";
              break;
              case "centres_id":
                $breadcump_model = "Centre";
                $breadcump_name = "Centro";
                $breadcump_field = "name";
              break;
              case "ttoos_id":
                $breadcump_model = "Ttoo";
                $breadcump_name = "Tour Operador";
                $breadcump_field = "name";
              break;
              case "incidencestypes_id":
                $breadcump_model = "Incidencestype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "origins_id":
                $breadcump_model = "Origin";
                $breadcump_name = "Origen";
                $breadcump_field = "name";
              break;
              case "ttoogroups_id":
                $breadcump_model = "Ttoogroup";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "ttoonationalities_id":
                $breadcump_model = "Ttoonationality";
                $breadcump_name = "Nacionalidad";
                $breadcump_field = "name";
              break;
              default:
                $breadcump_model = null;
            }

            // Condición para las búsquedas belongsto
            if($breadcump_model){
              if($value != ""){
                $breadcump[$key] = $value;
                $this->loadModel($breadcump_model);
                $conditions = array('conditions' => array($breadcump_model.'.id =' => $value), 'fields' => array($breadcump_model.'.'.$breadcump_field));
                $hotel = $this->$breadcump_model->find('all', $conditions);
                if($breadcump_name == "Responsable de noche"){
                  $breadcump[$breadcump_model."2"]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model."2"]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model."2"]['id'] = $value;
                }
                else{
                  $breadcump[$breadcump_model]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model]['id'] = $value;
                }
              }
            }
            // Condición para las búsquedas fijas tipo fecha inicio, fecha fin, status..
            else{
              if($value != ""){
                if($key == "status"){
                    if ($model=="Incidences") {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Activa"; break;
                          case 2: $value = "Finalizada"; break;
                        }
                    } else {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Aceptada"; break;
                          case 2: $value = "Asignada"; break;
                          case 3: $value = "Registrada"; break;
                          case 4: $value = "Anulada"; break;
                        }
                    }
                }
                if($key == "colaborator"){
                  switch($value){
                    case 'y': $value = "Sí"; break;
                    case 'n': $value = "No"; break;
                  }
                }
                if($key == "priority"){
                  $key = "Prioridad médico";
                }
                if($key =="dpd1"){
                    $key = "Fecha Inicio";
                }
                if($key =="dpd2"){
                    $key = "Fecha Fin";
                }

                $breadcump[$key] = $value;
                $breadcump[$key] = array('data_name' => $key, 'data' => $value);
              }
            }
        }

        return $breadcump;
    }

    public function excel($cabecera, $data, $report_type){

      $counter = count($data);
      $celdas = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

      // Importamos la clase PHPExcel
      App::import('Vendor', 'Classes/PHPExcel');
      App::uses('CakeTime', 'Utility');
      App::uses('CakeNumber', 'Utility');

      $objPHPExcel = new PHPExcel();
      $objPHPExcel->setActiveSheetIndex(0);

      $session = $this->request->session();
      $session->read('auth_user.User.user_name');

      // Set properties
      $objPHPExcel->getProperties()->setCreator($session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setLastModifiedBy($this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setTitle("FreepApp ".$report_type);
      $objPHPExcel->getProperties()->setSubject("Autogenerated Excel File");
      $objPHPExcel->getProperties()->setDescription("This is an automated excel file generated by IMS FreepApp Application");

      $filename = WWW_ROOT.'/files/tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx';

      $this->set('filename','tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx');

      //Sheet rename
      $objPHPExcel->getActiveSheet()->setTitle($report_type);

      //Creating Header
      $objPHPExcel->getActiveSheet()->SetCellValue('A1', Configure::read('title') . ' ' . Configure::read('Ver') . ' Report System');
      $objPHPExcel->getActiveSheet()->SetCellValue('A2', 'Type');
      $objPHPExcel->getActiveSheet()->SetCellValue('B2', $report_type);
      $objPHPExcel->getActiveSheet()->SetCellValue('A3', 'Records');
      $objPHPExcel->getActiveSheet()->SetCellValue('B3', $counter);
      $objPHPExcel->getActiveSheet()->SetCellValue('A4', 'Date');
      $objPHPExcel->getActiveSheet()->SetCellValue('B4', date('d/m/Y H:i:s', time()));
      $objPHPExcel->getActiveSheet()->SetCellValue('A5', 'User');
      $objPHPExcel->getActiveSheet()->SetCellValue('B5', $this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getActiveSheet()->mergeCells('A1:X1');
      $objPHPExcel->getActiveSheet()->mergeCells('B2:X2');
      $objPHPExcel->getActiveSheet()->mergeCells('B3:X3');
      $objPHPExcel->getActiveSheet()->mergeCells('B4:X4');
      $objPHPExcel->getActiveSheet()->mergeCells('B5:X5');

      //Header styles
      $style1 = array(
          'font' => array(
              'bold' => true,
              'size' => '18',
              'color' => array('rgb' => 'ffffff')

          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $style2 = array(
          'font' => array(
              'bold' => true,
              'size' => '14',
              'color' => array('rgb' => 'ffffff')
          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle('A1:X1')->applyFromArray($style1);
      $objPHPExcel->getActiveSheet()->getStyle('A2:B5')->applyFromArray($style2);

      //Title Bars
      for ($i=0; $i < count($cabecera); $i++) {
        if($i == 0){ $primeraCelda = "$celdas[$i]7"; }
        elseif( $i == (count($cabecera)-1) ){ $ultimaCelda = "$celdas[$i]7"; }
        $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$i]7", "$cabecera[$i]");
      }

      $header = "$primeraCelda:$ultimaCelda";
      $style = array(
          'font' => array('bold' => true,),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => 'E0E0E0')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle($header)->applyFromArray($style);
      $objPHPExcel->getActiveSheet()->setAutoFilter("$primeraCelda:$ultimaCelda");

      $rowCount = 8;
      for ($i=0; $i < count($data); $i++) {
        $contadorCeldas = 0;
        foreach ($data[$i] as $key => $arrayFinal) {
          $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$contadorCeldas]$rowCount", $data[$i][$key]);
              $contadorCeldas++;
        }
        $rowCount++;
      }

      //Set column autosize
      for($col = 'A'; $col !== 'AA'; $col++) {
          $objPHPExcel->getActiveSheet()
              ->getColumnDimension($col)
              ->setAutoSize(true);
      }
      $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
      $objWriter->save($filename);

      $f = fopen($filename, 'r+');
      $stat = fstat($f);
      return $size = $stat['size'];

    }

}

Line on get the error in parent Controller

$this->Session->read('auth_user.User.user_name')

Body:
Try this please:

Add the component  into your controller

public $components = array('Session');

And inside your action:

$session = $this->request->session();
$session->read('auth_user.User.user_name');