问:
How can I ensure that my python Code Registers the row1 2 or 3 under a different segment of Code?
```<code>value = [10 ,20 ,50 ,100]
Balance = 0
Change = 0
totalCoins = 0
print("|~~~~~~~~~|")
print("|~~~Jack~~|")
print("|~~Blacks~|")
print("|~~Food~~~|")
print("|~~~And~~~|")
print("|~~Drink~~|")
print("|~Machine~|")

print("Row 1 ~ Crisps")
print("A1 is Walkers Crisps")
print("B1 is Pringles")
print("C1 is Lays")
print("Row 2 ~ Drinks")
print("A2 is Diet Coke")
print("B2 is Crystal Pepsi")
print("C2 is Sprite")
print("Row 3 ~ Sweets")
print("A3 is Cadbury's Chocolate")
print("B3 is Strawberry Laces")
print("C3 is Haribo")
CoinAmount = input("Would you like to continue, Type Yes to continue or No to stop")
if CoinAmount == "Yes" or "YES":
  Balance = int(input("Enter the total value of your Coins in P, Note: Machine only accepts 10p, 20p, 50p £1coins however you Must put the amount you want in Pennies either 10, 20, 50, 100,: "))
  totalCoins = Balance + totalCoins
  print ('You now have a total Balance of' ,totalCoins ,'P')
  CoinAmount = input("Would you like to continue, Type Yes to continue or No to stop")
elif Balance != value:
    print("Machine doesn't accept these total coins")
while CoinAmount == "Yes":
    Balance = int(input("Enter the total value of your Coins in P, Note: Machine only accepts 10p, 20p, 50p £1coins however you Must put the amount you want in Pennies either 10, 20, 50, 100,: "))
    totalCoins = totalCoins + Balance
    print ('You now have a total Balance of' ,totalCoins ,'P')
    CoinAmount = input("Would you like to continue, Type Yes to continue or No to stop ")
while CoinAmount != "Yes":
    break
choice = int(input("Row 1 are crisps they cost 40p, Row 2 are drinks they cost 60p and Row 3 are sweets they cost £1 Choose a row: "))

if choice == 1:
    row1 = input("Please choose either A1, B1 or C1 for your item: ")
if row1 == "A1":
    print('You have bought A Packet of Walkers Crisps for 40p, you now have' , (totalCoins - 40), 'P left')
    Change = totalCoins - 40
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row1 == "A2":
    print('You have bought a tube of Pringles for 40p, you now have' , (totalCoins - 40), 'P left')
    Change = totalCoins - 40
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row1 == "A3":
    print('You have bought a packet of Lays for 40p, you now have' , (totalCoins - 40), 'P left')
    Change = totalCoins - 40
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif choice == 1 and totalCoins < 40:
    print('You cannot buy anything else please take your change of:' ,Change ,'P')

if choice == 2:
    row2 = input("Please choose either A2, B2, C3 for your item: ")
elif row2 == "A2":
    print('You have bought a can of Diet Coke for 60p and you now have', (totalCoins - 60), 'P left')
    Change = totalCoins - 60
    Credit = input ("Would you like to continue, Type Yes to continue or No to stop ")
elif row2 == "B2":
    print('You have bought a bottle of Crystal Pepsi for 60p and you now have', (totalCoins - 60), 'P left')
    Change = totalCoins - 60
    Credit = input ("Would you like to continue, Type Yes to continue or No to stop ")
elif row2 == "C2":
    print('You have bought a bottle of Sprite for 60p and you now have', (totalCoins - 60), 'P left')
    Change = totalCoins - 60
    Credit = input ("Would you like to continue, Type Yes to continue or No to stop ")
elif choice == 2 and totalCoins < 60:
    print ('You cannot buy this please choose something else')
    choice = int(input("Row 1 are crisps they cost 40p, Row 2 are drinks they cost 60p and Row 3 are sweets they cost £1 Choose a row: "))

if choice == 3:
    row3 = input("Please Choose Either A3, B3, and C3 for your item: ")
elif row3 == "A3":
    print('You have bought a bar of Cadburys Chocolate for £1 and now have' , (totalCoins - 100), 'P left')
    Change = totalCoins - 100
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row3 == "B3":
    print('You have bought a packet of Strawberry Laces for £1 and now have' , (totalCoins - 100), 'P left')
    Change = totalCoins - 100
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row3 == "B3":
    print('You have bought a packet of Haribo for £1 and now have' , (totalCoins - 100), 'P left')
    Change = totalCoins - 100
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif choice == 3 and totalCoins < 100:
    print("You cannot afford this please choose something else")
</code>```

I have my rows in Python3 defined by an Input but if I for example decide to choose 3 for my Choice it then says that I have not defined row1 earlier on in my code.

I am not sure what I have not done to define it since it is using an input to classify it.

答:
The problem is because you haven't indented your code properly. Python code relies upon correct indentation to determine the order of processing for commands. Currently your code checks row1 value even if you didnt select row1, but you define row1 based on selecting it from the input. You need to indent the if statements under each choice selection like the following.</p>

```<code>if choice == 1:
    row1 = input("Please choose either A1, B1 or C1 for your item: ")
    if row1 == "A1":
        //do something
    elif row1 == 'A2':
        //do something else etc...
</code>```

Body:
value = [10 ,20 ,50 ,100]
Balance = 0
Change = 0
totalCoins = 0
print("|~~~~~~~~~|")
print("|~~~Jack~~|")
print("|~~Blacks~|")
print("|~~Food~~~|")
print("|~~~And~~~|")
print("|~~Drink~~|")
print("|~Machine~|")

print("Row 1 ~ Crisps")
print("A1 is Walkers Crisps")
print("B1 is Pringles")
print("C1 is Lays")
print("Row 2 ~ Drinks")
print("A2 is Diet Coke")
print("B2 is Crystal Pepsi")
print("C2 is Sprite")
print("Row 3 ~ Sweets")
print("A3 is Cadbury's Chocolate")
print("B3 is Strawberry Laces")
print("C3 is Haribo")
CoinAmount = input("Would you like to continue, Type Yes to continue or No to stop")
if CoinAmount == "Yes" or "YES":
  Balance = int(input("Enter the total value of your Coins in P, Note: Machine only accepts 10p, 20p, 50p £1coins however you Must put the amount you want in Pennies either 10, 20, 50, 100,: "))
  totalCoins = Balance + totalCoins
  print ('You now have a total Balance of' ,totalCoins ,'P')
  CoinAmount = input("Would you like to continue, Type Yes to continue or No to stop")
elif Balance != value:
    print("Machine doesn't accept these total coins")
while CoinAmount == "Yes":
    Balance = int(input("Enter the total value of your Coins in P, Note: Machine only accepts 10p, 20p, 50p £1coins however you Must put the amount you want in Pennies either 10, 20, 50, 100,: "))
    totalCoins = totalCoins + Balance
    print ('You now have a total Balance of' ,totalCoins ,'P')
    CoinAmount = input("Would you like to continue, Type Yes to continue or No to stop ")
while CoinAmount != "Yes":
    break
choice = int(input("Row 1 are crisps they cost 40p, Row 2 are drinks they cost 60p and Row 3 are sweets they cost £1 Choose a row: "))

if choice == 1:
    row1 = input("Please choose either A1, B1 or C1 for your item: ")
if row1 == "A1":
    print('You have bought A Packet of Walkers Crisps for 40p, you now have' , (totalCoins - 40), 'P left')
    Change = totalCoins - 40
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row1 == "A2":
    print('You have bought a tube of Pringles for 40p, you now have' , (totalCoins - 40), 'P left')
    Change = totalCoins - 40
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row1 == "A3":
    print('You have bought a packet of Lays for 40p, you now have' , (totalCoins - 40), 'P left')
    Change = totalCoins - 40
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif choice == 1 and totalCoins < 40:
    print('You cannot buy anything else please take your change of:' ,Change ,'P')

if choice == 2:
    row2 = input("Please choose either A2, B2, C3 for your item: ")
elif row2 == "A2":
    print('You have bought a can of Diet Coke for 60p and you now have', (totalCoins - 60), 'P left')
    Change = totalCoins - 60
    Credit = input ("Would you like to continue, Type Yes to continue or No to stop ")
elif row2 == "B2":
    print('You have bought a bottle of Crystal Pepsi for 60p and you now have', (totalCoins - 60), 'P left')
    Change = totalCoins - 60
    Credit = input ("Would you like to continue, Type Yes to continue or No to stop ")
elif row2 == "C2":
    print('You have bought a bottle of Sprite for 60p and you now have', (totalCoins - 60), 'P left')
    Change = totalCoins - 60
    Credit = input ("Would you like to continue, Type Yes to continue or No to stop ")
elif choice == 2 and totalCoins < 60:
    print ('You cannot buy this please choose something else')
    choice = int(input("Row 1 are crisps they cost 40p, Row 2 are drinks they cost 60p and Row 3 are sweets they cost £1 Choose a row: "))

if choice == 3:
    row3 = input("Please Choose Either A3, B3, and C3 for your item: ")
elif row3 == "A3":
    print('You have bought a bar of Cadburys Chocolate for £1 and now have' , (totalCoins - 100), 'P left')
    Change = totalCoins - 100
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row3 == "B3":
    print('You have bought a packet of Strawberry Laces for £1 and now have' , (totalCoins - 100), 'P left')
    Change = totalCoins - 100
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif row3 == "B3":
    print('You have bought a packet of Haribo for £1 and now have' , (totalCoins - 100), 'P left')
    Change = totalCoins - 100
    Credit = input("Would you like to continue, Type Yes to continue or No to stop ")
elif choice == 3 and totalCoins < 100:
    print("You cannot afford this please choose something else")

I have my rows in Python3 defined by an Input but if I for example decide to choose 3 for my Choice it then says that I have not defined row1 earlier on in my code.

I am not sure what I have not done to define it since it is using an input to classify it.

Body:
The problem is because you haven't indented your code properly. Python code relies upon correct indentation to determine the order of processing for commands. Currently your code checks row1 value even if you didnt select row1, but you define row1 based on selecting it from the input. You need to indent the if statements under each choice selection like the following.

if choice == 1:
    row1 = input("Please choose either A1, B1 or C1 for your item: ")
    if row1 == "A1":
        //do something
    elif row1 == 'A2':
        //do something else etc...


来源: stackexchange

