来源: stackexchange

问:
How to get UnitOfWork from EventManager Mock Object Or how to get last persisted object in PHP Unit?
I am trying to unit test my bundle and I want to get unit of work from EventManager Mock. Basically, I want to get the last persisted object. I know in normal application, I can do the same with a EventSubscriber.

What I want to achieve is basically, check status of previous persisted record if its flag is pending, then in next persist, I want to update it to not pending.

Example:

Here's how I get Event Manager:

```<code>/**
 * @param Entity\Friend|null $friendEntity
 * @return \Doctrine\ORM\EntityManager|\PHPUnit_Framework_MockObject_MockObject
 */
private function getEntityManager(Entity\Friend $friendEntity = null)
{
    $repository = $this
        ->getMockBuilder('\Doctrine\ORM\EntityRepository')
        ->disableOriginalConstructor()
        ->setMethods(['findBy'])
        ->getMock();
    $repository
        ->expects($this->any())
        ->method('findBy')
        ->will($this->returnValue(null));

    /** @var \Doctrine\ORM\EntityManager|\PHPUnit_Framework_MockObject_MockObject $entityManager */
    $entityManager = $this
        ->getMockBuilder('\Doctrine\ORM\EntityManager')
        ->setMethods(['getRepository', 'getUnitOfWork', 'persist'])
        ->disableOriginalConstructor()
        ->getMock();
    $entityManager
        ->expects($this->any())
        ->method('getRepository')
        ->will($this->returnValue($repository));
    $entityManager
        ->expects($this->any())
        ->method('getUnitOfWork')
        ->will($this->returnValue($repository));
    $entityManager
        ->expects($this->any())
        ->method('persist')
        ->with($friendEntity)
        ->will($this->returnValue(null));
    return $entityManager;
}
</code>```

And in my test:

```<code>/**
 * Test add friend when friend pending
 */
public function testAddFriendPending()
{
    $friendEntity = new Entity\Friend($this->friend, $this->user);
    $entityManager = $this->getEntityManager($friendEntity);
    $pendingRequest = new FriendService($entityManager);
    /** @var Entity\Friend $lastInsert */
    $lastInsert = $pendingRequest->addFriend($this->friend, $this->user);
    $lastInsert->setId(1);
    $friendAddRequest = new FriendService($entityManager);
    $friendAddRequest->addFriend($this->user, $this->friend);
    $response = $friendAddRequest->getStatus();
    $this->assertEquals(Entity\Friend::FRIEND_ADD_STATUS_COMPLETED, $response);
}
</code>```

EDIT

Still receiving errors:

```<code>vendor/phpunit/phpunit/phpunit src/NalabTnahsarp/FriendFollowerBundle/Tests/Service/
PHPUnit 5.7.21 by Sebastian Bergmann and contributors.

EE                                                                  2 / 2 (100%)

Time: 102 ms, Memory: 4.00MB

There were 2 errors:

1) NalabTnahsarp\FriendFollowerBundle\Tests\Service\FriendTest::testAddFriendNotPending
Error: Call to a member function getUnitOfWork() on null

/Users/Sites/app/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:194
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:140
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:63
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Tests/Service/FriendTest.php:43

2) NalabTnahsarp\FriendFollowerBundle\Tests\Service\FriendTest::testAddFriendPending
Error: Call to a member function getUnitOfWork() on null

/Users/Sites/app/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:194
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:140
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:63
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Tests/Service/FriendTest.php:57
</code>```

答:
I suppose you want to check that the persisted entity has some specific values set and of course is the right type.

You should add this to the persist method for the entity manager like this:

If persist() is only called once you have it easy:

```<code>$entityManager
    ->expects($this->once())
    ->method('persist')
    ->with($theEntityYouExpectWithAllValues)
    ->will($this->returnValue(null));
</code>```

With more sophisticated expectations:

```<code>$entityManager
    ->expects($this->once())
    ->method('persist')
    ->willReturnCallback(function($entityToTest){
        $this->assertInstanceOf(EntityClass::class, $entityToTest);
        $this->assertEquals('some_value', $entityToTest->someKey);
    });
</code>```

If it is not the only call to persist() in the tested code you have to use $this->at() instead of once():

```<code>$entityManager
    ->expects($this->at(3)) // 3rd call of any method on manager not just persist
    ->method('persist')
    // ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to unit test my bundle and I want to get unit of work from EventManager Mock. Basically, I want to get the last persisted object. I know in normal application, I can do the same with a EventSubscriber.

What I want to achieve is basically, check status of previous persisted record if its flag is pending, then in next persist, I want to update it to not pending.

Example:

Here's how I get Event Manager:

/**
 * @param Entity\Friend|null $friendEntity
 * @return \Doctrine\ORM\EntityManager|\PHPUnit_Framework_MockObject_MockObject
 */
private function getEntityManager(Entity\Friend $friendEntity = null)
{
    $repository = $this
        ->getMockBuilder('\Doctrine\ORM\EntityRepository')
        ->disableOriginalConstructor()
        ->setMethods(['findBy'])
        ->getMock();
    $repository
        ->expects($this->any())
        ->method('findBy')
        ->will($this->returnValue(null));

    /** @var \Doctrine\ORM\EntityManager|\PHPUnit_Framework_MockObject_MockObject $entityManager */
    $entityManager = $this
        ->getMockBuilder('\Doctrine\ORM\EntityManager')
        ->setMethods(['getRepository', 'getUnitOfWork', 'persist'])
        ->disableOriginalConstructor()
        ->getMock();
    $entityManager
        ->expects($this->any())
        ->method('getRepository')
        ->will($this->returnValue($repository));
    $entityManager
        ->expects($this->any())
        ->method('getUnitOfWork')
        ->will($this->returnValue($repository));
    $entityManager
        ->expects($this->any())
        ->method('persist')
        ->with($friendEntity)
        ->will($this->returnValue(null));
    return $entityManager;
}

And in my test:

/**
 * Test add friend when friend pending
 */
public function testAddFriendPending()
{
    $friendEntity = new Entity\Friend($this->friend, $this->user);
    $entityManager = $this->getEntityManager($friendEntity);
    $pendingRequest = new FriendService($entityManager);
    /** @var Entity\Friend $lastInsert */
    $lastInsert = $pendingRequest->addFriend($this->friend, $this->user);
    $lastInsert->setId(1);
    $friendAddRequest = new FriendService($entityManager);
    $friendAddRequest->addFriend($this->user, $this->friend);
    $response = $friendAddRequest->getStatus();
    $this->assertEquals(Entity\Friend::FRIEND_ADD_STATUS_COMPLETED, $response);
}

EDIT

Still receiving errors:

vendor/phpunit/phpunit/phpunit src/NalabTnahsarp/FriendFollowerBundle/Tests/Service/
PHPUnit 5.7.21 by Sebastian Bergmann and contributors.

EE                                                                  2 / 2 (100%)

Time: 102 ms, Memory: 4.00MB

There were 2 errors:

1) NalabTnahsarp\FriendFollowerBundle\Tests\Service\FriendTest::testAddFriendNotPending
Error: Call to a member function getUnitOfWork() on null

/Users/Sites/app/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:194
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:140
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:63
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Tests/Service/FriendTest.php:43

2) NalabTnahsarp\FriendFollowerBundle\Tests\Service\FriendTest::testAddFriendPending
Error: Call to a member function getUnitOfWork() on null

/Users/Sites/app/vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php:194
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:140
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Service/Friend.php:63
/Users/Sites/app/src/NalabTnahsarp/FriendFollowerBundle/Tests/Service/FriendTest.php:57

Body:
I suppose you want to check that the persisted entity has some specific values set and of course is the right type.

You should add this to the persist method for the entity manager like this:

If persist() is only called once you have it easy:

$entityManager
    ->expects($this->once())
    ->method('persist')
    ->with($theEntityYouExpectWithAllValues)
    ->will($this->returnValue(null));

With more sophisticated expectations:

$entityManager
    ->expects($this->once())
    ->method('persist')
    ->willReturnCallback(function($entityToTest){
        $this->assertInstanceOf(EntityClass::class, $entityToTest);
        $this->assertEquals('some_value', $entityToTest->someKey);
    });

If it is not the only call to persist() in the tested code you have to use $this->at() instead of once():

$entityManager
    ->expects($this->at(3)) // 3rd call of any method on manager not just persist
    ->method('persist')
    // ...


问:
Using Leaflet, how to get polyline popup coordinates and add it to the popup content
I'm using Leaflet library for maps and I run into a small problem:

I have simple non-geographical map and with a simple line connecting two coordinates. When someone clicks anywhere on the line, a Popup opens up. I am trying to display the coordinates of the clicked spot in the popup itself.

I tried doing something like this, but I'm always getting undefined error.

```<code>L.polyline([xy([296.4, -235.1]), xy([1426.3, 100.3])], {color: 'red'}).bindPopup('Coordinates: ' + L.getPopup.getLatLng).addTo(myLayerGroup);
</code>```

I understand that I'm supposed to call the getLatLng() method on the popup itself, but how do I do that exactly? How to reference the popup itself since I never defined it as a separate variable? I'm having hundreds of lines on my map so declaring each line and popup as a separate variable is not really the optimal solution.

答:
So I needed a way to get coordinates of the popup which appears above polylines and display it in the popup itself. Here is my solution, for someone finding this problem in future.

Heres the premise. I wanted to display city markers and polyline routes on the map at the same time. Easiest way would be to add them both to the same feature group called cities and just simply display it on map. This of course works, but catching popups on cities group to change them would result in changing popups from both markers and polylines. I didn't want to do that. I only wanted to change popups from polylines.

The solution was to separate city markers and polyline routes into two groups, cities and cityRoutes. Add cityRoutes to cities to display them both on map at the same time, but in addition add cityRoutes to polylines as well. This time I could catch the popup open event from the group polylines and change the popup content of polyline, but keep the city markers popups unchanged.

```<code>var polylines = new L.FeatureGroup(); // Declare a group in which to store all polylines.
var cities = new L.FeatureGroup(); // Declare a group in which to store all cities.
var cityRoutes = new L.FeatureGroup(); // Declare a group in which to store all city routes.
cityRoutes.addTo(cities);
cityRoutes.addTo(polylines);