问:
Unix sort of version numbers
I have a list of version numbers, let's say for instance that they are in a file versions.txt

```<code>1.2.100.4
1.2.3.4
10.1.2.3
9.1.2.3
</code>```

I wish to sort them so that they are sorted by version.  i.e:

```<code>1.2.3.4
1.2.100.4
9.1.2.3
10.1.2.3
</code>```

I have tried using various sort commands using the "k" parameters, but do not really understand it well enough to pull it off.  Any help would be appreciated.

答:
The -V option is the nicest, but I wanted to stay away from installing new/other software since my sort didn’t have that option.

This is the command that worked for me in the end:

```<code>sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n test.txt
</code>```

From comments:

To reverse the order: sort -t. -k 1,1nr -k 2,2nr -k 3,3nr -k 4,4nr

To skip the v prefix: sort -t. -k 1.2,1n -k 2,2n -k 3,3n -k 4,4n

ContentLicense: CC BY-SA 2.5

Title: Unix sort of version numbers

Body:
I have a list of version numbers, let's say for instance that they are in a file versions.txt

1.2.100.4
1.2.3.4
10.1.2.3
9.1.2.3

I wish to sort them so that they are sorted by version.  i.e:

1.2.3.4
1.2.100.4
9.1.2.3
10.1.2.3

I have tried using various sort commands using the "k" parameters, but do not really understand it well enough to pull it off.  Any help would be appreciated.

Body:
The -V option is the nicest, but I wanted to stay away from installing new/other software since my sort didn’t have that option.

This is the command that worked for me in the end:

sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n test.txt

From comments:

To reverse the order: sort -t. -k 1,1nr -k 2,2nr -k 3,3nr -k 4,4nr

To skip the v prefix: sort -t. -k 1.2,1n -k 2,2n -k 3,3n -k 4,4n

ContentLicense: CC BY-SA 3.0


问:
Grails + GORM: Is there an equivalent to hibernate's @Generated?
I'm currently working on a grails project, where I have to map a legacy database with GORM. Some of the database columns are auto-generated by triggers.

My problem is now that after I save an entity, the state of the columns that were auto-generated is not reflected in the entity.

I know that I could do entity.refresh() to force a reload of the whole entity from the database. But I don't think this is a viable solution, as such scenarios should be handled transparently. And I don't want to explicitly refresh entities after every save.

I do know that in hibernate there exists a @Generated(GenerationTime.INSERT) annotation that does exactly what I want to do.

Is there an equivalent way to do this with GORM?

答:
I don't believe that GORM supports this natively (but would be interested if another answer can show a way!) but the documentation here: http://docs.grails.org/latest/ref/Domain%20Classes/refresh.html suggests that refresh is indeed the correct approach.

You can combine that with supported events (afterInsert and afterUpdate should work for you) to refresh your object.  That isn't completely transparent, but is at least fully contained within your domain object.

```<code>// I didn't actually test this but it should work like this, or similar.
//Put the method in your domain object itself and it will be called automatically.

def afterInsert(){
    this.refresh()
}
</code>```

Body:
I don't believe that GORM supports this natively (but would be interested if another answer can show a way!) but the documentation here: http://docs.grails.org/latest/ref/Domain%20Classes/refresh.html suggests that refresh is indeed the correct approach.

You can combine that with supported events (afterInsert and afterUpdate should work for you) to refresh your object.  That isn't completely transparent, but is at least fully contained within your domain object.

// I didn't actually test this but it should work like this, or similar.
//Put the method in your domain object itself and it will be called automatically.

def afterInsert(){
    this.refresh()
}


问:
AngularJS : get datas from (api rest)Symfony's url result
I am trying to retrieve datas from my Restful api symfony with AngularJS, but i get this error "Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object".

Here is my Symfony controller :

```<code>$agent = $this->get('doctrine')
        ->getRepository('CERAgentBundle:Agent', 'agent')
        ->findByCode($employeeID);

    $session = new Session();
    $session->set('agent', $agent);

    $formatted = [
        'civilite' => $agent[0]->getCivilite(),
        'prenom' => $agent[0]->getPrenom(),
        'nom' => $agent[0]->getNom(),
        ];

    return $formatted;
}
</code>```

that give me :
result

Here is my AngularJS controller :

```<code>angular.module('frontProfilDeveloppementApp')
.controller('AboutCtrl', function ($scope, $http, $sce){
  var url = $sce.trustAsResourceUrl('http://localhost:8000/index');
  $http.get({
      method:'GET',
      url:url})
      .success(function (data) {
          $scope.result = data;
      });
</code>```

});

My Angular view :

```<code><div ng-app="frontProfilDeveloppementApp" ng-controller="AboutCtrl">

<p>Today's welcome message is:</p>

<h1>{{result.nom}}</h1>
</code>```

Thanks for help

答:
I'm not sure what version of Angular you're using but success is deprecated and your parameters are not valid for a $http.get request. Your code should be something like:</p>

```<code>angular.module('frontProfilDeveloppementApp')
.controller('AboutCtrl', function ($scope, $http, $sce){
  var url = $sce.trustAsResourceUrl('http://localhost:8000/index');
  $http.get(url})
      .then(function (data) {
          $scope.result = data;
      });
});
</code>```

Body:
I am trying to retrieve datas from my Restful api symfony with AngularJS, but i get this error "Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object".

Here is my Symfony controller :

$agent = $this->get('doctrine')
        ->getRepository('CERAgentBundle:Agent', 'agent')
        ->findByCode($employeeID);

    $session = new Session();
    $session->set('agent', $agent);

    $formatted = [
        'civilite' => $agent[0]->getCivilite(),
        'prenom' => $agent[0]->getPrenom(),
        'nom' => $agent[0]->getNom(),
        ];

    return $formatted;
}

that give me :
result

Here is my AngularJS controller :

angular.module('frontProfilDeveloppementApp')
.controller('AboutCtrl', function ($scope, $http, $sce){
  var url = $sce.trustAsResourceUrl('http://localhost:8000/index');
  $http.get({
      method:'GET',
      url:url})
      .success(function (data) {
          $scope.result = data;
      });

});

My Angular view :

Today's welcome message is:

{{result.nom}}

Thanks for help

Body:
I'm not sure what version of Angular you're using but success is deprecated and your parameters are not valid for a $http.get request. Your code should be something like:

angular.module('frontProfilDeveloppementApp')
.controller('AboutCtrl', function ($scope, $http, $sce){
  var url = $sce.trustAsResourceUrl('http://localhost:8000/index');
  $http.get(url})
      .then(function (data) {
          $scope.result = data;
      });
});


问:
How can I call a method in a base Frame Renderer from the iOS Custom renderer?
I have this code:

```<code>public partial class PhrasesFrameRenderer : Frame
{
    Random rand = new Random();
    private int answeredPhraseCount;
    private int correctAns;

    public PhrasesFrameRenderer()
    {
        InitializeComponent();
        App.PhrasesFrameRenderer = this;

        public void abc()
        {

            ....
        };
</code>```

and the custom Renderer

```<code>[assembly: ExportRenderer(typeof(PhrasesFrameRenderer), typeof(PhrasesFrameCustomRenderer))]
namespace Japanese.iOS
{
    public class PhrasesFrameCustomRenderer : FrameRenderer
    {
        UISwipeGestureRecognizer leftSwipeGestureRecognizer;
        UISwipeGestureRecognizer rightSwipeGestureRecognizer;
        PhrasesFrameRenderer frame;
        bool rightSwipeEnabled = false;
</code>```

Can someone explain to me how I can call the ABC function in the Phrases FrameRenderer from the custom Renderer code.

答:
In your CustomRenderer the Element property is basically the view you declared in the PCL Xamarin Forms class in your case PhrasesFrameRenderer

You just need to cast this property to the class and you will have access to all the public methods and properties.

```<code>var frame = (PhrasesFrameRenderer)Element;
frame.abc();
</code>```

or

```<code>var frame = Element as PhrasesFrameRenderer;

if(frame != null)
    frame.abc();
</code>```

This should work.

One note: I would not call the Custom views as Renderer as this can create confusions with its actual renderer. Your custom frame could just be named PhrasesFrame

Body:
I have this code:

public partial class PhrasesFrameRenderer : Frame
{
    Random rand = new Random();
    private int answeredPhraseCount;
    private int correctAns;