// Add a couple of markers
L.marker([-229.0, -267.8]).bindPopup('City 1').addTo(cities);
L.marker([229.0, -67.8]).bindPopup('City 2').addTo(cities);

// Add a route
L.polyline([-229.0, -267.8], [229.0, -67.8]).bindPopup('Route 1').addTo(cityRoutes);

// Catch event when popup opens above polyline and add its coordinates to its content
polylines.on('popupopen', function (e) {
    var popup = e.popup;
    popup.setContent('Coordinates: ' +  popup.getLatLng().lng + ' / ' + popup.getLatLng().lat);
});
</code>```

Now of course, I could have just caught popup events on cityRoutes and it would be a shorter solution in this simple example, but in my case, I had multiple route groups like islandRoutes, cityRoutes, shipRoutes etc. This means I would have had to catch the popup event above each route separately. That adds much of redundant code. Easier solution was to just add all the routes to the third feature group called polylines and catch the events on that group.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Leaflet library for maps and I run into a small problem:

I have simple non-geographical map and with a simple line connecting two coordinates. When someone clicks anywhere on the line, a Popup opens up. I am trying to display the coordinates of the clicked spot in the popup itself.

I tried doing something like this, but I'm always getting undefined error.

L.polyline([xy([296.4, -235.1]), xy([1426.3, 100.3])], {color: 'red'}).bindPopup('Coordinates: ' + L.getPopup.getLatLng).addTo(myLayerGroup);

I understand that I'm supposed to call the getLatLng() method on the popup itself, but how do I do that exactly? How to reference the popup itself since I never defined it as a separate variable? I'm having hundreds of lines on my map so declaring each line and popup as a separate variable is not really the optimal solution.

Body:
So I needed a way to get coordinates of the popup which appears above polylines and display it in the popup itself. Here is my solution, for someone finding this problem in future.

Heres the premise. I wanted to display city markers and polyline routes on the map at the same time. Easiest way would be to add them both to the same feature group called cities and just simply display it on map. This of course works, but catching popups on cities group to change them would result in changing popups from both markers and polylines. I didn't want to do that. I only wanted to change popups from polylines.

The solution was to separate city markers and polyline routes into two groups, cities and cityRoutes. Add cityRoutes to cities to display them both on map at the same time, but in addition add cityRoutes to polylines as well. This time I could catch the popup open event from the group polylines and change the popup content of polyline, but keep the city markers popups unchanged.

var polylines = new L.FeatureGroup(); // Declare a group in which to store all polylines.
var cities = new L.FeatureGroup(); // Declare a group in which to store all cities.
var cityRoutes = new L.FeatureGroup(); // Declare a group in which to store all city routes.
cityRoutes.addTo(cities);
cityRoutes.addTo(polylines);

// Add a couple of markers
L.marker([-229.0, -267.8]).bindPopup('City 1').addTo(cities);
L.marker([229.0, -67.8]).bindPopup('City 2').addTo(cities);

// Add a route
L.polyline([-229.0, -267.8], [229.0, -67.8]).bindPopup('Route 1').addTo(cityRoutes);

// Catch event when popup opens above polyline and add its coordinates to its content
polylines.on('popupopen', function (e) {
    var popup = e.popup;
    popup.setContent('Coordinates: ' +  popup.getLatLng().lng + ' / ' + popup.getLatLng().lat);
});

Now of course, I could have just caught popup events on cityRoutes and it would be a shorter solution in this simple example, but in my case, I had multiple route groups like islandRoutes, cityRoutes, shipRoutes etc. This means I would have had to catch the popup event above each route separately. That adds much of redundant code. Easier solution was to just add all the routes to the third feature group called polylines and catch the events on that group.


问:
Excel VBA: Is there a faster way to do a running total?
I'm using a countif function with an expanding range and auto-filling to get the running totals and was wondering if there was a better way to go about it.

COUNTIF($A$2:A2,A2) + autofill down

There seems to be no problem if there's just a few thousand rows, but when it gets to 10k+ rows it slows down considerably.

I searched online for some clues, but all the "faster" ways had to do with the TOTAL count, not a RUNNING count.

Thank you for your help!

答:
You can use a Dictionary, faster on large data because it uses an efficient search algorithm (binary search). On large datasets this should make a noticeable difference.

```<code>Sub RunningCounts()
  Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
  Dim r As Range: Set r = Sheet1.Range("A2", Sheet1.Cells(Sheet1.Rows.count, "A").End(xlUp))
  Dim values: values = r.Value2
  Dim i As Long
  For i = LBound(values, 1) To UBound(values, 1)
     dict(values(i, 1)) = dict(values(i, 1)) + 1
     values(i, 1) = dict(values(i, 1))
  Next
  r.Offset(, 1).value = values ' <-- writes results on next column. change as needed
End Sub
</code>```

Body:
You can use a Dictionary, faster on large data because it uses an efficient search algorithm (binary search). On large datasets this should make a noticeable difference.

Sub RunningCounts()
  Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
  Dim r As Range: Set r = Sheet1.Range("A2", Sheet1.Cells(Sheet1.Rows.count, "A").End(xlUp))
  Dim values: values = r.Value2
  Dim i As Long
  For i = LBound(values, 1) To UBound(values, 1)
     dict(values(i, 1)) = dict(values(i, 1)) + 1
     values(i, 1) = dict(values(i, 1))
  Next
  r.Offset(, 1).value = values ' <-- writes results on next column. change as needed
End Sub


问:
Creating a declaration file in TypeScript to use a JavaScript library
I need to create a declaration type file in TypeScript to be able to use an old JavaScript library I'm using.

Here's the JavaScript library

Module.js

```<code>var GridManager = function(x) {
  this.foo = function () {
  }
}
</code>```

When I need to instantiate GridManager in JavaScript I do this

```<code>let gridManager = new GridManager(4);
</code>```

Now I need to create a declaration file .d.ts in TypeScript

TypeScript.d.ts

```<code>declare var GridManager: {
    foo(): void;
}
</code>```

When I create a GridManager in the .ts file I get the following error

Cannot use 'new' with an expression whose type lacks a call or
  construct signature

TypeScript.ts

```<code>export class View {

  gridManager: GridManager;

  constructor() {
    this.gridManager = new GridManager(4);
  }

}
</code>```

Can anyone help me with this?

答:
Change your .d.ts file as

```<code>export class GridManager {
    constructor(x:Number)
}
</code>```

foo is hidden from the scope of your class

Body:
I need to create a declaration type file in TypeScript to be able to use an old JavaScript library I'm using.

Here's the JavaScript library

Module.js

var GridManager = function(x) {
  this.foo = function () {
  }
}

When I need to instantiate GridManager in JavaScript I do this

let gridManager = new GridManager(4);

Now I need to create a declaration file .d.ts in TypeScript

TypeScript.d.ts

declare var GridManager: {
    foo(): void;
}

When I create a GridManager in the .ts file I get the following error

Cannot use 'new' with an expression whose type lacks a call or
  construct signature

TypeScript.ts

export class View {

  gridManager: GridManager;

  constructor() {
    this.gridManager = new GridManager(4);
  }

}

Can anyone help me with this?

Body:
Change your .d.ts file as

export class GridManager {
    constructor(x:Number)
}

foo is hidden from the scope of your class


问:
LinearLayoutManager on some device frozen app
Hello I have a BIG problem with my app.

I Use recyclerview for show info with images and text's

it's ok. RecyclerView work good... on Xiaomi Mi3

but I was tryed launch app on Xiaomi Mi4 and app frozen.

I try coment some lines and I know so app frozen on this line

```<code>listdata.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
</code>```

listtada is  private RecyclerView listdata;

when I launch app in Mi4 and active command is ↑ using CPU increase on 40% or more and app standing on line, not go next.

I don't know how it's in Mi4 difference from Mi3. android 6.0.1 ..

have you some ideas? or if want more info write, I send..

______________________________more code________________________________________

```<code>adapter = new MyRecyclerViewAdapter(IndexActivity.this, list_kone);
                        listdata.setAdapter(adapter);
                        listdata.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
</code>```

my myRecyclerViewAdapter

```<code>ublic class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
private List<Kon> listKone;
private Activity mact;

public MyRecyclerViewAdapter(Activity mact, List<Kon> listKone) {
    this.listKone = listKone;
    this.mact = mact;
}