    public PhrasesFrameRenderer()
    {
        InitializeComponent();
        App.PhrasesFrameRenderer = this;

        public void abc()
        {

            ....
        };

and the custom Renderer

[assembly: ExportRenderer(typeof(PhrasesFrameRenderer), typeof(PhrasesFrameCustomRenderer))]
namespace Japanese.iOS
{
    public class PhrasesFrameCustomRenderer : FrameRenderer
    {
        UISwipeGestureRecognizer leftSwipeGestureRecognizer;
        UISwipeGestureRecognizer rightSwipeGestureRecognizer;
        PhrasesFrameRenderer frame;
        bool rightSwipeEnabled = false;

Can someone explain to me how I can call the ABC function in the Phrases FrameRenderer from the custom Renderer code.

Body:
In your CustomRenderer the Element property is basically the view you declared in the PCL Xamarin Forms class in your case PhrasesFrameRenderer

You just need to cast this property to the class and you will have access to all the public methods and properties.

var frame = (PhrasesFrameRenderer)Element;
frame.abc();

or

var frame = Element as PhrasesFrameRenderer;

if(frame != null)
    frame.abc();

This should work.

One note: I would not call the Custom views as Renderer as this can create confusions with its actual renderer. Your custom frame could just be named PhrasesFrame


问:
GridLayout adding customView as a child issue, Android
i have made a simple timetable with GridLayout and it looks like this

Now the idea is to insert required subject into specific row and column. In order to achieve that i have created a class that extends CardView in which i need to insert TextView.
code:
TimeTable.xml

```<code><GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:columnCount="8"
    android:columnOrderPreserved="true"
    android:rowCount="6"
    tools:context="com.digiart.schoolapp.fragments.TimetableFragment">

    <android.support.v7.widget.CardView
        android:id="@+id/timetable_card_space"

        android:layout_column="0"
        android:layout_columnSpan="1"
        android:layout_columnWeight="1"
        android:layout_row="0"
        app:cardElevation="2dp"
        app:contentPadding="5dp">

        <TextView
            android:id="@+id/timetable_dummy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="time"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:visibility="invisible" />
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:id="@+id/timetable_day1_card"
        android:layout_column="1"
        android:layout_columnWeight="1"
        android:layout_row="0"
        app:cardElevation="2dp"
        app:contentPadding="5dp">

        <TextView
            android:id="@+id/timetable_day1_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Monday"
            android:textAppearance="@style/TextAppearance.AppCompat.Body2" />
    </android.support.v7.widget.CardView>

    .....
    ........
    <android.support.v7.widget.CardView
        android:id="@+id/timetable_time1_card"
        android:layout_column="0"
        android:layout_columnWeight="1"
        android:layout_row="1"
        app:cardElevation="2dp"
        app:contentPadding="5dp">

        <TextView
            android:id="@+id/timetable_time1_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="09.00"
            android:textAppearance="@style/TextAppearance.AppCompat.Body2" />
    </android.support.v7.widget.CardView>
    .....
    ......
   </GridLayout>
</code>```

TimetableSubject:

```<code>public class TimetableSubject extends CardView {

    TextView subjectText;

    public TimetableSubject(Context context,int column,int row,int columnSpan,String subjectName) {
        super(context);

        GridLayout.LayoutParams subjectParam =new GridLayout.LayoutParams();
        subjectParam.columnSpec = GridLayout.spec(column,columnSpan);
        subjectParam.rowSpec = GridLayout.spec(row);

        subjectText = new TextView(context);
        CardView.LayoutParams textParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        subjectText.setText(subjectName);
        subjectText.setLayoutParams(textParams);

        setLayoutParams(subjectParam);
    }

}
</code>```

Now i get what i need to do, i need to pass row and column to the custom view, and set those as layout params. the issue i think is with the Layout parameters code, i must be messing something up there. Could anyone explain how to set layout params for this situation properly? Thanks.

答:
There was an issue with GridLayout weight parameter in Spec. Managed to solve the problem by inserting weight as a float parameter in Spec
Code:</p>

```<code>public class TimetableSubjectView extends CardView {

    TextView subjectText;

    public TimetableSubjectView(Context context, int column, int row, float columnWeight, String subjectName, int color) {
        super(context);

        GridLayout.Spec rowI = GridLayout.spec(row,1,columnWeight);
        GridLayout.Spec colI = GridLayout.spec(column,1,columnWeight);

        GridLayout.LayoutParams subjectParam =new GridLayout.LayoutParams(rowI,colI);
        subjectParam.setMargins(5,5,5,5);

        setBackgroundColor(color);
        subjectText = new TextView(context);
        CardView.LayoutParams textParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        subjectText.setText(subjectName);
        subjectText.setGravity(Gravity.CENTER);
        subjectText.setLayoutParams(textParams);
        this.addView(subjectText);
        setLayoutParams(subjectParam);
    }

}
</code>```

Body:
i have made a simple timetable with GridLayout and it looks like this

Now the idea is to insert required subject into specific row and column. In order to achieve that i have created a class that extends CardView in which i need to insert TextView.
code:
TimeTable.xml

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:columnCount="8"
    android:columnOrderPreserved="true"
    android:rowCount="6"
    tools:context="com.digiart.schoolapp.fragments.TimetableFragment">

    <android.support.v7.widget.CardView
        android:id="@+id/timetable_card_space"

        android:layout_column="0"
        android:layout_columnSpan="1"
        android:layout_columnWeight="1"
        android:layout_row="0"
        app:cardElevation="2dp"
        app:contentPadding="5dp">

        <TextView
            android:id="@+id/timetable_dummy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="time"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:visibility="invisible" />
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:id="@+id/timetable_day1_card"
        android:layout_column="1"
        android:layout_columnWeight="1"
        android:layout_row="0"
        app:cardElevation="2dp"
        app:contentPadding="5dp">

        <TextView
            android:id="@+id/timetable_day1_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Monday"
            android:textAppearance="@style/TextAppearance.AppCompat.Body2" />
    </android.support.v7.widget.CardView>

    .....
    ........
    <android.support.v7.widget.CardView
        android:id="@+id/timetable_time1_card"
        android:layout_column="0"
        android:layout_columnWeight="1"
        android:layout_row="1"
        app:cardElevation="2dp"
        app:contentPadding="5dp">

        <TextView
            android:id="@+id/timetable_time1_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="09.00"
            android:textAppearance="@style/TextAppearance.AppCompat.Body2" />
    </android.support.v7.widget.CardView>
    .....
    ......
   </GridLayout>

TimetableSubject:

public class TimetableSubject extends CardView {

    TextView subjectText;

    public TimetableSubject(Context context,int column,int row,int columnSpan,String subjectName) {
        super(context);

        GridLayout.LayoutParams subjectParam =new GridLayout.LayoutParams();
        subjectParam.columnSpec = GridLayout.spec(column,columnSpan);
        subjectParam.rowSpec = GridLayout.spec(row);

        subjectText = new TextView(context);
        CardView.LayoutParams textParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        subjectText.setText(subjectName);
        subjectText.setLayoutParams(textParams);

        setLayoutParams(subjectParam);
    }

}

Now i get what i need to do, i need to pass row and column to the custom view, and set those as layout params. the issue i think is with the Layout parameters code, i must be messing something up there. Could anyone explain how to set layout params for this situation properly? Thanks.

Body:
There was an issue with GridLayout weight parameter in Spec. Managed to solve the problem by inserting weight as a float parameter in Spec
Code:

public class TimetableSubjectView extends CardView {

    TextView subjectText;

    public TimetableSubjectView(Context context, int column, int row, float columnWeight, String subjectName, int color) {
        super(context);

        GridLayout.Spec rowI = GridLayout.spec(row,1,columnWeight);
        GridLayout.Spec colI = GridLayout.spec(column,1,columnWeight);

        GridLayout.LayoutParams subjectParam =new GridLayout.LayoutParams(rowI,colI);
        subjectParam.setMargins(5,5,5,5);

        setBackgroundColor(color);
        subjectText = new TextView(context);
        CardView.LayoutParams textParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        subjectText.setText(subjectName);
        subjectText.setGravity(Gravity.CENTER);
        subjectText.setLayoutParams(textParams);
        this.addView(subjectText);
        setLayoutParams(subjectParam);
    }

}


问:
Is a script in the footer "render-blocking"?
After discussing it with a colleague, we need an answer to the question: Is a script in the footer "render-blocking"? I mean, is any content showed to the user before the script is completely loaded?

Thank you

答:
Generally, every script is a blocker, but it is better to hold js in the footer.

Html page is executed by browser line by line as like as your code. If your script will be in the footer - that means that everything that before this script - is already rendered.


问:
undefined method `user' for nil:NilClass
I have a posting system that allows for comments.
I am making a notification system and am getting this error:

NoMethodError in CommentsController#create
undefined method `user' for nil:NilClass

I think that user is defined as a post attribute, and I'm calling the post so it should be okay.

Here is the create method

```<code>def create
    @comment = Comment.new(comment_params)
    @comment.user_id = current_user.id
    respond_to do |format|
      if @comment.save
        create_notification @post
        format.html { redirect_to request.referer, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end
</code>```

It should be noted that I was following a tutorial for part of it, and it orginially had the line "create_notification @post, @comment", but that created an argument error later.

Here is the method create_notification, the error is in the second line

```<code>def create_notification(post)
      return if post.user.id == current_user.id
      Notification.create(user_id: post.user.id,
                        notified_by_id: current_user.id,
                        post_id: post.id,
                        comment_id: comment.id,
                        notice_type: 'comment')
    end
</code>```

It starts at the second line, and if commented out, it moves on to the next lines.

Here is the app trace

```<code>app/controllers/comments_controller.rb:71:in `create_notification'
app/controllers/comments_controller.rb:33:in `block in create'
app/controllers/comments_controller.rb:31:in `create'
</code>```

答:
NoMethodError in CommentsController#create undefined method `user' for
  nil:NilClass

In create_notification @post, @post is nil Make sure you have defined @post. For instance @post = Post.find(params[:comment][:post_id])

Body:
I have a posting system that allows for comments.
I am making a notification system and am getting this error:

NoMethodError in CommentsController#create
undefined method `user' for nil:NilClass

I think that user is defined as a post attribute, and I'm calling the post so it should be okay.

Here is the create method

def create
    @comment = Comment.new(comment_params)
    @comment.user_id = current_user.id
    respond_to do |format|
      if @comment.save
        create_notification @post
        format.html { redirect_to request.referer, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

It should be noted that I was following a tutorial for part of it, and it orginially had the line "create_notification @post, @comment", but that created an argument error later.

Here is the method create_notification, the error is in the second line

def create_notification(post)
      return if post.user.id == current_user.id
      Notification.create(user_id: post.user.id,
                        notified_by_id: current_user.id,
                        post_id: post.id,
                        comment_id: comment.id,
                        notice_type: 'comment')
    end

It starts at the second line, and if commented out, it moves on to the next lines.

Here is the app trace

app/controllers/comments_controller.rb:71:in `create_notification'
app/controllers/comments_controller.rb:33:in `block in create'
app/controllers/comments_controller.rb:31:in `create'


问:
Find position of last Non Null element in a list in C#
I have the following values in my MySQL DB

```<code>Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null
</code>```

and I have create the a list in the below format

```<code>List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);
</code>```

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

答:
How about</p>

```<code>var row = StockData.OrderByDescending(x => x.Date)
                   .FirstOrDefault(x => x.High_Low_Price.HasValue);

if (row != null) // In case above query don't return anything
                 // cause all rows have blank High_Low_Price
{
    var result = row.ModifiedDate;
}
</code>```

Body:
I have the following values in my MySQL DB

Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null

and I have create the a list in the below format

List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

Body:
How about

var row = StockData.OrderByDescending(x => x.Date)
                   .FirstOrDefault(x => x.High_Low_Price.HasValue);

if (row != null) // In case above query don't return anything
                 // cause all rows have blank High_Low_Price
{
    var result = row.ModifiedDate;
}


问:
Should consecutive whitespace in an XML file be ignored by an XML reader?
At my work we have our own XML classes which build a DOM, but I'm not sure how consecutive whitespace should be handled?

e.g.

```<code><some-text>
Hello     World
</some-text>
</code>```

When this is read into the DOM, should the text node include the consecutive whitespace inbetween Hello and World or just reduce it to one space?

Or should the XML source be written like this:

```
<some-text>
Hello     World
</some-text>
```

or if not   than perhaps   ?

答: IMO it seems quite natural to treat whitespaces as significant in this case. I would expect DOM node's value to be equal to what I used in markup. </p>

OwnerDisplayName: Ben Daniel

Body:
At my work we have our own XML classes which build a DOM, but I'm not sure how consecutive whitespace should be handled?

e.g.

<some-text>
Hello     World
</some-text>

When this is read into the DOM, should the text node include the consecutive whitespace inbetween Hello and World or just reduce it to one space?

Or should the XML source be written like this:

<some-text>
Hello     World
</some-text>

or if not   than perhaps   ?

LastEditorDisplayName: Ben Daniel

OwnerDisplayName: aku


问:
try to download file from asp.net server and using UpdatePanel, ProgressTemplate.. But not working
I Want to make some actions in my program.
While these actions run I want to tell the client that these actions are on process.
and after this process end, I want to send to the client this file for example Excel file.
I minimize my project to show exactly where the problem is

Now, this is my problem:
Button1 does not work, And Button2 works fine why? and how to fix that?
Maybe have better solution?

this is my aspx clint code :

```<code><form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" Height="38px" onclick="Button1_Click" Text="Button" Width="167px" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            The report is creating please wait...
        </ProgressTemplate>
    </asp:UpdateProgress>

    <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
</form>
</code>```

And next is my code behind

```<code>public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {}

        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread.Sleep(5000);
            sendBackToUser();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            sendBackToUser();
        }

        private void sendBackToUser()
        {
            FileInfo file = new FileInfo(@"C:\F\f.xlsx");
            if (file.Exists)
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=" + @"C:\F\f.xlsx");
                Response.AddHeader("Content-Type", "application/Excel");
                Response.ContentType = "application/vnd.xlsx";
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }
</code>```

答:
Here the waiting box in my project, wich is in a separate control :

```<code><%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WaitingBox.ascx.cs" Inherits="Web_GUI.Controls.WaitingBox" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<asp:AlwaysVisibleControlExtender ID="AlwaysVisibleControlExtender1"
    runat="server" TargetControlID="Panel1" HorizontalSide="Center"
    VerticalSide="Middle" HorizontalOffset="150">
</asp:AlwaysVisibleControlExtender>

<asp:Panel ID="Panel1" runat="server" CssClass="waitingBox">
    <table>
        <tr>
            <td>Please wait ...</td>
        </tr>
        <tr>
            <td id="cell_WaitingBox-Panel"><asp:Image ID="imgWaiting" runat="server" ImageUrl="~/Themes/img/loading_animation.gif" /></td>
       </tr>
    </table>
</asp:Panel>
</code>```

And simply adding this to any other control that uses it :

```<code>        <asp:UpdateProgress ID="UpdateProgress2" runat="server" DisplayAfter="100" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>
                <MyControls:WaitingBox ID="wb2" runat="server" />
            </ProgressTemplate>
        </asp:UpdateProgress>
</code>```

Hope it inspire you... cause i don't exactly remember how it work.

But once it work, it can show a waiting box in all the control of your project.

I remember it shows a please wait message whenever the code behind is taking more than DisplayAfter="100" wich is 0.1 secondes maybe.

EDIT Below code is in an other project, more simple

js :

```<code>$.ajax({
url: "@Url.Action("create", "Post")",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ model: model})
}).done(function(result){
window.open('@Url.Action("Print", "controler", new { id = Model.id })', '_blank').focus();
});
</code>```

code behind :

```<code>return Json( new { Whatever...});
</code>```

But you rather try to call another javascript function so... forget you saw this

Body:
I Want to make some actions in my program.
While these actions run I want to tell the client that these actions are on process.
and after this process end, I want to send to the client this file for example Excel file.
I minimize my project to show exactly where the problem is

Now, this is my problem:
Button1 does not work, And Button2 works fine why? and how to fix that?
Maybe have better solution?

this is my aspx clint code :

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" Height="38px" onclick="Button1_Click" Text="Button" Width="167px" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            The report is creating please wait...
        </ProgressTemplate>
    </asp:UpdateProgress>

    <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
</form>

And next is my code behind

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {}

        protected void Button1_Click(object sender, EventArgs e)
        {
            Thread.Sleep(5000);
            sendBackToUser();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            sendBackToUser();
        }

        private void sendBackToUser()
        {
            FileInfo file = new FileInfo(@"C:\F\f.xlsx");
            if (file.Exists)
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=" + @"C:\F\f.xlsx");
                Response.AddHeader("Content-Type", "application/Excel");
                Response.ContentType = "application/vnd.xlsx";
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }

Body:
Here the waiting box in my project, wich is in a separate control :

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WaitingBox.ascx.cs" Inherits="Web_GUI.Controls.WaitingBox" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<asp:AlwaysVisibleControlExtender ID="AlwaysVisibleControlExtender1"
    runat="server" TargetControlID="Panel1" HorizontalSide="Center"
    VerticalSide="Middle" HorizontalOffset="150">
</asp:AlwaysVisibleControlExtender>

<asp:Panel ID="Panel1" runat="server" CssClass="waitingBox">
    <table>
        <tr>
            <td>Please wait ...</td>
        </tr>
        <tr>
            <td id="cell_WaitingBox-Panel"><asp:Image ID="imgWaiting" runat="server" ImageUrl="~/Themes/img/loading_animation.gif" /></td>
       </tr>
    </table>
</asp:Panel>

And simply adding this to any other control that uses it :

        <asp:UpdateProgress ID="UpdateProgress2" runat="server" DisplayAfter="100" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>
                <MyControls:WaitingBox ID="wb2" runat="server" />
            </ProgressTemplate>
        </asp:UpdateProgress>

Hope it inspire you... cause i don't exactly remember how it work.

But once it work, it can show a waiting box in all the control of your project.

I remember it shows a please wait message whenever the code behind is taking more than DisplayAfter="100" wich is 0.1 secondes maybe.

EDIT Below code is in an other project, more simple

js :

$.ajax({
url: "@Url.Action("create", "Post")",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ model: model})
}).done(function(result){
window.open('@Url.Action("Print", "controler", new { id = Model.id })', '_blank').focus();
});

code behind :

return Json( new { Whatever...});

But you rather try to call another javascript function so... forget you saw this


问:
Sprockets can't find angular.js even after adding node_modules to asset path
I'm using rails 5.0.3

I've added npm to this project at the applications' root.

In order to load node_modules into the asset pipeline I've added the following line to config/initializers/assets.rb

```<code>Rails.application.config.assets.paths << Rails.root.join('node_modules')
</code>```

Then I've included angular in my application.js manifest file like so:

```<code>//= require angular/angular.js
//= require app.js
//= require_tree ./ng/constants
//= require_tree ./ng/services
//= require_tree ./ng/controllers
</code>```

I've tried a number of variations such as:

```<code>require_directory angular
require_tree angular
require angular/angular.js
require angular
</code>```

This DOES work locally, but when I push to heroku it says:

```<code>Sprockets::FileNotFound: couldn't find file 'angular/angular.js' with type 'application/javascript'
 ...... [lists all the asset paths Sprockets has searched including node_modules]
/tmp/build_93a7b2eb7cc158c5d30b242da36b56ac/node_modules
</code>```

It seems that there is something happening when the application is loading the assets in Heroku for production than when it's run locally in development, but what is it?

I've also tried precompiling everything in my manifest file by including this line from config/initializers/assets.rb

```<code>Rails.application.config.assets.precompile += %w( application.js )
</code>```

The way that this works in Heroku for production is by first doing:

```<code>rake assets:precompile
</code>```

Why must I precompile these assets before I push to master? How can I make this part of the default process?

答: The way we solved this is by installing the webpacker gem and running rails webpacker:install

Body:
I'm using rails 5.0.3

I've added npm to this project at the applications' root.

In order to load node_modules into the asset pipeline I've added the following line to config/initializers/assets.rb

Rails.application.config.assets.paths << Rails.root.join('node_modules')

Then I've included angular in my application.js manifest file like so:

//= require angular/angular.js
//= require app.js
//= require_tree ./ng/constants
//= require_tree ./ng/services
//= require_tree ./ng/controllers

I've tried a number of variations such as:

require_directory angular
require_tree angular
require angular/angular.js
require angular

This DOES work locally, but when I push to heroku it says:

Sprockets::FileNotFound: couldn't find file 'angular/angular.js' with type 'application/javascript'
 ...... [lists all the asset paths Sprockets has searched including node_modules]
/tmp/build_93a7b2eb7cc158c5d30b242da36b56ac/node_modules

It seems that there is something happening when the application is loading the assets in Heroku for production than when it's run locally in development, but what is it?

I've also tried precompiling everything in my manifest file by including this line from config/initializers/assets.rb

Rails.application.config.assets.precompile += %w( application.js )

The way that this works in Heroku for production is by first doing:

rake assets:precompile

Why must I precompile these assets before I push to master? How can I make this part of the default process?


问:
Using reflection to test doInBackground() method in asyncTask
The method signature of the doInBackground method in AsyncTask.class looks like this:

```<code>protected Boolean doInBackground(MyObject... params);
</code>```

And inside the test with reflection it looks like this:

```<code>try {
Method doInBackgroundMethod = asyncTaskInstance.getClass().getDeclaredMethod("doInBackground", MyObject[].class);
            doInBackgroundMethod.setAccessible(true);
            boolean success = (boolean) doInBackgroundMethod.invoke(asyncTaskInstance, myObjectInstance);
            Assert.assertTrue(success);
} catch ...
</code>```

but I get the following error:

```<code>java.lang.IllegalArgumentException: argument type mismatch, on line "doInBackgroundMethod.invoke(asyncTaskInstance, myObjectInstance);"
</code>```

Yes,I know there are two methods with the same signature, so I am searching for a solution for this problem.

答: Instead of MyObject[].class use Object[].class as doInBackground uses type set during init and automaticly casts to this type when invoking doInBackground but when you doing it manually - you also need to make cast manually.

Body:
The method signature of the doInBackground method in AsyncTask.class looks like this:

protected Boolean doInBackground(MyObject... params);

And inside the test with reflection it looks like this:

try {
Method doInBackgroundMethod = asyncTaskInstance.getClass().getDeclaredMethod("doInBackground", MyObject[].class);
            doInBackgroundMethod.setAccessible(true);
            boolean success = (boolean) doInBackgroundMethod.invoke(asyncTaskInstance, myObjectInstance);
            Assert.assertTrue(success);
} catch ...

but I get the following error:

java.lang.IllegalArgumentException: argument type mismatch, on line "doInBackgroundMethod.invoke(asyncTaskInstance, myObjectInstance);"

Yes,I know there are two methods with the same signature, so I am searching for a solution for this problem.


问:
Request.Form for DropDownList
I have on my view:

```<code></td>
  <td class="span-8 last">
    <div class="editor-label">
        <label for="Traslado_Movimiento_UbicacionFuncional_Id">Ubicación Funcional</label>
    </div>
     <div class="editor-field">
       <select id="Traslado_Movimiento_UbicacionFuncional_Id"                 name="Traslado.Movimiento.UbicacionFuncional_Id"><option value=""> -- Seleccione -- </option>
          </select>
    </div>
</td>
</code>```

And I want to get the selected value on the select.

On my controller I wrote:

```<code>string selected = Request.Form["Traslado_Movimiento_UbicacionFuncional_Id"];
</code>```

But selected is always NULL....

Please, help!

Thx

答: You need to pass the input's name, which contains .s.

Title: Request.Form for DropDownList

Body:
I have on my view:

        Ubicación Funcional

       <select id="Traslado_Movimiento_UbicacionFuncional_Id"                 name="Traslado.Movimiento.UbicacionFuncional_Id"><option value=""> -- Seleccione -- </option>
          </select>

And I want to get the selected value on the select.

On my controller I wrote:

string selected = Request.Form["Traslado_Movimiento_UbicacionFuncional_Id"];

But selected is always NULL....

Please, help!

Thx


问:
TensorFlow: tf.layers vs low-level API
I am currently in the process of planning my first Conv. NN implementation in Tensorflow, and have been reading many of the tutorials available on Tensorflow's website for insight.

It seems that there are essentially two ways to create a custom CNN:

1) Use Tensorflow layers module tf.layers, which is the "high-level API". Using this method, you define a model definition function consisting of tf.layers objects, and in the main function, instantiate a tf.learn.Estimator, passing the model definition function to it. From here, the fit() and evaluate() methods can be called on the Estimator object, which train and validate, respectively. Link: https://www.tensorflow.org/tutorials/layers. Main function below:

```<code>def main(unused_argv):
  # Load training and eval data
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = learn.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
       tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  mnist_classifier.fit(
      x=train_data,
      y=train_labels,
      batch_size=100,
      steps=20000,
      monitors=[logging_hook])

  # Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = mnist_classifier.evaluate(
      x=eval_data, y=eval_labels, metrics=metrics)
  print(eval_results)
</code>```

Full code here

2) Use Tensorflow's "low-level API" in which layers are defined in a definition function. Here, layers are manually defined, and the user must perform many calculations manually. In the main function, the user starts a tf.Session(), and manually configures training/validation using for loop(s). Link: https://www.tensorflow.org/get_started/mnist/pros. Main function below:

```<code>def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                        logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  graph_location = tempfile.mkdtemp()
  print('Saving graph to: %s' % graph_location)
  train_writer = tf.summary.FileWriter(graph_location)
  train_writer.add_graph(tf.get_default_graph())

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
</code>```

Full code here

My dilemma is, I like the simplicity of defining the neural network using tf.layers (option 1), but I want the customizability of the training that the "low-level API" (option 2) provides. Specifically, when using the tf.layers implementation, is there a way to report validation accuracy every n iterations of training? Or more generally, can I train/validate using the tf.Session(), or am I confined to using the tf.learn.Estimator's fit() and evaluate() methods?

It seems odd that one would want a final evaluation score after all training is complete, as I thought the whole point of validation is to track network progression during training. Otherwise, what would be the difference between validation and testing?

Any help would be appreciated.

答:
You're nearly right however tf.layers is separate from the Estimator class of functions etc. If you wanted to you could use tf.Layers to define your layers but then build your own training loops or whatever else you like. You can think of tf.Layers just being those functions that you could create in your second option above.

If you are interested in being able to build up a basic model quickly but being able to extend it with other functions, your own training loops etc. then there's no reason you can't use layers to build your model and interact with it however you wish.

tf.Layers - https://www.tensorflow.org/api_docs/python/tf/layers