@Override
public int getItemCount() {
    return (null != listKone ? listKone.size() : 0);
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.dlazdica_item, null);
    CustomViewHolder viewHolder = new CustomViewHolder(view);

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onItemClickListener.onItemClick(listKone.get(i));
        }
    };

    view.setOnClickListener(listener);

    return viewHolder;
}

@Override
public void onBindViewHolder(final CustomViewHolder customViewHolder, final int i) {
    final Kon feedItem = listKone.get(i);

    mact.runOnUiThread (new Thread(new Runnable() {
        public void run() {
            customViewHolder.viewpager.setAdapter(new SamplePagerAdapter(listKone,i,mact));
            customViewHolder.indicator.setViewPager(customViewHolder.viewpager);
        }
    }));

    customViewHolder.txtnadpis.setText(listKone.get(i).getJazyky(0).getNadpis());
    // txtvhodnypre.setText(listKone.get(i).getNarodenie());
    customViewHolder.txtcena.setText(Integer.toString(listKone.get(i).getCena()));

    try {
        Calendar cal = Calendar.getInstance();
        String[] arrdatum = listKone.get(i).getNarodenie().split("-");
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(arrdatum[2]));
        cal.set(Calendar.MONTH, Integer.parseInt(arrdatum[1]));
        cal.set(Calendar.YEAR, Integer.parseInt(arrdatum[0]));
        Date narodenie = cal.getTime();
        customViewHolder.txtvek.setText(Integer.toString((int) ((Calendar.getInstance().getTime().getTime() - narodenie.getTime()) / 1000 / 60 / 60 / 24 / 365.25)));
    } catch (Exception e){
        customViewHolder.txtvek.setText("neuvedené");
    }

    customViewHolder.txtheigh.setText(Integer.toString(listKone.get(i).getVyska())+"cm");
    //   txtlokalina.setText(Integer.toString(listKone.get(i).getCena()));
    customViewHolder.cutpopis.setText(listKone.get(i).getJazyky(0).getPopis());
    String[] arrplemena = mact.getResources().getStringArray(R.array.plemena);
    customViewHolder.txtplemeno.setText(arrplemena[listKone.get(i).getPlemeno()]);
    // Then later, when you want to display image
}

class CustomViewHolder extends RecyclerView.ViewHolder {

    TextView txtnadpis,txtvhodnypre,txtcena,txtvek,txtheigh,txtplemeno,txtlokalina,cutpopis;
    ViewPager viewpager;
    CircleIndicator indicator;

    CustomViewHolder(View view) {
        super(view);

        viewpager = (ViewPager) itemView.findViewById(R.id.viewPager2);
        indicator = (CircleIndicator) itemView.findViewById(R.id.indicator);

        txtnadpis = (TextView)itemView.findViewById(R.id.nadpis);
        txtvhodnypre = (TextView)itemView.findViewById(R.id.vhodnyppre);
        txtcena = (TextView)itemView.findViewById(R.id.txt_cena);
        txtvek = (TextView)itemView.findViewById(R.id.txt_vek);
        txtheigh = (TextView)itemView.findViewById(R.id.txtheigh);
        txtplemeno = (TextView)itemView.findViewById(R.id.txt_breed);
        txtlokalina = (TextView)itemView.findViewById(R.id.txt_lokalita);
        cutpopis = (TextView)itemView.findViewById(R.id.cutpopis);

    }
}

public interface OnItemClickListener {
    void onItemClick(Kon item);
}

private OnItemClickListener onItemClickListener;
public OnItemClickListener getOnItemClickListener() {
    return onItemClickListener;
}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}
</code>```

}

答: I checked permissionsand on Xiaomi Mi4 I haven't allowed all. </p>

Body:
Hello I have a BIG problem with my app.

I Use recyclerview for show info with images and text's

it's ok. RecyclerView work good... on Xiaomi Mi3

but I was tryed launch app on Xiaomi Mi4 and app frozen.

I try coment some lines and I know so app frozen on this line

listdata.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

listtada is  private RecyclerView listdata;

when I launch app in Mi4 and active command is ↑ using CPU increase on 40% or more and app standing on line, not go next.

I don't know how it's in Mi4 difference from Mi3. android 6.0.1 ..

have you some ideas? or if want more info write, I send..

______________________________more code________________________________________

adapter = new MyRecyclerViewAdapter(IndexActivity.this, list_kone);
                        listdata.setAdapter(adapter);
                        listdata.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

my myRecyclerViewAdapter

ublic class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
private List<Kon> listKone;
private Activity mact;

public MyRecyclerViewAdapter(Activity mact, List<Kon> listKone) {
    this.listKone = listKone;
    this.mact = mact;
}

@Override
public int getItemCount() {
    return (null != listKone ? listKone.size() : 0);
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.dlazdica_item, null);
    CustomViewHolder viewHolder = new CustomViewHolder(view);

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onItemClickListener.onItemClick(listKone.get(i));
        }
    };

    view.setOnClickListener(listener);

    return viewHolder;
}

@Override
public void onBindViewHolder(final CustomViewHolder customViewHolder, final int i) {
    final Kon feedItem = listKone.get(i);

    mact.runOnUiThread (new Thread(new Runnable() {
        public void run() {
            customViewHolder.viewpager.setAdapter(new SamplePagerAdapter(listKone,i,mact));
            customViewHolder.indicator.setViewPager(customViewHolder.viewpager);
        }
    }));

    customViewHolder.txtnadpis.setText(listKone.get(i).getJazyky(0).getNadpis());
    // txtvhodnypre.setText(listKone.get(i).getNarodenie());
    customViewHolder.txtcena.setText(Integer.toString(listKone.get(i).getCena()));

    try {
        Calendar cal = Calendar.getInstance();
        String[] arrdatum = listKone.get(i).getNarodenie().split("-");
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(arrdatum[2]));
        cal.set(Calendar.MONTH, Integer.parseInt(arrdatum[1]));
        cal.set(Calendar.YEAR, Integer.parseInt(arrdatum[0]));
        Date narodenie = cal.getTime();
        customViewHolder.txtvek.setText(Integer.toString((int) ((Calendar.getInstance().getTime().getTime() - narodenie.getTime()) / 1000 / 60 / 60 / 24 / 365.25)));
    } catch (Exception e){
        customViewHolder.txtvek.setText("neuvedené");
    }

    customViewHolder.txtheigh.setText(Integer.toString(listKone.get(i).getVyska())+"cm");
    //   txtlokalina.setText(Integer.toString(listKone.get(i).getCena()));
    customViewHolder.cutpopis.setText(listKone.get(i).getJazyky(0).getPopis());
    String[] arrplemena = mact.getResources().getStringArray(R.array.plemena);
    customViewHolder.txtplemeno.setText(arrplemena[listKone.get(i).getPlemeno()]);
    // Then later, when you want to display image
}

class CustomViewHolder extends RecyclerView.ViewHolder {

    TextView txtnadpis,txtvhodnypre,txtcena,txtvek,txtheigh,txtplemeno,txtlokalina,cutpopis;
    ViewPager viewpager;
    CircleIndicator indicator;

    CustomViewHolder(View view) {
        super(view);

        viewpager = (ViewPager) itemView.findViewById(R.id.viewPager2);
        indicator = (CircleIndicator) itemView.findViewById(R.id.indicator);

        txtnadpis = (TextView)itemView.findViewById(R.id.nadpis);
        txtvhodnypre = (TextView)itemView.findViewById(R.id.vhodnyppre);
        txtcena = (TextView)itemView.findViewById(R.id.txt_cena);
        txtvek = (TextView)itemView.findViewById(R.id.txt_vek);
        txtheigh = (TextView)itemView.findViewById(R.id.txtheigh);
        txtplemeno = (TextView)itemView.findViewById(R.id.txt_breed);
        txtlokalina = (TextView)itemView.findViewById(R.id.txt_lokalita);
        cutpopis = (TextView)itemView.findViewById(R.id.cutpopis);

    }
}

public interface OnItemClickListener {
    void onItemClick(Kon item);
}

private OnItemClickListener onItemClickListener;
public OnItemClickListener getOnItemClickListener() {
    return onItemClickListener;
}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

}


问:
NameError during python xml parsing
```<code>>>> stringx
'<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>'
>>>
>>>
>>> e = xml.etree.ElementTree.fromstring(stringx)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xml' is not defined
</code>```

Can someone suggest what am I missing here? is it the xml code or the way I am trying to parse?

答:
import xml.etree.ElementTree

Looks like you have forgotten this.

Reference the documentation for proper usage.

https://docs.python.org/2/library/xml.etree.elementtree.html

Edit: Thanks @mzjn. Your are correct. I was just passing by and notice OP forgot the import. Didn't actually try it out. Credit goes to you :)

Title: NameError during python xml parsing

Body:
>>> stringx
'<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>'
>>>
>>>
>>> e = xml.etree.ElementTree.fromstring(stringx)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xml' is not defined

Can someone suggest what am I missing here? is it the xml code or the way I am trying to parse?


问:
ORDER BY and Aliased COUNT() in One query
```<code>          POSTS
[ id -   post   -  content ]
----------------------------
[ 1  -  1post1  - 1content1]
[ 2  -  1post2  - 2content2]

        VOTES
   [ id -  pid]
   ------------
   [ 1  -    1]
   [ 2  -    1]
   [ 3  -    1]
   [ 4  -    2]
   [ 5  -    2]