tf.Estimator - https://www.tensorflow.org/api_docs/python/tf/estimator

Title: TensorFlow: tf.layers vs low-level API

Body:
I am currently in the process of planning my first Conv. NN implementation in Tensorflow, and have been reading many of the tutorials available on Tensorflow's website for insight.

It seems that there are essentially two ways to create a custom CNN:

1) Use Tensorflow layers module tf.layers, which is the "high-level API". Using this method, you define a model definition function consisting of tf.layers objects, and in the main function, instantiate a tf.learn.Estimator, passing the model definition function to it. From here, the fit() and evaluate() methods can be called on the Estimator object, which train and validate, respectively. Link: https://www.tensorflow.org/tutorials/layers. Main function below:

def main(unused_argv):
  # Load training and eval data
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = learn.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
       tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  mnist_classifier.fit(
      x=train_data,
      y=train_labels,
      batch_size=100,
      steps=20000,
      monitors=[logging_hook])

  # Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = mnist_classifier.evaluate(
      x=eval_data, y=eval_labels, metrics=metrics)
  print(eval_results)

Full code here

2) Use Tensorflow's "low-level API" in which layers are defined in a definition function. Here, layers are manually defined, and the user must perform many calculations manually. In the main function, the user starts a tf.Session(), and manually configures training/validation using for loop(s). Link: https://www.tensorflow.org/get_started/mnist/pros. Main function below:

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                        logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  graph_location = tempfile.mkdtemp()
  print('Saving graph to: %s' % graph_location)
  train_writer = tf.summary.FileWriter(graph_location)
  train_writer.add_graph(tf.get_default_graph())

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

Full code here

My dilemma is, I like the simplicity of defining the neural network using tf.layers (option 1), but I want the customizability of the training that the "low-level API" (option 2) provides. Specifically, when using the tf.layers implementation, is there a way to report validation accuracy every n iterations of training? Or more generally, can I train/validate using the tf.Session(), or am I confined to using the tf.learn.Estimator's fit() and evaluate() methods?

It seems odd that one would want a final evaluation score after all training is complete, as I thought the whole point of validation is to track network progression during training. Otherwise, what would be the difference between validation and testing?

Any help would be appreciated.


问:
Changing name when converting JSON to POJO and back
I'm getting a JSON from an endpoint and I'm converting that into a POJO using GSON. I need to manipulate some of that data and convert it back into a JSON but with different names. If I used @SerializedName, the name changes when it's converted to a POJO from the JSON, but changes back again when I convert back into a JSON.

How could I fix this?

答:
If you are willing to switch from GSON to Jackson, then you can see the solution to this other Stack Overflow question

EDIT

Assuming you are stuck with GSON, it doesn't appear to be possible using the same class to read and write the same field with different keys. While other frameworks accomplish this by performing serialization and deserialization from getters and setters and looking for custom decorators on those methods, according to the GSON design document (see Using fields vs getters to indicate Json elements) they have decided to only use fields for now.

EDIT2

As a workaround, I might suggest creating another POJO that can be instantiated from your original object instance but has the field names you would like for serialization back to JSON. It would be a little hack-y, but you could encapsulate it in a ToJSON() method on the main class to keep things clean when doing the serialization.


问:
Get line counts of INSERT's by tablename from mysqldump - awk, sed, grep
bash master needed...

To compare mysqldumps from multiple dates, I need sql GROUP BY, ORDER BY functionality... but on the command line...

Using grep / sed / awk I need to look for all INSERT statements, then export a line count per tablename. I'd really love a byte count per tablename too...

A typical line looks like this:

```<code>INSERT INTO `admin_rule` ...
</code>```

match the INSERT, then match the tablename in ``, counting by unique tablename

答:
How about this little awk snippet:

```<code>BEGIN   { FS="`" }
/^INSERT/ { count[$2]+=1; bytes[$2]+=length($0) }
END { for(table in count) print table "," count[table] "," bytes[table]; }
</code>```

Edit: test case here:

```<code>$ cat test.sql
INSERT INTO `t1` VALUES('a', 12, 'b');
INSERT INTO `t2` VALUES('test', 'whatever', 3.14);
INSERT INTO `t3` VALUES(1, 2, 3, 4);
INSERT INTO `t2` VALUES('yay', 'works', NULL);
INSERT INTO `t2` VALUES(NULL, 'something' 2.71);
INSERT INTO `t3` VALUES(5, 6, 7, 8);
INSERT INTO `t5` VALUES('beta', 'gamma');
INSERT INTO `t6` VALUES('this', 'is', 'table', 'six');
$ awk -f t.awk <test.sql
t5,1,41
t6,1,54
t1,1,38
t2,3,144
t3,2,72
</code>```

Body:
bash master needed...

To compare mysqldumps from multiple dates, I need sql GROUP BY, ORDER BY functionality... but on the command line...

Using grep / sed / awk I need to look for all INSERT statements, then export a line count per tablename. I'd really love a byte count per tablename too...

A typical line looks like this:

INSERT INTO `admin_rule` ...

match the INSERT, then match the tablename in ``, counting by unique tablename

Body:
How about this little awk snippet:

BEGIN   { FS="`" }
/^INSERT/ { count[$2]+=1; bytes[$2]+=length($0) }
END { for(table in count) print table "," count[table] "," bytes[table]; }

Edit: test case here:

$ cat test.sql
INSERT INTO `t1` VALUES('a', 12, 'b');
INSERT INTO `t2` VALUES('test', 'whatever', 3.14);
INSERT INTO `t3` VALUES(1, 2, 3, 4);
INSERT INTO `t2` VALUES('yay', 'works', NULL);
INSERT INTO `t2` VALUES(NULL, 'something' 2.71);
INSERT INTO `t3` VALUES(5, 6, 7, 8);
INSERT INTO `t5` VALUES('beta', 'gamma');
INSERT INTO `t6` VALUES('this', 'is', 'table', 'six');
$ awk -f t.awk <test.sql
t5,1,41
t6,1,54
t1,1,38
t2,3,144
t3,2,72


问:
Applying a set of ordinary differential equations to each grid cell
I am developing an agent-based model to simulate the spread of infectious diseases in heterogeneous landscapes composed of habitat polygons (or clumps of connected cells). To simplify the model, I consider a habitat grid (or raster) containing the polygon ID of each cell. In addition, I have epidemiological parameters associated with each polygon ID. At each time step, the parameter values change in the polygon. Thus, the data frame landscape (see below) is updated at each time step. Here is an example at t = 0:

```<code>landscape <- data.frame(polygon_ID = seq(1, 10, by = 1),
                        beta = sample(c(100, 200, 400, 600), 10, replace = TRUE),
                        gamma = sample(c(25, 26, 27, 28), 10, replace = TRUE))
</code>```

To study the disease dynamics, I also am developing a compartmental model based on a system of ordinary differential equations (ODEs). Here is an example to represent the system of ODEs:

```<code>solve_sir_model <- function (times, parameters) {

  sir_model <- function (times, states, parameters) {

    with(as.list(c(states, parameters)), {

      dSdt <- -beta*S*I
      dIdt <- beta*S*I-gamma*I
      dRdt <- gamma*I
      dNdt <- dSdt + dIdt + dRdt

      return(list(c(dSdt, dIdt, dRdt, dNdt)))

    })
  }

  states <- c(S = 99, I = 1, R = 0, N = 100)
  return(ode(y = states, times = times, func = sir_model, parms = parameters))
}

require(deSolve)
output <- as.data.frame(solve_sir_model(times = seq(0, 5, by = 1), parameters = c(beta = 400, gamma = 28)))
</code>```

At each time step, is it possible to apply the system of ODEs to each habitat polygon (thus each row) in the data frame landscape? I am using lsoda as an ODE solver. Do I need to use another solver to apply the ODEs at each time step?

EDIT

It seems that the method iteration in the function ode can be useful in my case:

Method "iteration" is special in that here the function func should
  return the new value of the state variables rather than the rate of
  change. This can be used for individual based models, for difference
  equations, or in those cases where the integration is performed within
  func).

I have tested the method but I don't understand why it doesn't work with a single time step:

```<code>solve_sir_model <- function (times, parameters) {

  sir_model <- function (times, states, parameters) {

    with(as.list(c(states, parameters)), {

      dSdt <- -beta*S*I
      dIdt <- beta*S*I-gamma*I
      dRdt <- gamma*I
      dNdt <- dSdt + dIdt + dRdt

      return(list(c(dSdt, dIdt, dRdt, dNdt)))

    })
  }

  states <- c(S = 99, I = 1, R = 0, N = 100)
  return(ode(y = states, times = times, func = sir_model, parms = parameters, method = "iteration"))
}

require(deSolve)
output <- as.data.frame(solve_sir_model(times = 1, parameters = c(beta = 400, gamma = 28)))

 Error in iteration(y, times, func, parms, ...) :
   times should be equally spaced In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
</code>```

答:
Something like this.</p>

```<code># Library *not* require
library(deSolve)

# Parameters: number of polygons, beta, & gamma
n.polys <- 10
beta <- sample(c(100, 200, 400, 600), n.polys, replace = TRUE)
gamma <- sample(c(25, 26, 27, 28), n.polys, replace = TRUE)

# Model defintion
sir_model <- function (t, Y, pars) {
  # Break up state variable into parts
  S <- Y[1:n.polys]
  I <- Y[(n.polys+1):(2 * n.polys)]
  R <- Y[(2 * n.polys+1):(3 * n.polys)]

  # Calculate rate of change
  dSdt <- -beta * S * I
  dIdt <- beta * S * I - gamma * I
  dRdt <- gamma * I

  # Return rates of change after concatenating them
  return(list(c(dSdt, dIdt, dRdt)))
}

# Initial conditions
Y.ini <- c(S = rep(99, n.polys), I = rep(1, n.polys), R = rep(0, n.polys))

# Solve the model
ode(y = Y.ini, times = 0:5, func = sir_model, parms = NULL)
</code>```

Body:
I am developing an agent-based model to simulate the spread of infectious diseases in heterogeneous landscapes composed of habitat polygons (or clumps of connected cells). To simplify the model, I consider a habitat grid (or raster) containing the polygon ID of each cell. In addition, I have epidemiological parameters associated with each polygon ID. At each time step, the parameter values change in the polygon. Thus, the data frame landscape (see below) is updated at each time step. Here is an example at t = 0:

landscape <- data.frame(polygon_ID = seq(1, 10, by = 1),
                        beta = sample(c(100, 200, 400, 600), 10, replace = TRUE),
                        gamma = sample(c(25, 26, 27, 28), 10, replace = TRUE))

To study the disease dynamics, I also am developing a compartmental model based on a system of ordinary differential equations (ODEs). Here is an example to represent the system of ODEs:

solve_sir_model <- function (times, parameters) {

  sir_model <- function (times, states, parameters) {

    with(as.list(c(states, parameters)), {

      dSdt <- -beta*S*I
      dIdt <- beta*S*I-gamma*I
      dRdt <- gamma*I
      dNdt <- dSdt + dIdt + dRdt

      return(list(c(dSdt, dIdt, dRdt, dNdt)))

    })
  }

  states <- c(S = 99, I = 1, R = 0, N = 100)
  return(ode(y = states, times = times, func = sir_model, parms = parameters))
}

require(deSolve)
output <- as.data.frame(solve_sir_model(times = seq(0, 5, by = 1), parameters = c(beta = 400, gamma = 28)))

At each time step, is it possible to apply the system of ODEs to each habitat polygon (thus each row) in the data frame landscape? I am using lsoda as an ODE solver. Do I need to use another solver to apply the ODEs at each time step?

EDIT

It seems that the method iteration in the function ode can be useful in my case:

Method "iteration" is special in that here the function func should
  return the new value of the state variables rather than the rate of
  change. This can be used for individual based models, for difference
  equations, or in those cases where the integration is performed within
  func).

I have tested the method but I don't understand why it doesn't work with a single time step:

solve_sir_model <- function (times, parameters) {

  sir_model <- function (times, states, parameters) {

    with(as.list(c(states, parameters)), {

      dSdt <- -beta*S*I
      dIdt <- beta*S*I-gamma*I
      dRdt <- gamma*I
      dNdt <- dSdt + dIdt + dRdt

      return(list(c(dSdt, dIdt, dRdt, dNdt)))

    })
  }

  states <- c(S = 99, I = 1, R = 0, N = 100)
  return(ode(y = states, times = times, func = sir_model, parms = parameters, method = "iteration"))
}

require(deSolve)
output <- as.data.frame(solve_sir_model(times = 1, parameters = c(beta = 400, gamma = 28)))

 Error in iteration(y, times, func, parms, ...) :
   times should be equally spaced In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

Body:
Something like this.

# Library *not* require
library(deSolve)

# Parameters: number of polygons, beta, & gamma
n.polys <- 10
beta <- sample(c(100, 200, 400, 600), n.polys, replace = TRUE)
gamma <- sample(c(25, 26, 27, 28), n.polys, replace = TRUE)

# Model defintion
sir_model <- function (t, Y, pars) {
  # Break up state variable into parts
  S <- Y[1:n.polys]
  I <- Y[(n.polys+1):(2 * n.polys)]
  R <- Y[(2 * n.polys+1):(3 * n.polys)]

  # Calculate rate of change
  dSdt <- -beta * S * I
  dIdt <- beta * S * I - gamma * I
  dRdt <- gamma * I

  # Return rates of change after concatenating them
  return(list(c(dSdt, dIdt, dRdt)))
}

# Initial conditions
Y.ini <- c(S = rep(99, n.polys), I = rep(1, n.polys), R = rep(0, n.polys))

# Solve the model
ode(y = Y.ini, times = 0:5, func = sir_model, parms = NULL)


答:
```<code>int position = StockData.IndexOf(
              StockData.Where(lst=>lst.High_Low_Price!=null).OrderByDesc(lst=>lst.Date).FirstOrDefault()
            );

var lastDate = StockData[position]?.Date;
</code>```

Title: Find position of last Non Null element in a list in C#


问:
CUDA 8.0 nvcc fatal: single input file required for a non-link phase when an ouputtfile is specified
I'm trying to link object files in my CUDA project. Below is my makefile:

```<code>CUDA_PATH := /usr/local/cuda
NVCC := $(CUDA_PATH)/bin/nvcc

NVCCFLAGS := -arch=sm_37 --device-c -std=c++11 -cudart=shared -rdc=true

LIBS := -lcutil -lcudpp -lcuda -lcudart -lcurand

LIBPATH := $(CUDA_PATH)/lib64
SOLIBS := $(LIBPATH)/*.so

OBJS := main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o

########################################################################

# link
all: $(OBJs)
    $(NVCC) $(NVCCFLAGS) $(OBJS) $(SOLIBS) $(LIBS) -o mpamp
#--output-file mpamp.o

########################################################################

# compile individually
main.o: main.cu header.h
    $(NVCC) $(NVCCFLAGS) -c main.cu

mtx.o: mtx.cu header.h
    $(NVCC) $(NVCCFLAGS) -c mtx.cu

mpamp_for_loop_funs.o: mpamp_for_loop_funs.cu header.h
    $(NVCC) $(NVCCFLAGS) -c mpamp_for_loop_funs.cu

cuBLAS_funs.o: cuBLAS_funs.cu header.h
    $(NVCC) $(NVCCFLAGS) -c cuBLAS_funs.cu

sparsify_threshold.o: sparsify_threshold.cu header.h
    $(NVCC) $(NVCCFLAGS) -c sparsify_threshold.cu

########################################################################

run: build
    $(EXEC) ./mpamp

clean:
    \rm *.o *~ mpamp

########################################################################
</code>```

I have tried removing the $(SOLIBS), it returns the same error:

```<code>ece$ make all
/usr/local/cuda/bin/nvcc -arch=sm_37 --device-c -std=c++11 -cudart=shared -rdc=true main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o /usr/local/cuda/lib64/*.so -lcutil -lcudpp -lcuda -lcudart -lcurand -o mpamp
nvcc fatal   : A single input file is required for a non-link phase when an outputfile is specified
make: *** [all] Error 1
</code>```

In addition, when I remove -o mpamp, the make all command works, but does not generate an output file to then execute.

Does anyone have any tips on getting past this error?

I recently moved from Visual Studio in Windows to a Linux machine. VS did the compiling and linking 'automatically' (I added slashes and newlines):