1post1 = 3 votes
2post2 = 2 votes
</code>```

When i try this query

```<code>$query = "SELECT a.title, a.content, b.COUNT(id) FROM posts a, votes b WHERE id = :id ORDER BY b.COUNT(id)";
</code>```

it doesn't work and gives me this error

```<code>FUNCTION b.COUNT does not exist. Check the 'Function Name Parsing and Resolution
</code>```

Is there is a better way to do this? I thought about using UNION ALL to be like this

```<code>$query = "SELECT title, content, COUNT(id) FROM posts WHERE id = :id
UNION ALL
SELECT COUNT(id) FROM votes WHERE pid = :id";
</code>```

but the problem here i won't be able to use ORDER BY COUNT(id) for the first part, Which is what i want to order it depending on the second part.

答:
It looks like there's a relation between posts/votes so the join is needed.  a cross join which is what you're doing now seems incorrect.  as it would take the results (2) from post and (5) from results and multiply them giving you 10 records.  You need a join so that the postID from votes is referenced.

count is a function so it gets used as count(table.field) to count values in a  specific column or count(*) just to count the number of records in a table.

When joining two tables; be sure to alias the columns (in your case ID exists in both so specifying what table ID you're after matters.

when using an aggregate such as COUNT() a group by is needed if you have non-aggregated fields (Such as ID or post in your example)

So maybe... (ANSI 92)

```<code>SELECT P.ID, P.Post, count(V.ID) as No_Votes
FROM Posts P
INNER JOIN Votes V
 on V.PID = P.ID
WHERE  P.ID = :id
GROUP BY P.ID, P.Post
ORDER BY No_votes  -- due to order of operation we can use the column alias in an order by.
</code>```

Or... (ANSI 87)

```<code>SELECT P.ID, P.Post, count(V.ID) as No_Votes
FROM Posts P, Votes V
WHERE V.PID = P.ID
  AND P.ID = :id
GROUP BY P.ID, P.Post
ORDER BY No_votes
</code>```

Maybe you want all posts even those w/o votes so perhaps you need to use an OUTER JOin (Right /left instead of inner depending on what you're after: your example and expected results don't show anything but an inner so I started here)

Body:
          POSTS
[ id -   post   -  content ]
----------------------------
[ 1  -  1post1  - 1content1]
[ 2  -  1post2  - 2content2]

        VOTES
   [ id -  pid]
   ------------
   [ 1  -    1]
   [ 2  -    1]
   [ 3  -    1]
   [ 4  -    2]
   [ 5  -    2]

1post1 = 3 votes
2post2 = 2 votes

When i try this query

$query = "SELECT a.title, a.content, b.COUNT(id) FROM posts a, votes b WHERE id = :id ORDER BY b.COUNT(id)";

it doesn't work and gives me this error

FUNCTION b.COUNT does not exist. Check the 'Function Name Parsing and Resolution

Is there is a better way to do this? I thought about using UNION ALL to be like this

$query = "SELECT title, content, COUNT(id) FROM posts WHERE id = :id
UNION ALL
SELECT COUNT(id) FROM votes WHERE pid = :id";

but the problem here i won't be able to use ORDER BY COUNT(id) for the first part, Which is what i want to order it depending on the second part.

Body:
It looks like there's a relation between posts/votes so the join is needed.  a cross join which is what you're doing now seems incorrect.  as it would take the results (2) from post and (5) from results and multiply them giving you 10 records.  You need a join so that the postID from votes is referenced.

count is a function so it gets used as count(table.field) to count values in a  specific column or count(*) just to count the number of records in a table.

When joining two tables; be sure to alias the columns (in your case ID exists in both so specifying what table ID you're after matters.

when using an aggregate such as COUNT() a group by is needed if you have non-aggregated fields (Such as ID or post in your example)

So maybe... (ANSI 92)

SELECT P.ID, P.Post, count(V.ID) as No_Votes
FROM Posts P
INNER JOIN Votes V
 on V.PID = P.ID
WHERE  P.ID = :id
GROUP BY P.ID, P.Post
ORDER BY No_votes  -- due to order of operation we can use the column alias in an order by.

Or... (ANSI 87)

SELECT P.ID, P.Post, count(V.ID) as No_Votes
FROM Posts P, Votes V
WHERE V.PID = P.ID
  AND P.ID = :id
GROUP BY P.ID, P.Post
ORDER BY No_votes

Maybe you want all posts even those w/o votes so perhaps you need to use an OUTER JOin (Right /left instead of inner depending on what you're after: your example and expected results don't show anything but an inner so I started here)


问:
PowerShell directly vs. SQL Agent PowerShell Job Steps
If I run this 3 line script in Powershell (Run As Administrator, and my domain account is a local administrator on MyRemoteServer), it works as expected (note that there is a dollar sign in the service name that I had to escape with a back tick):

```<code>Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Stop-Service -Force}
get-service -Name "AOS60`$01" -ComputerName "MyRemoteServer" | Format-Table -Property MachineName, Status, Name, DisplayName -auto
Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Start-Service}
</code>```

[Step 2 is to provide proof that the service actually has a status of "Stopped" after step 1. Once successfully converted to an Agent Job, step 2 will actually invoke a stored procedure that does a series of database restores.]

If I put these statements into SQL Agent (SQL Server 2012 SP2) as job steps and start the job, the job crashes (it doesn't merely fail, it wants to invoke the debugger) at the first step. The domain service account that runs the SQL Agent Service was allegedly granted the necessary permissions on MyRemoteServer by our Operations group.

The job script encountered the following errors. These errors did not stop the script:

Unhandled Exception: System.FormatException: Index (zero based) must
  be greater than or equal to zero and less than the size of the
  argument list.    at
  System.Text.StringBuilder.AppendFormat(IFormatProvider provider,
  String format, Object[] args)    at
  System.String.Format(IFormatProvider provider, String format, Object[]
  args)    at
  Microsoft.SqlServer.Management.PowerShell.Res.GetString(String key,
  Object arg0)    at
  Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.GetErrorRecordMessage(ErrorRecord
  errorRecord)    at
  Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.HandleAgentJob(RunspaceConfiguration
  config)    at
  Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.Main(String[]
  args)

I scripted out the job below for reference. Note that it fails even if I leave out the @output_file_name, so the problem isn't writing to the output file but in executing the step itself.

```<code>USE [msdb]
GO

/****** Object:  Job [Test stopping and restarting AX]    Script Date: 6/21/2017 1:49:30 PM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]    Script Date: 6/21/2017 1:49:30 PM ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Test stopping and restarting AX',
        @enabled=1,
        @notify_level_eventlog=0,
        @notify_level_email=0,
        @notify_level_netsend=0,
        @notify_level_page=0,
        @delete_level=0,
        @description=N'No description available.',
        @category_name=N'[Uncategorized (Local)]',
        @owner_login_name=N'ROGUE\amfreeman', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Synchronously Stop AX Service on DEVAOS2]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Synchronously Stop AX Service on DEVAOS2',
        @step_id=1,
        @cmdexec_success_code=0,
        @on_success_action=3,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'PowerShell',
        @command=N'Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Stop-Service -Force}',
        @database_name=N'master',
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Synchronously_Stop_AX_Service_on_DEVAOS2.txt',
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Get status of  AX Service on DEVAOS2]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Get status of  AX Service on DEVAOS2',
        @step_id=2,
        @cmdexec_success_code=0,
        @on_success_action=3,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'PowerShell',
        @command=N'get-service -Name "AOS60`$01" -ComputerName "MyRemoteServer" | Format-Table -Property MachineName, Status, Name, DisplayName -auto',
        @database_name=N'master',
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Get_status_of__AX_Service_on_DEVAOS2.txt',
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Synchronously Start AX Service on MyRemoteServer]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Synchronously Start AX Service on MyRemoteServer',
        @step_id=3,
        @cmdexec_success_code=0,
        @on_success_action=1,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'PowerShell',
        @command=N'Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Start-Service}',
        @database_name=N'master',
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Synchronously_Start_AX_Service_on_MyRemoteServer.txt',
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
</code>```

How I can get the SQL Agent Job to run properly?

答:
There were two issues:

1) Note the word "allegedly" in this sentence in my original post: "The domain service account that runs the SQL Agent Service was allegedly granted the necessary permissions on MyRemoteServer by our Operations group." As it turns out, all of the required permissions had not been granted to the domain account that runs the SQL Server Agent service.

2) I took the advice of @NedOtter (and from various other blogs and Stack posts) and converted to using PowerShell through CmdExec. I don't know that this was necessary, but it sure seems to be the consensus on the way to go.

I used two job steps, with the following in the @command parameters:

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe "Invoke-Command -ComputerName ''MyRemoteServer'' -ScriptBlock{Get-Service -Name ''AOS60$01'' | Stop-Service -Force}"
C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe "Invoke-Command -ComputerName ''MyRemoteServer'' -ScriptBlock{Get-Service -Name ''AOS60$01'' | Start-Service}"
</code>```

These combine to synchronously stop and then start the service. I then inserted a job step in between that restores the databases in this test instance from my production backups.

Body:
If I run this 3 line script in Powershell (Run As Administrator, and my domain account is a local administrator on MyRemoteServer), it works as expected (note that there is a dollar sign in the service name that I had to escape with a back tick):

Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Stop-Service -Force}
get-service -Name "AOS60`$01" -ComputerName "MyRemoteServer" | Format-Table -Property MachineName, Status, Name, DisplayName -auto
Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Start-Service}

[Step 2 is to provide proof that the service actually has a status of "Stopped" after step 1. Once successfully converted to an Agent Job, step 2 will actually invoke a stored procedure that does a series of database restores.]

If I put these statements into SQL Agent (SQL Server 2012 SP2) as job steps and start the job, the job crashes (it doesn't merely fail, it wants to invoke the debugger) at the first step. The domain service account that runs the SQL Agent Service was allegedly granted the necessary permissions on MyRemoteServer by our Operations group.

The job script encountered the following errors. These errors did not stop the script:

Unhandled Exception: System.FormatException: Index (zero based) must
  be greater than or equal to zero and less than the size of the
  argument list.    at
  System.Text.StringBuilder.AppendFormat(IFormatProvider provider,
  String format, Object[] args)    at
  System.String.Format(IFormatProvider provider, String format, Object[]
  args)    at
  Microsoft.SqlServer.Management.PowerShell.Res.GetString(String key,
  Object arg0)    at
  Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.GetErrorRecordMessage(ErrorRecord
  errorRecord)    at
  Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.HandleAgentJob(RunspaceConfiguration
  config)    at
  Microsoft.SqlServer.Management.PowerShell.SqlPowerShell.Main(String[]
  args)

I scripted out the job below for reference. Note that it fails even if I leave out the @output_file_name, so the problem isn't writing to the output file but in executing the step itself.

USE [msdb]
GO

/****** Object:  Job [Test stopping and restarting AX]    Script Date: 6/21/2017 1:49:30 PM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]    Script Date: 6/21/2017 1:49:30 PM ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Test stopping and restarting AX',
        @enabled=1,
        @notify_level_eventlog=0,
        @notify_level_email=0,
        @notify_level_netsend=0,
        @notify_level_page=0,
        @delete_level=0,
        @description=N'No description available.',
        @category_name=N'[Uncategorized (Local)]',
        @owner_login_name=N'ROGUE\amfreeman', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Synchronously Stop AX Service on DEVAOS2]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Synchronously Stop AX Service on DEVAOS2',
        @step_id=1,
        @cmdexec_success_code=0,
        @on_success_action=3,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'PowerShell',
        @command=N'Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Stop-Service -Force}',
        @database_name=N'master',
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Synchronously_Stop_AX_Service_on_DEVAOS2.txt',
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Get status of  AX Service on DEVAOS2]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Get status of  AX Service on DEVAOS2',
        @step_id=2,
        @cmdexec_success_code=0,
        @on_success_action=3,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'PowerShell',
        @command=N'get-service -Name "AOS60`$01" -ComputerName "MyRemoteServer" | Format-Table -Property MachineName, Status, Name, DisplayName -auto',
        @database_name=N'master',
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Get_status_of__AX_Service_on_DEVAOS2.txt',
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Synchronously Start AX Service on MyRemoteServer]    Script Date: 6/21/2017 1:49:30 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Synchronously Start AX Service on MyRemoteServer',
        @step_id=3,
        @cmdexec_success_code=0,
        @on_success_action=1,
        @on_success_step_id=0,
        @on_fail_action=2,
        @on_fail_step_id=0,
        @retry_attempts=0,
        @retry_interval=0,
        @os_run_priority=0, @subsystem=N'PowerShell',
        @command=N'Invoke-Command -ComputerName "MyRemoteServer" -ScriptBlock{Get-Service -Name "AOS60`$01" | Start-Service}',
        @database_name=N'master',
        @output_file_name=N'E:\Microsoft SQL Server\MSSQL11.RELEASE\MSSQL\Log\Test_stopping_and_restarting_AX_$(ESCAPE_SQUOTE(STEPID))_Synchronously_Start_AX_Service_on_MyRemoteServer.txt',
        @flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

How I can get the SQL Agent Job to run properly?

Body:
There were two issues:

1) Note the word "allegedly" in this sentence in my original post: "The domain service account that runs the SQL Agent Service was allegedly granted the necessary permissions on MyRemoteServer by our Operations group." As it turns out, all of the required permissions had not been granted to the domain account that runs the SQL Server Agent service.

2) I took the advice of @NedOtter (and from various other blogs and Stack posts) and converted to using PowerShell through CmdExec. I don't know that this was necessary, but it sure seems to be the consensus on the way to go.

I used two job steps, with the following in the @command parameters:

C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe "Invoke-Command -ComputerName ''MyRemoteServer'' -ScriptBlock{Get-Service -Name ''AOS60$01'' | Stop-Service -Force}"
C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe "Invoke-Command -ComputerName ''MyRemoteServer'' -ScriptBlock{Get-Service -Name ''AOS60$01'' | Start-Service}"

These combine to synchronously stop and then start the service. I then inserted a job step in between that restores the databases in this test instance from my production backups.


问:
Set environment variable in nested batch file
I am trying to factor out a piece of a batch file that sets an environment variable to another batch file. This piece is somewhat involved and I would rather not repeat it in multiple batch files. I won't over-complicate this post with the actual code I'm trying to run in the nested batch file, but will provide a simple example that shows what I'm trying to do and reproduces the problem.

Batch1.cmd

```<code>cmd.exe /c setvar.cmd abc def
set abc
</code>```

setvar.cmd

```<code>set var=%1
set val=%2
set %var%=%val%
</code>```

The error returned for "set abc" in Batch1.cmd is this:

Environment variable abc not defined

I imagine cmd.exe starts up a new environment, because on return to Batch1.cmd, the variable does not exist.

Is there a way I can nest a batch file and keep the environment it creates?

答:
The environment block is not shared between processes. As you are starting a new cmd instance a separate environment block is created, changed and destroyed before returning the control to the current batch file, that will not see any change as it was done in a different process.

Use call setvar.cmd abc def to start the nested batch file in the current process.

Body:
I am trying to factor out a piece of a batch file that sets an environment variable to another batch file. This piece is somewhat involved and I would rather not repeat it in multiple batch files. I won't over-complicate this post with the actual code I'm trying to run in the nested batch file, but will provide a simple example that shows what I'm trying to do and reproduces the problem.

Batch1.cmd

cmd.exe /c setvar.cmd abc def
set abc

setvar.cmd

set var=%1
set val=%2
set %var%=%val%

The error returned for "set abc" in Batch1.cmd is this:

Environment variable abc not defined

I imagine cmd.exe starts up a new environment, because on return to Batch1.cmd, the variable does not exist.

Is there a way I can nest a batch file and keep the environment it creates?


问:
iPhone SDK - Table view, error with spaces
I have little knowledge with the iPhone SKD (don't even know what code it is objective c?). I have so far got a table view working, and then showing content on another nib file once a row clicked.

I have elseif statements for each row, telling them to load a nib file inside the ViewController. However, One row is causing a problem, it crases the app.

```<code>else if ([[array objectAtIndex:indexPath.row] isEqual:@"ASCII Characters"])
    {
        Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"ASCII Characters" bundle:nil];
        [self.navigationController pushViewController:asciicharacters animated:YES];
        [asciicharacters release];

    }
</code>```

Here is an image of the debugger console:

I don't what to do, there is no errors displaying at all. It just crashes the app, if that row is clicked (both on simulator and iPhone). I think is't something to do with the spaces with in the name. This is the only row that has a space. But I need a space otherwise it would look silly. Thanks :)

答:
From the debug dump, it's clear that it simply can't find the NIB file named "ASCII Characters".

If this is happening on both the simulator and the device it's unlikely to be a case sensitivity issue (bearing in mind the fact that iOS devices use a case sensitive file system, whereas (depending on the format) your Mac OS X drive probably isn't case sensitive). As such, I presume the file is simply missing.

Have you checked the relevant directory tree outside of Xcode to ensure that the file is there?

ContentLicense: CC BY-SA 2.5

Body:
I have little knowledge with the iPhone SKD (don't even know what code it is objective c?). I have so far got a table view working, and then showing content on another nib file once a row clicked.

I have elseif statements for each row, telling them to load a nib file inside the ViewController. However, One row is causing a problem, it crases the app.

else if ([[array objectAtIndex:indexPath.row] isEqual:@"ASCII Characters"])
    {
        Asciicharacters *asciicharacters = [[Asciicharacters alloc] initWithNibName:@"ASCII Characters" bundle:nil];
        [self.navigationController pushViewController:asciicharacters animated:YES];
        [asciicharacters release];

    }

Here is an image of the debugger console:

I don't what to do, there is no errors displaying at all. It just crashes the app, if that row is clicked (both on simulator and iPhone). I think is't something to do with the spaces with in the name. This is the only row that has a space. But I need a space otherwise it would look silly. Thanks :)


问:
letsencrypt certbot timeout error
I am getting this weird letsencrypt error while trying to run the command

```<code>$ certbot certonly --standalone --email example@gmail.com --agree-tos -n -d trumporate.com,www.trumporate.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Obtaining a new certificate
Performing the following challenges:
tls-sni-01 challenge for trumporate.com
tls-sni-01 challenge for www.trumporate.com
Waiting for verification...
Cleaning up challenges
Failed authorization procedure. trumporate.com (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Timeout, www.trumporate.com (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Timeout

IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: trumporate.com
   Type:   connection
   Detail: Timeout

   Domain: www.trumporate.com
   Type:   connection
   Detail: Timeout

   To fix these errors, please make sure that your domain name was
   entered correctly and the DNS A record(s) for that domain
   contain(s) the right IP address. Additionally, please check that
   your computer has a publicly routable IP address and that no
   firewalls are preventing the server from communicating with the
   client. If you're using the webroot plugin, you should also verify
   that you are serving files from the webroot path you provided.
</code>```

Right now I have generated the file dhparam using

```<code>$ sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
</code>```

Here is my current nginx conf file

```<code>$ cat /etc/nginx/sites-available/trumporate
server {
    listen 80;
    server_name trumporate.com www.trumporate.com;

    location / {
        include proxy_params;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:5000;
    }
}
</code>```

Not sure where am I going wrong. Should trumporate.com be resolvable on this vm where I am running certbot?

stopped nginx and ran it again, gave the same error

I have registered the domain through route53.
It's got 2 type A records pointing to the elastic IP attached to the ec2 box.
one for the www version and one without it and has 4 NS records and an SOA record which I think were there by default when creating the hosting zone

答:
Should trumporate.com be resolvable on this vm where I am running certbot?

Sounds like your not running the command on the ec2 box you are trying to get the cert on. That would be a problem since standalone spins up a webserver, then tries to hit it externally with the domain you provide. This "proves" you own the domain so to speak. You need to run the command from the ec2 box, and you need to open up the port it runs on to the world via your security group. You can specify the tls-sni port (the one thats failing) with --tls-sni-01-port, but by default its on 443, so you might just need to open port 443.

You also mentioned you are using route53, so you could just use the route53 verifier. This has the advantage of working anywhere, you just need to have the access key/secret set up on the computer you run it on.

```<code>certbot certonly --dns-route53 --domains trumporate.com,www.trumporate.com
</code>```

Title: letsencrypt certbot timeout error

Body:
I am getting this weird letsencrypt error while trying to run the command

$ certbot certonly --standalone --email example@gmail.com --agree-tos -n -d trumporate.com,www.trumporate.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Obtaining a new certificate
Performing the following challenges:
tls-sni-01 challenge for trumporate.com
tls-sni-01 challenge for www.trumporate.com
Waiting for verification...
Cleaning up challenges
Failed authorization procedure. trumporate.com (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Timeout, www.trumporate.com (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Timeout

IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: trumporate.com
   Type:   connection
   Detail: Timeout

   Domain: www.trumporate.com
   Type:   connection
   Detail: Timeout

   To fix these errors, please make sure that your domain name was
   entered correctly and the DNS A record(s) for that domain
   contain(s) the right IP address. Additionally, please check that
   your computer has a publicly routable IP address and that no
   firewalls are preventing the server from communicating with the
   client. If you're using the webroot plugin, you should also verify
   that you are serving files from the webroot path you provided.

Right now I have generated the file dhparam using

$ sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

Here is my current nginx conf file

$ cat /etc/nginx/sites-available/trumporate
server {
    listen 80;
    server_name trumporate.com www.trumporate.com;

    location / {
        include proxy_params;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:5000;
    }
}

Not sure where am I going wrong. Should trumporate.com be resolvable on this vm where I am running certbot?

stopped nginx and ran it again, gave the same error

I have registered the domain through route53.
It's got 2 type A records pointing to the elastic IP attached to the ec2 box.
one for the www version and one without it and has 4 NS records and an SOA record which I think were there by default when creating the hosting zone

Body:
Should trumporate.com be resolvable on this vm where I am running certbot?

Sounds like your not running the command on the ec2 box you are trying to get the cert on. That would be a problem since standalone spins up a webserver, then tries to hit it externally with the domain you provide. This "proves" you own the domain so to speak. You need to run the command from the ec2 box, and you need to open up the port it runs on to the world via your security group. You can specify the tls-sni port (the one thats failing) with --tls-sni-01-port, but by default its on 443, so you might just need to open port 443.

You also mentioned you are using route53, so you could just use the route53 verifier. This has the advantage of working anywhere, you just need to have the access key/secret set up on the computer you run it on.

certbot certonly --dns-route53 --domains trumporate.com,www.trumporate.com


问:
angularjs: How to inject a dependency into a controller
I try to inject a dependency into a controller. I have tried passing  dependencies through an Array, through an inline anonymous function and to use controller.$inject. Nothing works and I'm ready to explode.

Most of the blogs and article that mention dependency injection shows a simple example, where the code passes the $scope and a dependency.... but when I try to replicate the code example nothing works.

There is something that I'm missing. Do I have to instantiate the dependency or how do I pass the dependency?

```<code>var myApp = angular.module('myApp', []);

function MyViewModel() {
    this.theRightAnswer = 'The answer is 42';
}

myApp.controller('myController', ['$scope', 'MyViewModel', function ($scope, MyViewModel) {
        $scope.theAnswer = MyViewModel.theRightAnswer;
    }]);
</code>```

答:
Use either service/ Factory/ provider for that, & then through dependency Injection you can share the functionality in different controllers. Add following line in your code & it'll work as expected.

```<code>myApp.service('MyViewModel', MyViewModel);
</code>```

http://plnkr.co/edit/7ZclGB93Soq5Ce8pFmkQ?p=preview

Body:
I try to inject a dependency into a controller. I have tried passing  dependencies through an Array, through an inline anonymous function and to use controller.$inject. Nothing works and I'm ready to explode.

Most of the blogs and article that mention dependency injection shows a simple example, where the code passes the $scope and a dependency.... but when I try to replicate the code example nothing works.

There is something that I'm missing. Do I have to instantiate the dependency or how do I pass the dependency?

var myApp = angular.module('myApp', []);

function MyViewModel() {
    this.theRightAnswer = 'The answer is 42';
}

myApp.controller('myController', ['$scope', 'MyViewModel', function ($scope, MyViewModel) {
        $scope.theAnswer = MyViewModel.theRightAnswer;
    }]);

Body:
Use either service/ Factory/ provider for that, & then through dependency Injection you can share the functionality in different controllers. Add following line in your code & it'll work as expected.

myApp.service('MyViewModel', MyViewModel);

http://plnkr.co/edit/7ZclGB93Soq5Ce8pFmkQ?p=preview


问:
Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes) in /wp-includes/wp-db.php on line 2413
I'm getting an error when I try to open one of my dashboard pages in my wordpress script

The error message is as follows:

```<code>Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 72 bytes) in
    /home2/liquifac/public_html/grandviewbiz.com/wp-includes/wp-db.php on line 2413
</code>```

I asked around and was told I have to increase the memory_limit to something higher than 256M, so I changed it to 512M and still the same problem.

So could you please tell me how to fix this and what should I do?

答: I have found the solution. The problem was caused by iThemes Security plugin. I turned it off and the errors have gone.

Body:
I'm getting an error when I try to open one of my dashboard pages in my wordpress script

The error message is as follows:

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 72 bytes) in
    /home2/liquifac/public_html/grandviewbiz.com/wp-includes/wp-db.php on line 2413

I asked around and was told I have to increase the memory_limit to something higher than 256M, so I changed it to 512M and still the same problem.

So could you please tell me how to fix this and what should I do?


问:
SQL How to update a column with data from the same table
```<code>ID START_DATE     ADD_DAYS    NEW_DATE
------------------------------------------
1  02/02/2017     5
2  06/24/2017     3
3  07/14/2017     9
4  05/19/2017     12
</code>```

<p>I have the following table and I want to go in and update the column NEW_DATE with data that I read from the table itself. I am struggling to understand the correct MS SQL to achieve that. Any help? </p>

答:
If you can control the schema, it might be worth adding this NEW_DATE column as a calculated column.

```<code>ALTER TABLE table_name ADD NEW_DATE as DATEADD(DAY,ADD_DAYS,START_DATE)
</code>```

That way you don't need to update anything and any changes to add_days or start_date are automatically recalculated

Body:
ID START_DATE     ADD_DAYS    NEW_DATE
------------------------------------------
1  02/02/2017     5
2  06/24/2017     3
3  07/14/2017     9
4  05/19/2017     12

I have the following table and I want to go in and update the column NEW_DATE with data that I read from the table itself. I am struggling to understand the correct MS SQL to achieve that. Any help?

Body:
If you can control the schema, it might be worth adding this NEW_DATE column as a calculated column.

ALTER TABLE table_name ADD NEW_DATE as DATEADD(DAY,ADD_DAYS,START_DATE)

That way you don't need to update anything and any changes to add_days or start_date are automatically recalculated


问:
Cannot import android.support.v7.media
I need to import this to be able to use MediaRouterSelector.

I already updated my Android Support Repository in SDK Manage, but I still can't import this library :/

I want to follow this tutorial:

https://developer.android.com/guide/topics/media/mediarouter.html

So I can add screenshare to my app and connect to my SmartTV.

答:
You've updated Android Support Repository through SDK Manager.

Now you need to import required artifact in your project.

Open the build.gradle file for your application.

Make sure that the repositories section includes a maven section with the "https://maven.google.com" endpoint. For example:

```<code>allprojects {
   repositories {
      jcenter()
      maven {
          url "https://maven.google.com"
      }
   }
}
</code>```

Add the support library to the dependencies section. For example, to add the v4 core-utils library, add the following lines:

```<code>dependencies {
     ...
     compile "com.android.support:mediarouter-v7:25.3.1"
}
</code>```

Take a look, how you should integrate in your project.

Title: Cannot import android.support.v7.media

Body:
You've updated Android Support Repository through SDK Manager.

Now you need to import required artifact in your project.

Open the build.gradle file for your application.

Make sure that the repositories section includes a maven section with the "https://maven.google.com" endpoint. For example:

allprojects {
   repositories {
      jcenter()
      maven {
          url "https://maven.google.com"
      }
   }
}

Add the support library to the dependencies section. For example, to add the v4 core-utils library, add the following lines:

dependencies {
     ...
     compile "com.android.support:mediarouter-v7:25.3.1"
}

Take a look, how you should integrate in your project.


问:
Matplotlib & Jupyter - Same command returns different results in different cells
First Jupyter cell:

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
%matplotlib notebook

plt.figure()
plt.plot((1,2,3))

labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))
</code>```

The ouput is (besides the chart):

Labels are: ['', '', '', '', '', '', '', '', '', '', '']

Now, in another cell, if I run the same code:

```<code>labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))
</code>```

The ouput is:

Labels are: ['', '0.00', '0.25', '0.50', '0.75', '1.00', '1.25', '1.50', '1.75', '2.00', '']

Why the same code, referencing the same Axes, returns different results?

答:
instead of:

```<code>%matplotlib notebook
</code>```

Use:

```<code>%matplotlib inline
</code>```

Body:
First Jupyter cell:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
%matplotlib notebook

plt.figure()
plt.plot((1,2,3))

labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))

The ouput is (besides the chart):

Labels are: ['', '', '', '', '', '', '', '', '', '', '']

Now, in another cell, if I run the same code:

labels = [item.get_text() for item in plt.gca().get_xticklabels()]
print("Labels are: {}".format(labels))

The ouput is:

Labels are: ['', '0.00', '0.25', '0.50', '0.75', '1.00', '1.25', '1.50', '1.75', '2.00', '']

Why the same code, referencing the same Axes, returns different results?

Body:
instead of:

%matplotlib notebook

Use:

%matplotlib inline


问:
Errors not being recorded to php error log
No matter what I do I cannot get php to log errors to a log file.

All the error parameters are set as follows (taken from phpinfo read out):

```<code>display_errors =    On
error_append_string = no value
error_log = C:\inetpub\logs\php-error.log
error_prepend_string =  no value
error_reporting = 22519
html_errors = On
ignore_repeated_errors = Off
track_errors = On
xmlrpc_error_number = 0
xmlrpc_errors = Off
</code>```

Am I missing something?

答:
Jay,

Do you have access to php.ini or PHP Selector (in cPanel)?

Make sure to set error_reporting as E_ALL. Maybe your current settings only shows critical errors and the config I sent before will help you seeing all the errors printed at error.log file.

You also can use the following code at the page you want to generate reports:

```<code>error_reporting(E_ALL);
ini_set('display_errors', 1);
</code>```

If you have any doubt else, tell me here.

Body:
No matter what I do I cannot get php to log errors to a log file.

All the error parameters are set as follows (taken from phpinfo read out):

display_errors =    On
error_append_string = no value
error_log = C:\inetpub\logs\php-error.log
error_prepend_string =  no value
error_reporting = 22519
html_errors = On
ignore_repeated_errors = Off
track_errors = On
xmlrpc_error_number = 0
xmlrpc_errors = Off

Am I missing something?

Body:
Jay,

Do you have access to php.ini or PHP Selector (in cPanel)?

Make sure to set error_reporting as E_ALL. Maybe your current settings only shows critical errors and the config I sent before will help you seeing all the errors printed at error.log file.

You also can use the following code at the page you want to generate reports:

error_reporting(E_ALL);
ini_set('display_errors', 1);

If you have any doubt else, tell me here.


问:
Django comparing form field value with selected value
I have a number of select box form fields which I need to output in the template with custom markup as a list. To do this I have created an include which gets passed the current form field as an argument.

I can loop over the list of options to create the list I want without any problems. My problem is that above the list of options I need to display either the form label, or the current selected value. This is the code I have to do this:

{% if field.value %}
    {% for value, option in field.field.choices %}
        {% if value == field.value %}
            {{ option }}
        {% endif %}
    {% endfor %}
{% else %}
    {{ field.label }}
{% endif %}```
</div>
</div>
</p>

<p>If for example <code>value</code> in the above code is 1, and <code>field.value</code> is also 1, the equality test doesn't work and the bit of code within the if statement does not get executed. I guessed it might be down to the data type of the two values I was comparing, so I tried casting both to an integer as follows:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% if field.value %}
    {% for value, option in field.field.choices %}
        {% if value|add:"0" == field.value|add:"0" %}
            {{ option }}
        {% endif %}
    {% endfor %}
{% else %}
    {{ field.label }}
{% endif %}</code>```

This worked fine for the case where the values in the select box were integers. However, sometimes my select boxes have booleans as the value, so in this case the comparison won't work with the integer casting applied.

How can I safely compare the two values whatever the type of data is being compared?

答:
I think I have found the answer.

The issue is that the selected value is always a string, and the value in the forloop could be an integer or a boolean (or potentially other data types). The answer is to cast the value in the forloop to a string:

```<code>{% if field.value %}
    {% for value, option in field.field.choices %}
        {% if value|stringformat:"s" == field.value %}
            {{ option }}
        {% endif %}
    {% endfor %}
{% else %}
    {{ field.label }}
{% endif %}
</code>```

Body:
I have a number of select box form fields which I need to output in the template with custom markup as a list. To do this I have created an include which gets passed the current form field as an argument.

I can loop over the list of options to create the list I want without any problems. My problem is that above the list of options I need to display either the form label, or the current selected value. This is the code I have to do this:

{% if field.value %}
    {% for value, option in field.field.choices %}
        {% if value == field.value %}
            {{ option }}
        {% endif %}
    {% endfor %}
{% else %}
    {{ field.label }}
{% endif %}

If for example value in the above code is 1, and field.value is also 1, the equality test doesn't work and the bit of code within the if statement does not get executed. I guessed it might be down to the data type of the two values I was comparing, so I tried casting both to an integer as follows:

{% if field.value %}
    {% for value, option in field.field.choices %}
        {% if value|add:"0" == field.value|add:"0" %}
            {{ option }}
        {% endif %}
    {% endfor %}
{% else %}
    {{ field.label }}
{% endif %}

This worked fine for the case where the values in the select box were integers. However, sometimes my select boxes have booleans as the value, so in this case the comparison won't work with the integer casting applied.

How can I safely compare the two values whatever the type of data is being compared?

Body:
I think I have found the answer.

The issue is that the selected value is always a string, and the value in the forloop could be an integer or a boolean (or potentially other data types). The answer is to cast the value in the forloop to a string:

{% if field.value %}
    {% for value, option in field.field.choices %}
        {% if value|stringformat:"s" == field.value %}
            {{ option }}
        {% endif %}
    {% endfor %}
{% else %}
    {{ field.label }}
{% endif %}


问:
Django Foreignkey problem,
```<code>class Service(models.Model)
name = models.CharField("service name", max_length = 20, unique = True)

class Newclass(models.Model):
 service = models.ForeignKey(Services)
 user1 = models.ForeignKey(User)
</code>```

Basically what I want is :
For each service I can have different user1, but no duplicate user1 for any service.
example

```<code>service = 'some'  user1 = 'amit'
service = 'some'   user1 = 'laspal'
service = 'some1'  user1 = 'amit'
</code>```

So how to avoid this conditions:

```<code>   service = 'some'    user1 = 'amit'
   service = 'some'    user1  = 'amit'
</code>```

Should I check while adding the user1 to newclass or is there some field I am missing out which I can user with Fk().

Thanks.

答:
If you mean you don't want that 2 Newclass models can exist with the same service and user1, you should use:

```<code>class Newclass(models.Model):
  service = models.ForeignKey(Services)
  user1 = models.ForeignKey(User)

  class Meta:
    unique_together = (('service', 'user1'),)
</code>```

Title: Django Foreignkey problem,

Body:
class Service(models.Model)
name = models.CharField("service name", max_length = 20, unique = True)

class Newclass(models.Model):
 service = models.ForeignKey(Services)
 user1 = models.ForeignKey(User)

Basically what I want is :
For each service I can have different user1, but no duplicate user1 for any service.
example

service = 'some'  user1 = 'amit'
service = 'some'   user1 = 'laspal'
service = 'some1'  user1 = 'amit'

So how to avoid this conditions:

   service = 'some'    user1 = 'amit'
   service = 'some'    user1  = 'amit'

Should I check while adding the user1 to newclass or is there some field I am missing out which I can user with Fk().

Thanks.

Body:
If you mean you don't want that 2 Newclass models can exist with the same service and user1, you should use:

class Newclass(models.Model):
  service = models.ForeignKey(Services)
  user1 = models.ForeignKey(User)

  class Meta:
    unique_together = (('service', 'user1'),)


问:
newRequestQueue Android's Volley crashes
I want to use Volley to capture the server response when a GET/POST request is made to a specific URL.

For this purpose I tried to use the example code from the Android Developer page:

```<code>final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
</code>```

However, the app terminates when I specify my server's URL in the variable

```<code>String url ="http://www.google.com";
</code>```

Any ideas why this is happening?

UPDATE: This is the logcat:

```<code>[ 09-24 07:49:55.360 26661:26661 D/]HostConnection::get() New Host Connection established 0xb7a6c690, tid 26661
09-24 07:49:55.410 26661-26661/test.com.test D/OpenGLRenderer: Enabling debug mode 0
09-24 07:49:55.480 26661-26661/test.com.test D/AndroidRuntime: Shutting down VM
09-24 07:49:55.480 26661-26661/test.com.test W/dalvikvm: threadid=1: thread     exiting with uncaught exception (group=0xb2cddb20)
09-24 07:49:55.490 26661-26661/test.com.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: test.com.test, PID: 26661
java.lang.StringIndexOutOfBoundsException: length=256; regionStart=0; regionLength=500
    at java.lang.String.startEndAndLength(String.java:588)
    at java.lang.String.substring(String.java:1475)
    at test.com.test.MainActivity$1.onResponse(MainActivity.java:39)
    at test.com.test.MainActivity$1.onResponse(MainActivity.java:35)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答: You must be declare RequestQueue queue; before onCreate() and then initializing it in onCreate()

Body:
I want to use Volley to capture the server response when a GET/POST request is made to a specific URL.

For this purpose I tried to use the example code from the Android Developer page:

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

However, the app terminates when I specify my server's URL in the variable

String url ="http://www.google.com";

Any ideas why this is happening?

UPDATE: This is the logcat:

[ 09-24 07:49:55.360 26661:26661 D/]HostConnection::get() New Host Connection established 0xb7a6c690, tid 26661
09-24 07:49:55.410 26661-26661/test.com.test D/OpenGLRenderer: Enabling debug mode 0
09-24 07:49:55.480 26661-26661/test.com.test D/AndroidRuntime: Shutting down VM
09-24 07:49:55.480 26661-26661/test.com.test W/dalvikvm: threadid=1: thread     exiting with uncaught exception (group=0xb2cddb20)
09-24 07:49:55.490 26661-26661/test.com.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: test.com.test, PID: 26661
java.lang.StringIndexOutOfBoundsException: length=256; regionStart=0; regionLength=500
    at java.lang.String.startEndAndLength(String.java:588)
    at java.lang.String.substring(String.java:1475)
    at test.com.test.MainActivity$1.onResponse(MainActivity.java:39)
    at test.com.test.MainActivity$1.onResponse(MainActivity.java:35)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)


问:
run maya from python shell
So I have hundreds of maya files that have to be run with one script. So I was thinking why do I even have to bother opening maya, I should be able to do it from python shell (not the python shell in maya, python shell in windows)

So the idea is:

```<code>fileList = ["....my huge list of files...."]
for f in fileList:
    openMaya
    runMyAwesomeScript
</code>```

I found this:

```<code>C:\Program Files\Autodesk\Maya201x\bin\mayapy.exe
maya.standalone.initialize()
</code>```

And it looks like it loads sth, because I can see my scripts loading from custom paths. However it does not make the maya.exe run.

Any help is welcome since I never did this kind of maya python external things.

P.S. Using maya 2015 and python 2.7.3

答:
You are on the right track. Maya.standalone runs a headless, non-gui versions of Maya so it's ideal for batching, but it is essentially a command line app. Apart from lacking GUI it is the same as regular session, so you'll have the same python path and

You'll want to design your batch process so it doesn't need any UI interactions (so, for example, you want to make sure you are saving or exporting things in a way that does not throw dialogs at the user).

If you just want a commandline-only maya, this will let you run an session interactively:

```<code>mayapy.exe -i -c "import maya.standalone; maya.standalone.initialize()"
</code>```

If you have a script to run instead, include import maya.standalone and maya.standalone.initialize() at the top and then whatever work you want to do.  Then run it from the command line like this:

```<code>mayapy.exe "path/to/script.py"
</code>```

Presumably you'd want to include a list of files to process in that script and have it just chew through them one at a time.  Something like this:

```<code>import maya.standalone
maya.standalone.initialize()
import maya.cmds as cmds
import traceback

files = ['path/to/file1.ma'. '/path/to/file2.ma'.....]

succeeded, failed = {}

for eachfile in files:
    cmds.file(eachfile, open=True, force=True)
    try:
        # real work goes here, this is dummy
        cmds.polyCube()
        cmds.file(save=True)
        succeeded[eachfile] = True
    except:
        failed[eachfile] = traceback.format_exc()

print "Processed %i files" % len(files)
print "succeeded:"
for item in succeeded:
       print "\t", item

print "failed:"
for item, reason in failed.items():
    print "\t", item
    print "\t", reason
</code>```

which should do some operation on a bunch of files and report which ones succeed and which fail for what reason

Title: run maya from python shell

Body:
So I have hundreds of maya files that have to be run with one script. So I was thinking why do I even have to bother opening maya, I should be able to do it from python shell (not the python shell in maya, python shell in windows)

So the idea is:

fileList = ["....my huge list of files...."]
for f in fileList:
    openMaya
    runMyAwesomeScript

I found this:

C:\Program Files\Autodesk\Maya201x\bin\mayapy.exe
maya.standalone.initialize()

And it looks like it loads sth, because I can see my scripts loading from custom paths. However it does not make the maya.exe run.

Any help is welcome since I never did this kind of maya python external things.

P.S. Using maya 2015 and python 2.7.3

Body:
You are on the right track. Maya.standalone runs a headless, non-gui versions of Maya so it's ideal for batching, but it is essentially a command line app. Apart from lacking GUI it is the same as regular session, so you'll have the same python path and

You'll want to design your batch process so it doesn't need any UI interactions (so, for example, you want to make sure you are saving or exporting things in a way that does not throw dialogs at the user).

If you just want a commandline-only maya, this will let you run an session interactively:

mayapy.exe -i -c "import maya.standalone; maya.standalone.initialize()"

If you have a script to run instead, include import maya.standalone and maya.standalone.initialize() at the top and then whatever work you want to do.  Then run it from the command line like this:

mayapy.exe "path/to/script.py"

Presumably you'd want to include a list of files to process in that script and have it just chew through them one at a time.  Something like this:

import maya.standalone
maya.standalone.initialize()
import maya.cmds as cmds
import traceback

files = ['path/to/file1.ma'. '/path/to/file2.ma'.....]

succeeded, failed = {}

for eachfile in files:
    cmds.file(eachfile, open=True, force=True)
    try:
        # real work goes here, this is dummy
        cmds.polyCube()
        cmds.file(save=True)
        succeeded[eachfile] = True
    except:
        failed[eachfile] = traceback.format_exc()

print "Processed %i files" % len(files)
print "succeeded:"
for item in succeeded:
       print "\t", item

print "failed:"
for item, reason in failed.items():
    print "\t", item
    print "\t", reason

which should do some operation on a bunch of files and report which ones succeed and which fail for what reason


问:
How to retain scroll position in Angular lists?
So I am on my second Angular project which consists of a long list view and a detail view. (Thinking of the hero list example by official tutorial).

Every time I scroll down to the list and open a detail view and click "Back" from the detail view the list get reloaded and thus the scroll position get lost which means I need to scroll all the way down again.

Is there any way that I could retain the scroll position on previous view?

Thanks

答: The only way I could see is using z-index. Make two separate divs for your list and details. When you go to details, hide list view using z-index and when you come back to list view reset z-index. That way you won't loose scroll position.</p>


问:
Materialize CSS - Select Doesn't Seem to Render
I am currently working with materialize CSS and it seems I've gotten snagged with the select fields.

I'm using the example provided from their site but unfortunately it it's rendering in the view whatsoever.  I was wondering if someone else might be able to help.

What I am trying to do is create a row with 2 end spacers that provide padding - then within the inner two row items there should be a search text input and a search select dropdown.

This is the example I'm working from: http://materializecss.com/forms.html

Thank you in advance.

Here is the snippet of code in question.

```<code><div class="row">
<form class="col s12">
    <div class="row">
        <div class="input-field col s2"></div>
        <div class="input-field col s5">
            <input id="icon_prefix" type="text" class="validate" />
            <label for="icon_prefix">Search</label>
        </div>
        <div class="input-field col s3">
            <label>Materialize Select</label>
            <select>
                <option value="" disabled="disabled" selected="selected">Choose your option</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
            </select>
        </div>
        <div class="input-field col s2"></div>
    </div>
</form>
</code>```

答: This works too: class = "browser-default"</p>

Body:
I am currently working with materialize CSS and it seems I've gotten snagged with the select fields.

I'm using the example provided from their site but unfortunately it it's rendering in the view whatsoever.  I was wondering if someone else might be able to help.

What I am trying to do is create a row with 2 end spacers that provide padding - then within the inner two row items there should be a search text input and a search select dropdown.

This is the example I'm working from: http://materializecss.com/forms.html

Thank you in advance.

Here is the snippet of code in question.

<form class="col s12">

            <input id="icon_prefix" type="text" class="validate" />
            Search

            Materialize Select
            <select>
                <option value="" disabled="disabled" selected="selected">Choose your option</option>
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
            </select>

</form>