```<code>nvcc -dlink -o x64\Debug\MPAMP.device-link.obj -Xcompiler "/EHsc /W3 /nologo /Od /Zi /RTC1 /MTd " \
-L"\lib\x64" cublas.lib cublas_device.lib cudadevrt.lib curand.lib
cudart.lib cudart_static.lib \
kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib \
odbc32.lib odbccp32.lib  -gencode=arch=compute_35,code=sm_35 -G \
--machine 64 x64\Debug\cuBLAS_funs.cu.obj x64\Debug\inner_loop.cu.obj x64\Debug\main.cu.obj \
x64\Debug\mpamp_for_loop_funs.cu.obj x64\Debug\mtx.cu.obj x64\Debug\sparsify_threshold.cu.obj
</code>```

Update: Per the answer below, the pertinent makefile lines are now:

```<code>NVCCFLAGS := -arch=sm_37 --device-c -std=c++11

NVCCLFLAGS := -arch=sm_37 -std=c++11 -cudart=shared -rdc=true

LDFLAGS := -I$(CUDA_PATH)/include -L$(CUDAPATH)/lib64

LIBPATH := $(CUDA_PATH)/lib64
SOLIBS := $(LIBPATH)/libcublas.so $(LIBPATH)/libcurand.so $(LIBPATH)/libcudart.so

OBJS := main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o

LIBS := -lcutil -lcudpp -lcuda -lcudart -lcurand -lcublas

########################################################################

# link
all: $(OBJs)
    $(NVCC) $(NVCCLFLAGS) $(LDFLAGS) -o mpamp $(OBJS) $(SOLIBS) $(LIBS)
</code>```

But, I receive the following error:

```<code>ece$ make all
/usr/local/cuda/bin/nvcc -arch=sm_37 -std=c++11 -cudart=shared -rdc=true -I/usr/local/cuda/include -L/lib64 -o mpamp main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o /usr/local/cuda/lib64/libcublas.so /usr/local/cuda/lib64/libcurand.so /usr/local/cuda/lib64/libcudart.so -lcutil -lcudpp -lcuda -lcudart -lcurand -lcublas
nvlink error   : Undefined reference to 'cublasDgemm_v2' in 'cuBLAS_funs.o'
make: *** [all] Error 255
</code>```

I have tried rearranging the flags in the linking statement as per this question, to no avail.

Solved! Thanks for your help. Here's the final changes:

```<code>LIBPATH := $(CUDA_PATH)/lib64
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64
SOLIBS := $(LIBPATH)/libcublas.so $(LIBPATH)/libcurand.so

OBJS := main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o

LIBS := -lcuda -lcurand -lcublas -lcublas_device
</code>```

答:
The fundamental problem here is that you have jumbled compile and link switches together, attempting to use the same set of switches both for compile and link.

Coupled with this, your code appears to use or depend on CUDA separable compilation with device linking, and it is not possible in that case to use the same set of switches for both compile and link, unless the compile and link phases are all combined, which they are not in your example.

Careful study of the nvcc manual for the switches you are using will identify the issues.

When you specify --device-c, you are indicating to the compiler (nvcc) that this is a compile phase/step only (just as specifying -c would for a gnu compiler toolchain).  Therefore specifying that switch for any kind of link process is not sensible.

The solution with the smallest number of changes is to remove that from your link phase command.  One possible approach would be to create an additional Makefile variable:

```<code>NVCCLFLAGS := -arch=sm_37 -std=c++11 -cudart=shared -rdc=true
</code>```

and modify your link phase command to use that:

```<code># link
all: $(OBJs)
    $(NVCC) $(NVCCLFLAGS) $(OBJS) $(SOLIBS) $(LIBS) -o mpamp
</code>```

Body:
I'm trying to link object files in my CUDA project. Below is my makefile:

CUDA_PATH := /usr/local/cuda
NVCC := $(CUDA_PATH)/bin/nvcc

NVCCFLAGS := -arch=sm_37 --device-c -std=c++11 -cudart=shared -rdc=true

LIBS := -lcutil -lcudpp -lcuda -lcudart -lcurand

LIBPATH := $(CUDA_PATH)/lib64
SOLIBS := $(LIBPATH)/*.so

OBJS := main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o

########################################################################

# link
all: $(OBJs)
    $(NVCC) $(NVCCFLAGS) $(OBJS) $(SOLIBS) $(LIBS) -o mpamp
#--output-file mpamp.o

########################################################################

# compile individually
main.o: main.cu header.h
    $(NVCC) $(NVCCFLAGS) -c main.cu

mtx.o: mtx.cu header.h
    $(NVCC) $(NVCCFLAGS) -c mtx.cu

mpamp_for_loop_funs.o: mpamp_for_loop_funs.cu header.h
    $(NVCC) $(NVCCFLAGS) -c mpamp_for_loop_funs.cu

cuBLAS_funs.o: cuBLAS_funs.cu header.h
    $(NVCC) $(NVCCFLAGS) -c cuBLAS_funs.cu

sparsify_threshold.o: sparsify_threshold.cu header.h
    $(NVCC) $(NVCCFLAGS) -c sparsify_threshold.cu

########################################################################

run: build
    $(EXEC) ./mpamp

clean:
    \rm *.o *~ mpamp

########################################################################

I have tried removing the $(SOLIBS), it returns the same error:

ece$ make all
/usr/local/cuda/bin/nvcc -arch=sm_37 --device-c -std=c++11 -cudart=shared -rdc=true main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o /usr/local/cuda/lib64/*.so -lcutil -lcudpp -lcuda -lcudart -lcurand -o mpamp
nvcc fatal   : A single input file is required for a non-link phase when an outputfile is specified
make: *** [all] Error 1

In addition, when I remove -o mpamp, the make all command works, but does not generate an output file to then execute.

Does anyone have any tips on getting past this error?

I recently moved from Visual Studio in Windows to a Linux machine. VS did the compiling and linking 'automatically' (I added slashes and newlines):

nvcc -dlink -o x64\Debug\MPAMP.device-link.obj -Xcompiler "/EHsc /W3 /nologo /Od /Zi /RTC1 /MTd " \
-L"\lib\x64" cublas.lib cublas_device.lib cudadevrt.lib curand.lib
cudart.lib cudart_static.lib \
kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib \
odbc32.lib odbccp32.lib  -gencode=arch=compute_35,code=sm_35 -G \
--machine 64 x64\Debug\cuBLAS_funs.cu.obj x64\Debug\inner_loop.cu.obj x64\Debug\main.cu.obj \
x64\Debug\mpamp_for_loop_funs.cu.obj x64\Debug\mtx.cu.obj x64\Debug\sparsify_threshold.cu.obj

Update: Per the answer below, the pertinent makefile lines are now:

NVCCFLAGS := -arch=sm_37 --device-c -std=c++11

NVCCLFLAGS := -arch=sm_37 -std=c++11 -cudart=shared -rdc=true

LDFLAGS := -I$(CUDA_PATH)/include -L$(CUDAPATH)/lib64

LIBPATH := $(CUDA_PATH)/lib64
SOLIBS := $(LIBPATH)/libcublas.so $(LIBPATH)/libcurand.so $(LIBPATH)/libcudart.so

OBJS := main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o

LIBS := -lcutil -lcudpp -lcuda -lcudart -lcurand -lcublas

########################################################################

# link
all: $(OBJs)
    $(NVCC) $(NVCCLFLAGS) $(LDFLAGS) -o mpamp $(OBJS) $(SOLIBS) $(LIBS)

But, I receive the following error:

ece$ make all
/usr/local/cuda/bin/nvcc -arch=sm_37 -std=c++11 -cudart=shared -rdc=true -I/usr/local/cuda/include -L/lib64 -o mpamp main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o /usr/local/cuda/lib64/libcublas.so /usr/local/cuda/lib64/libcurand.so /usr/local/cuda/lib64/libcudart.so -lcutil -lcudpp -lcuda -lcudart -lcurand -lcublas
nvlink error   : Undefined reference to 'cublasDgemm_v2' in 'cuBLAS_funs.o'
make: *** [all] Error 255

I have tried rearranging the flags in the linking statement as per this question, to no avail.

Solved! Thanks for your help. Here's the final changes:

LIBPATH := $(CUDA_PATH)/lib64
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64
SOLIBS := $(LIBPATH)/libcublas.so $(LIBPATH)/libcurand.so

OBJS := main.o mtx.o mpamp_for_loop_funs.o cuBLAS_funs.o sparsify_threshold.o

LIBS := -lcuda -lcurand -lcublas -lcublas_device

Body:
The fundamental problem here is that you have jumbled compile and link switches together, attempting to use the same set of switches both for compile and link.

Coupled with this, your code appears to use or depend on CUDA separable compilation with device linking, and it is not possible in that case to use the same set of switches for both compile and link, unless the compile and link phases are all combined, which they are not in your example.

Careful study of the nvcc manual for the switches you are using will identify the issues.

When you specify --device-c, you are indicating to the compiler (nvcc) that this is a compile phase/step only (just as specifying -c would for a gnu compiler toolchain).  Therefore specifying that switch for any kind of link process is not sensible.

The solution with the smallest number of changes is to remove that from your link phase command.  One possible approach would be to create an additional Makefile variable:

NVCCLFLAGS := -arch=sm_37 -std=c++11 -cudart=shared -rdc=true

and modify your link phase command to use that:

# link
all: $(OBJs)
    $(NVCC) $(NVCCLFLAGS) $(OBJS) $(SOLIBS) $(LIBS) -o mpamp


问:
VHDL implementation of pipeline calculating Y=A*B+C
I have VHDL code, which implements Y=A*B+C pipeline in three stages, as illustrated below

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity pipeline is
   Port (A : in std_logic_vector (15 downto 0);
      B : in std_logic_vector (15 downto 0);
      C : in std_logic_vector (15 downto 0);
      Y : out std_logic_vector (32 downto 0);
      CLK : in std_logic;
      RESET : in std_logic);
end pipeline;

architecture Behavioral3 of pipeline is
   signal OUT_A, OUT_B, OUT_C : std_logic_vector (15 downto 0);
   signal OUT_MUL_2, OUT_C_2 : std_logic_vector (31 downto 0);

   begin
      Stage1: process(CLK, RESET)
         begin
            if RESET ='0' then
               OUT_A <= x"0000";
               OUT_B <= x"0000";
               OUT_C <= x"0000";
            elsif CLK ='1' and CLK'event then
               OUT_A <= A;
               OUT_B <= B;
               OUT_C <= C;
            end if;
       end process;

       Stage2: process(CLK, RESET)
          begin
             if RESET = '0' then
                OUT_MUL_2 <= x"00000000";
                OUT_C_2 <= x"00000000";
             elsif CLK ='1' and CLK'event then
                OUT_MUL_2 <= OUT_A * OUT_B ;
                OUT_C_2 <= x"0000" & OUT_C ;
             end if;
       end process;

       Stage3: process(CLK, RESET)
          begin
             if RESET ='0' then
                Y <= (others => ‘0’);
             elsif CLK ='1' and CLK'event then
                Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);
             end if;
       end process;
end Behavioral3;
</code>```

Question:
Why in the process "Stage3" the code is :

Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);

rather than :

Y <= OUT_MUL_2 + OUT_C_2;

Wouldn't the implementation as written yield an OUT signal Y of always 0 (low), because anything&0 is always 0 and 0+0 is again 0 ?

答: There is one point to take in account. Adders could be a signed adder. To avoid a misunderstood that a positive number on 32 bits is interpreted as a negative number, you can add a '0' bit before to be sure that the add will take in account 2 positive numbers.</p>

Body:
I have VHDL code, which implements Y=A*B+C pipeline in three stages, as illustrated below

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity pipeline is
   Port (A : in std_logic_vector (15 downto 0);
      B : in std_logic_vector (15 downto 0);
      C : in std_logic_vector (15 downto 0);
      Y : out std_logic_vector (32 downto 0);
      CLK : in std_logic;
      RESET : in std_logic);
end pipeline;

architecture Behavioral3 of pipeline is
   signal OUT_A, OUT_B, OUT_C : std_logic_vector (15 downto 0);
   signal OUT_MUL_2, OUT_C_2 : std_logic_vector (31 downto 0);

   begin
      Stage1: process(CLK, RESET)
         begin
            if RESET ='0' then
               OUT_A <= x"0000";
               OUT_B <= x"0000";
               OUT_C <= x"0000";
            elsif CLK ='1' and CLK'event then
               OUT_A <= A;
               OUT_B <= B;
               OUT_C <= C;
            end if;
       end process;

       Stage2: process(CLK, RESET)
          begin
             if RESET = '0' then
                OUT_MUL_2 <= x"00000000";
                OUT_C_2 <= x"00000000";
             elsif CLK ='1' and CLK'event then
                OUT_MUL_2 <= OUT_A * OUT_B ;
                OUT_C_2 <= x"0000" & OUT_C ;
             end if;
       end process;

       Stage3: process(CLK, RESET)
          begin
             if RESET ='0' then
                Y <= (others => ‘0’);
             elsif CLK ='1' and CLK'event then
                Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);
             end if;
       end process;
end Behavioral3;

Question:
Why in the process "Stage3" the code is :

Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);

rather than :

Y <= OUT_MUL_2 + OUT_C_2;

Wouldn't the implementation as written yield an OUT signal Y of always 0 (low), because anything&0 is always 0 and 0+0 is again 0 ?


问:
Forcing a message loop to yield
I hope this question isn't too broad.

I'm working with a legacy Ada application. This application is built around a very old piece of middleware that handles, among other things, our IPC. For the sake of this question, I can boil the middleware's provisions down to

1: a message loop that processes messages (from other programs or this program)

2: a function to send messages to this program or others

3: a function to read from a database

The program operates mainly on a message loop - simply something like

```<code> loop
    This_Msg := Message_Loop.Wait_For_Message; -- Blocking wait call
    -- Do things based on This_Msg's ID
 end loop
</code>```

however there are also callbacks that can be triggered by external stimuli. These callbacks run in their own threads. Some of these callbacks call the database-reading function, which has always been fine, EXCEPT, as we recently discovered, in a relatively rare condition. When this condition occurs, it turns out it isn't safe to read from the database when the message loop is executing its blocking Wait_For_Message.

It seemed like a simple solution would be to use a protected object to synchronize the Wait_For_Message and database read: if we try to read the database while Wait_For_Message is blocking, the read will block until Wait_For_Message returns, at which point the Wait_For_Message call will be blocked until the database read is complete. The next problem is that I can't guarantee the message loop will receive a message in a timely fashion, meaning that the database read could be blocked for an arbitrary amount of time. It seems like the solution to this is also simple: send a do-nothing message to the loop before blocking, ensuring that the Wait_For_Message call will yield.

What I'm trying to wrap my head around is:

If I send the do-nothing message and THEN block before the database read, I don't think I can guarantee that Wait_For_Message won't have returned, yielded, processed the do-nothing message, and started blocking again before the pre-database read block. I think I conceptually need to start blocking and THEN push a message, but I'm not sure how to do this. I think I could handle it with a second layer of locks, but I can't think of the most efficient way to do so, and don't know if that's even the right solution. This is really my first foray into concurrency in Ada, so I'm hoping for a pointer in the right direction.

答:
Perhaps you should use a task for this; the following would have the task waiting at the SELECT to either process a message or access the DB while another call on an entry during the processing would queue on that entry for the loop to reiterate the select, thus eliminating the problem altogether... unless, somehow, your DB-access calls the message entry; but that shouldn't happen.

Package Example is
    Task Message_Processor is
        Entry Message( Text : String );
        Entry Read_DB( Data : DB_Rec );
    End Message_Processor;
End Example;

Package Body Example is
    Task Body Message_Processor is
        Package Message_Holder is new Ada.Containers.Indefinite_Holders
          (Element_Type => String);
        Package DB_Rec_Holder is new Ada.Containers.Indefinite_Holders
          (Element_Type => DB_Rec);

        Current_Message : Message_Holder.Holder;
        Current_DB_Rec  : DB_Rec_Holder.Holder;
    Begin
        MESSAGE_LOOP:
        loop
            select
                accept Message (Text : in String) do
                    Current_Message:= Message_Holder.To_Holder( Text );
                end Message;
                -- Process the message **outside** the rendevouz.
                delay 1.0; -- simulate processing.
                Ada.Text_IO.Put_Line( Current_Message.Element );
            or
                accept Read_DB (Data : in DB_Rec) do
                    Current_DB_Rec:= DB_Rec_Holder.To_Holder( Data );
                end Message;
                -- Process the DB-record here, **outside** the rendevouz.
            or
                Terminate;
            end select;
        end loop MESSAGE_LOOP;
    End Message_Processor;
End Example;
```

Title: Forcing a message loop to yield

Body:
I hope this question isn't too broad.

I'm working with a legacy Ada application. This application is built around a very old piece of middleware that handles, among other things, our IPC. For the sake of this question, I can boil the middleware's provisions down to

1: a message loop that processes messages (from other programs or this program)

2: a function to send messages to this program or others

3: a function to read from a database

The program operates mainly on a message loop - simply something like

 loop
    This_Msg := Message_Loop.Wait_For_Message; -- Blocking wait call
    -- Do things based on This_Msg's ID
 end loop

however there are also callbacks that can be triggered by external stimuli. These callbacks run in their own threads. Some of these callbacks call the database-reading function, which has always been fine, EXCEPT, as we recently discovered, in a relatively rare condition. When this condition occurs, it turns out it isn't safe to read from the database when the message loop is executing its blocking Wait_For_Message.

It seemed like a simple solution would be to use a protected object to synchronize the Wait_For_Message and database read: if we try to read the database while Wait_For_Message is blocking, the read will block until Wait_For_Message returns, at which point the Wait_For_Message call will be blocked until the database read is complete. The next problem is that I can't guarantee the message loop will receive a message in a timely fashion, meaning that the database read could be blocked for an arbitrary amount of time. It seems like the solution to this is also simple: send a do-nothing message to the loop before blocking, ensuring that the Wait_For_Message call will yield.

What I'm trying to wrap my head around is:

If I send the do-nothing message and THEN block before the database read, I don't think I can guarantee that Wait_For_Message won't have returned, yielded, processed the do-nothing message, and started blocking again before the pre-database read block. I think I conceptually need to start blocking and THEN push a message, but I'm not sure how to do this. I think I could handle it with a second layer of locks, but I can't think of the most efficient way to do so, and don't know if that's even the right solution. This is really my first foray into concurrency in Ada, so I'm hoping for a pointer in the right direction.


问:
Why am I getting this TypeError - "can't convert Symbol into Integer"?
I have an array of hashes. Each entry looks like this:

```<code>- !map:Hashie::Mash
  name: Connor H Peters
  id: "506253404"
</code>```

I'm trying to create a second array, which contains just the id values.

```<code>["506253404"]
</code>```

This is how I'm doing it

```<code>second_array = first_array.map { |hash| hash[:id] }
</code>```

But I'm getting this error

```<code>TypeError in PagesController#home
can't convert Symbol into Integer
</code>```

If I try

```<code>second_array = first_array.map { |hash| hash["id"] }
</code>```

I get

```<code>TypeError in PagesController#home
can't convert String into Integer
</code>```

What am I doing wrong? Thanks for reading.

答:
You're using Hashie, which isn't the same as Hash from ruby core. Looking at the Hashie github repo, it seems that you can access hash keys as methods:

```<code>first_array.map { |hash| hash.id }
</code>```

Try this out and see if that works--make sure that it doesn't return the object_id. As such, you may want to double-check by doing first_array.map { |hash| hash.name } to see if you're really accessing the right data.

Then, provided it's correct, you can use a proc to get the id (but with a bit more brevity):

```<code>first_array.map(&:id)
</code>```

Body:
I have an array of hashes. Each entry looks like this:

- !map:Hashie::Mash
  name: Connor H Peters
  id: "506253404"

I'm trying to create a second array, which contains just the id values.

["506253404"]

This is how I'm doing it

second_array = first_array.map { |hash| hash[:id] }

But I'm getting this error

TypeError in PagesController#home
can't convert Symbol into Integer

If I try

second_array = first_array.map { |hash| hash["id"] }

I get

TypeError in PagesController#home
can't convert String into Integer

What am I doing wrong? Thanks for reading.

Body:
You're using Hashie, which isn't the same as Hash from ruby core. Looking at the Hashie github repo, it seems that you can access hash keys as methods:

first_array.map { |hash| hash.id }

Try this out and see if that works--make sure that it doesn't return the object_id. As such, you may want to double-check by doing first_array.map { |hash| hash.name } to see if you're really accessing the right data.

Then, provided it's correct, you can use a proc to get the id (but with a bit more brevity):

first_array.map(&:id)