问:
Iteration controlled loop not working correctly
The following should generate 2 random numbers between 0 and 100, that follow certain rules.

Those rules being:

*Neither can be 0

*Num1 must be larger than Num2

*And Num1 must be divisible by Num2 (The num1 % num2 bit)

Currently the loop works correctly for the first two points, but not the last one. It is still generating numbers where num1 is not divisible by num2. Whats gone wrong?

```<code>do {
        if (num1 == 0) {
            num1 = rand()%100;
        }
        else if(num2 == 0) {
            num2 = rand()%100;
        }
        else if (num1 < num2) {
            num2 = rand()%100;
        }
        else if(num1 % num2 != 0) {
            num2 = rand()%100;
        }
        a++;
        printf("Loop no.:%d %d mod %d = %d %d / %d \n",a,num1,num2,num1%num2,num1,num2);
    } while(num1 < num2 && (num1%num2 != 0) && num1 != 0 && num2 != 0);
</code>```

答: If you want to have all conditions met, your while-condition should actually be something like while(num1 < num2 || (num1%num2 != 0) || num1== 0 || num2 == 0). If you connect the conditions by &&, the loop will end once one of the conditions is not met, e.g. when num1 is not divisible by num2.

Body:
The following should generate 2 random numbers between 0 and 100, that follow certain rules.

Those rules being:

*Neither can be 0

*Num1 must be larger than Num2

*And Num1 must be divisible by Num2 (The num1 % num2 bit)

Currently the loop works correctly for the first two points, but not the last one. It is still generating numbers where num1 is not divisible by num2. Whats gone wrong?

do {
        if (num1 == 0) {
            num1 = rand()%100;
        }
        else if(num2 == 0) {
            num2 = rand()%100;
        }
        else if (num1 < num2) {
            num2 = rand()%100;
        }
        else if(num1 % num2 != 0) {
            num2 = rand()%100;
        }
        a++;
        printf("Loop no.:%d %d mod %d = %d %d / %d \n",a,num1,num2,num1%num2,num1,num2);
    } while(num1 < num2 && (num1%num2 != 0) && num1 != 0 && num2 != 0);


来源: stackexchange

问:
Apache Tika do not extract first line of the RTF file, It only extract last three char of first line.
I have added the RTF file in comment.Copy the following text in text editor and save as RTF format.

```<code>BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(new File("level1Missing.rtf"));
ParseContext pcontext = new ParseContext();
RTFParser rt = new RTFParser();
rt.parse(inputstream, handler, metadata, pcontext);
//getting the content of the document
System.out.println("Contents of the PDF :\n\n" + handler.toString());
</code>```

答:
In my view, Apache Tika has no problem. The criticality is in the rtf file; there is a \par less before {\line {\b Level1} : \par}.

You can try with this another simple file:

```<code>{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\par
This is some {\b bold} text.\par
}
</code>```

If you remove \par before This is some {\b bold} text.\par, tika will extract the last chars of the first line.

ContentLicense: CC BY-SA 3.0

Body:
I have added the RTF file in comment.Copy the following text in text editor and save as RTF format.

BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(new File("level1Missing.rtf"));
ParseContext pcontext = new ParseContext();
RTFParser rt = new RTFParser();
rt.parse(inputstream, handler, metadata, pcontext);
//getting the content of the document
System.out.println("Contents of the PDF :\n\n" + handler.toString());

Body:
In my view, Apache Tika has no problem. The criticality is in the rtf file; there is a \par less before {\line {\b Level1} : \par}.

You can try with this another simple file:

{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\par
This is some {\b bold} text.\par
}

If you remove \par before This is some {\b bold} text.\par, tika will extract the last chars of the first line.


问:
Constraint Layout Changing Through The Screen Size
I am working on a project and I can't figure it out after long time searching, how to manage and fit my layout to every screen size.
I tried everything and it just split the objects on the screen.
I need to create a stable layout that doesn't change through the different screen sizes.
I will appreciate your help.</p>

答:
If you want a layout that shows correctly across various screen sizes, try not to hard code positions of the objects inside the layout. For example, don't use android:layout_marginLeft="50dp" and|or android:paddingLeft="50dp", etc to position the object inside the layout.

Instead, use more of
 android:layout_weight and android:layout_gravity in LinearLayout

and
 android:layout_centerInParent, android:layout_centerHorizontal or android:layout_centerVertical in RelativeLayout.

Make sure the parent layout has:

```<code>android:layout_height="match_parent"
android:layout_width="match_parent"
</code>```

Body:
If you want a layout that shows correctly across various screen sizes, try not to hard code positions of the objects inside the layout. For example, don't use android:layout_marginLeft="50dp" and|or android:paddingLeft="50dp", etc to position the object inside the layout.

Instead, use more of
 android:layout_weight and android:layout_gravity in LinearLayout

and
 android:layout_centerInParent, android:layout_centerHorizontal or android:layout_centerVertical in RelativeLayout.

Make sure the parent layout has:

android:layout_height="match_parent"
android:layout_width="match_parent"


问:
Simulate data in R from a linear model where the parameters are correlated
I would like to simulate data from the follow model in R

```<code>Y ~ N(b0 + b1*X, sigma)
</code>```

and fit the following model in R

```<code>lm(Y ~ 1 + X, data)
</code>```

roughly here is what the R code would be,

```<code>nsims = 1000
X = 1:50
b0 = rnorm(nsims, 55.63, 31.40)
b1 = rnorm(nsims, 1.04, .39)
sigma = rnorm(nsims, 11.34, 4.11)
</code>```

The catch is that I'd like b0, b1, and sigma to be correlated. I'd like them to have this for a correlation.

```<code>R <- matrix(c(1, .16, .54,
              .16, 1, .13,
              .54, .13, 1),
              nrow = 3)
colnames(R) <- c("b0", "b1", "sigma")
</code>```

Now given that I want this correlation structure, my rnorm code above is wrong. If my data didn't need this correlation matrix, I would probably do the following,

```<code> sim_data <- data.frame()
 for(i in 1:nsims){
   Y = b0[i] + b1[i]*X + rnorm(length(X), 0, sigma[i])
   data_tmp <- data.frame(Y = Y, X = X, ID = i)
   sim_data <- rbind(sim_data, data_tmp)
 }
</code>```

But this ignores my correlation structure because of the way I generated the parameters. Can anyone offer me some suggestions or pointers where to look for how to incorporate a correlation?

答:
Simulate 3-dimensional normal distribution and take variables from it. You can use MASS package for multivariate simulation and MBESS package for transformation from correlation to covariance matric which is needed in mvrnorm function.

```<code>library(MASS)
library(MBESS)
R <- matrix(c(1, .16, .54,
              .16, 1, .13,
              .54, .13, 1),
            nrow = 3)
SD <- c(31.40, .39, 4.11)
## convert correlation matrix to covariance matrix
Cov <- cor2cov(R, SD)
### you can also do it algebraically without MBESS package
### Cov <- SD %*% t(SD) * R
### where %*% is matrix multiplication and * is normal multiplication
### t() is transpose function

# simulate multivariate normal distribution
mvnorm <- mvrnorm(
  1000,
  mu = c(55.63, 1.04, 11.34),
  Sigma = Cov,
  empirical = T
)
# check whether correlation matrix is right
cor(mvnorm)
     [,1] [,2] [,3]
[1,] 1.00 0.16 0.54
[2,] 0.16 1.00 0.13
[3,] 0.54 0.13 1.00
# extract variables
b0 <- mvnorm[, 1]
b1 <- mvnorm[, 2]
sigma <- mvnorm[, 3]
</code>```

Body:
I would like to simulate data from the follow model in R

Y ~ N(b0 + b1*X, sigma)

and fit the following model in R

lm(Y ~ 1 + X, data)

roughly here is what the R code would be,

nsims = 1000
X = 1:50
b0 = rnorm(nsims, 55.63, 31.40)
b1 = rnorm(nsims, 1.04, .39)
sigma = rnorm(nsims, 11.34, 4.11)

The catch is that I'd like b0, b1, and sigma to be correlated. I'd like them to have this for a correlation.

R <- matrix(c(1, .16, .54,
              .16, 1, .13,
              .54, .13, 1),
              nrow = 3)
colnames(R) <- c("b0", "b1", "sigma")

Now given that I want this correlation structure, my rnorm code above is wrong. If my data didn't need this correlation matrix, I would probably do the following,

 sim_data <- data.frame()
 for(i in 1:nsims){
   Y = b0[i] + b1[i]*X + rnorm(length(X), 0, sigma[i])
   data_tmp <- data.frame(Y = Y, X = X, ID = i)
   sim_data <- rbind(sim_data, data_tmp)
 }

But this ignores my correlation structure because of the way I generated the parameters. Can anyone offer me some suggestions or pointers where to look for how to incorporate a correlation?

Body:
Simulate 3-dimensional normal distribution and take variables from it. You can use MASS package for multivariate simulation and MBESS package for transformation from correlation to covariance matric which is needed in mvrnorm function.

library(MASS)
library(MBESS)
R <- matrix(c(1, .16, .54,
              .16, 1, .13,
              .54, .13, 1),
            nrow = 3)
SD <- c(31.40, .39, 4.11)
## convert correlation matrix to covariance matrix
Cov <- cor2cov(R, SD)
### you can also do it algebraically without MBESS package
### Cov <- SD %*% t(SD) * R
### where %*% is matrix multiplication and * is normal multiplication
### t() is transpose function

# simulate multivariate normal distribution
mvnorm <- mvrnorm(
  1000,
  mu = c(55.63, 1.04, 11.34),
  Sigma = Cov,
  empirical = T
)
# check whether correlation matrix is right
cor(mvnorm)
     [,1] [,2] [,3]
[1,] 1.00 0.16 0.54
[2,] 0.16 1.00 0.13
[3,] 0.54 0.13 1.00
# extract variables
b0 <- mvnorm[, 1]
b1 <- mvnorm[, 2]
sigma <- mvnorm[, 3]


问:
JavaFX dialog without icon
I don't know how to create a dialog without any icon in JavaFX. I've tried

```<code>((Stage)dialog.getDialogPane().getScene().getWindow()).getIcons().clear();
</code>```

but it still leaves the ugly default icon (on Windows 10) of dialog. Is there any better way than setting empty PNG as icon? If so give me the hint.

答:
When you want to get rid of icon you may switch window style to make only content visible without closed, minimize, etc, buttons and also without icon.

javadoc Dialog class

```<code>dialog.initStyle(StageStyle.UNDECORATED);
</code>```

Specifies the style for this dialog. This must be done prior to making
  the dialog visible. The style is one of: StageStyle.DECORATED,
  StageStyle.UNDECORATED, StageStyle.TRANSPARENT, StageStyle.UTILITY, or
  StageStyle.UNIFIED.

Title: JavaFX dialog without icon

Body:
I don't know how to create a dialog without any icon in JavaFX. I've tried

((Stage)dialog.getDialogPane().getScene().getWindow()).getIcons().clear();

but it still leaves the ugly default icon (on Windows 10) of dialog. Is there any better way than setting empty PNG as icon? If so give me the hint.

Body:
When you want to get rid of icon you may switch window style to make only content visible without closed, minimize, etc, buttons and also without icon.

javadoc Dialog class

dialog.initStyle(StageStyle.UNDECORATED);

Specifies the style for this dialog. This must be done prior to making
  the dialog visible. The style is one of: StageStyle.DECORATED,
  StageStyle.UNDECORATED, StageStyle.TRANSPARENT, StageStyle.UTILITY, or
  StageStyle.UNIFIED.


问:
how to align 2 rows in an info box
so i have these 2 rows of text displaying in an info box....but one row has an icon and the next one doesnt. i'm not exactly sure how to align the words so that the second row without the icon is indented correctly.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed

```

it comes out like this

EDIT: also using bootstrap...if that helps

答:
No need to wrap everything in divs, I would suggest just wrapping your copy in a span and using flexbox to align your items.

HTML Edit:

```<code><div class="alert alert-info my-alert">
  <i class="alert-icon-info alert-icon"></i>
  <span class="alert-copy">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed <br>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed</span>
</div>
</code>```

CSS edit:

```<code>.my-alert {
  display:flex;
  flex-direction:row;
}
</code>```

JSFiddle here: https://jsfiddle.net/visioncreative/ufu6Lcud/3/

Great documentation on Flexbox at CSS-Tricks here, https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Title: how to align 2 rows in an info box

Body:
so i have these 2 rows of text displaying in an info box....but one row has an icon and the next one doesnt. i'm not exactly sure how to align the words so that the second row without the icon is indented correctly.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed

it comes out like this

EDIT: also using bootstrap...if that helps

Body:
No need to wrap everything in divs, I would suggest just wrapping your copy in a span and using flexbox to align your items.

HTML Edit:

<div class="alert alert-info my-alert">
  <i class="alert-icon-info alert-icon"></i>
  <span class="alert-copy">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed <br>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed</span>
</div>

CSS edit:

.my-alert {
  display:flex;
  flex-direction:row;
}

JSFiddle here: https://jsfiddle.net/visioncreative/ufu6Lcud/3/

Great documentation on Flexbox at CSS-Tricks here, https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
Preserve line breaks in angularjs
I have seen this SO question.

My code instead of ng-bind="item.desc" uses {{item.desc}} because I have a ng-repeat before.

So my code:

```<code><div ng-repeat="item in items">
  {{item.description}}
</div>
</code>```

The item description contains \n for newlines which are not rendered.

How can the {{item.description}} display the newlines easily assuming that I have the ng-repeat above?

答: Just use the css style "white-space: pre-wrap" and you should be good to go. I've had the same issue where I need to handle error messages for which the line breaks and white spaces are really particular. I just added this inline where I was binding the data and it works like Charm!</p>

Title: Preserve line breaks in angularjs

Body:
I have seen this SO question.

My code instead of ng-bind="item.desc" uses {{item.desc}} because I have a ng-repeat before.

So my code:

  {{item.description}}

The item description contains \n for newlines which are not rendered.

How can the {{item.description}} display the newlines easily assuming that I have the ng-repeat above?


问:
How can I access a variable outside of define in requirejs
I have the following module implemented based on ko (knockout).

```<code>define(['ko'],
    function(ko) {
        function compareViewModel() {
            var self = this;
            self.products = ko.observableArray([]);
            self.addProduct = function(p) {
                self.products.push(p);
            }
            self.visible = ko.computed(function() {
                return self.products().length > 0;
            });
        }

        return { cvm: compareViewModel() };
    });
</code>```

I want to be able to access cvm outside of define

```<code>$(function () {
    //ACCESS CVM HERE
    $('.compare-chk').click(function () {
        var $chk = $(this).prev('input:checkbox');
        if ($chk !== 'undefined') {
            if (!$chk.is(':checked')) {
                cvm.addProduct($chk.attr('value'));
                console.log(cvm.products());
            }
        }
    });
});
</code>```

Is that even possible?

答:
In order you access cvm you have to state that you need the module where this is defined:

```<code>requirejs(['jquery', 'ko'], function($, ko){
    $(function () {
    //ACCESS CVM HERE
        $('.compare-chk').click(function () {
            var $chk = $(this).prev('input:checkbox');
            if ($chk !== 'undefined') {
                if (!$chk.is(':checked')) {
                    ko.cvm.addProduct($chk.attr('value'));
                    console.log(ko.cvm.products());
                }
            }
        });
    });
});
</code>```

Note It's quite possible that the modules and libraries in the array we pass as the first argument of requirejs need some tweaking. You have to specify where these files are in your application. For instance, please have a look here, which is an introductory tutorial in requirejs or here, which is the official documentation of the library.

Body:
I have the following module implemented based on ko (knockout).

define(['ko'],
    function(ko) {
        function compareViewModel() {
            var self = this;
            self.products = ko.observableArray([]);
            self.addProduct = function(p) {
                self.products.push(p);
            }
            self.visible = ko.computed(function() {
                return self.products().length > 0;
            });
        }

        return { cvm: compareViewModel() };
    });

I want to be able to access cvm outside of define

$(function () {
    //ACCESS CVM HERE
    $('.compare-chk').click(function () {
        var $chk = $(this).prev('input:checkbox');
        if ($chk !== 'undefined') {
            if (!$chk.is(':checked')) {
                cvm.addProduct($chk.attr('value'));
                console.log(cvm.products());
            }
        }
    });
});

Is that even possible?

Body:
In order you access cvm you have to state that you need the module where this is defined:

requirejs(['jquery', 'ko'], function($, ko){
    $(function () {
    //ACCESS CVM HERE
        $('.compare-chk').click(function () {
            var $chk = $(this).prev('input:checkbox');
            if ($chk !== 'undefined') {
                if (!$chk.is(':checked')) {
                    ko.cvm.addProduct($chk.attr('value'));
                    console.log(ko.cvm.products());
                }
            }
        });
    });
});

Note It's quite possible that the modules and libraries in the array we pass as the first argument of requirejs need some tweaking. You have to specify where these files are in your application. For instance, please have a look here, which is an introductory tutorial in requirejs or here, which is the official documentation of the library.


问:
Unable to change to landscape mode in android
Since I made a lot of changes to the app, I am starting this thread to reflect them.  I am still having problems changing orientation.

Here's the code

```<code>Activity

    package com.flash;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class QuizActivity extends Activity {

private static final String TAG = "QuizActivity";

private Button mTrueButton;
private Button mFalseButton;
private ImageButton mPrevButton;
private ImageButton mNextButton;
private TextView mQuestionTextView;

private TrueFalse[] mQuestionBank;
private int mCurrentIndex = 0;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(Bundle)");
    setQuestionBank();
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.activity_quiz);
        ProcessPortrait();
    } else {
        if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
        }
    }
}

private void ProcessPortrait() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mPrevButton = (ImageButton) findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCurrentIndex == 0) {
                mCurrentIndex = mQuestionBank.length - 1;
            } else {
                mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            }
            updateQuestion();
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void ProcessLandscape() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void setQuestionBank() {
    mQuestionBank = new TrueFalse[]{
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
    };
}

private void updateQuestion() {
    int question = mQuestionBank[mCurrentIndex].getmQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].ismTrueQuestion();

    int messageResId = 0;

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_Toast;
    } else {
        messageResId = R.string.incorrect_Toast;
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart() called");
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "onStart() called");
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume() called");
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop() called");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy() called");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.main);
        ProcessPortrait();
    } else if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
    }
}
</code>```

}

```<code>XML

Portrait

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

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/prev_button"
            android:src="@drawable/arrow_left"/>

        <ImageButton
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/next_button"
            android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </LinearLayout>
</code>```

Landscape

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

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/next_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="10sp"
                android:contentDescription="@string/next_button"
                android:gravity="bottom|right"
                android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </FrameLayout>

Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.flash"
        android:versionCode="1"
        android:versionName="1.0"
    >
        <application android:label="@string/app_name"
                 android:icon="@drawable/ic_launcher" >
            <activity android:name=".QuizActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|
        keyboardHidden|screenSize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
</code>```

When I debug using my phone, landscape works, although it may by my phone that is adjusting to the new orientation and not the app.

I am currently unable to get the debugger to work when using the emulator, so that is an issue I need help with as well.

When I run/debug the app, the home page displays and I have to press the recent apps button on the emulator and then double click on the app to bring it forward, hmmm, yet another issue.

Anyway, any help will be greatly appreciated

答:
It seems like you're trying to fight against the system when an orientation change comes about.

I would suggest not overriding onConfigurationChanged() method.

I would suggest not checking what the orientation of the activity is in the onCreate() method.

Use resource qualifiers to determine what layout is used.

That all said when you rotate the activity this way the activity will be destroyed and recreated. Unless you have a big reason for not allowing the activity to be destroyed/re-created, I'd advise not handling orientation manually as you are. If you want to use orientation changes in this fashion you'll want to change your code to something similar to this:

First, rename your xml layout files to be the same name, eg activity_quiz. Then place them into different directories in your res folder like res/layout/activity_quiz.xml and res/layout-land/activity_quiz.xml.

Second change is to remove the android:configChanges="orientation" option. You can safely leave the other two configChanges options though.

Third change your activity code by removing the onConfigurationChanged() method completely. The system will handle that. And your onCreate() method should look like this:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setQuestionBank();
    setContentView(R.layout.activity_quiz);
}
</code>```

Once you change your activity code, you should be able to merge your ProcessPortrait() and ProcessLandscape() methods into a singular method pretty much keeping your exact logic as it is now, just make sure to do a null check before accessing your views to ensure the app doesn't crash due to a NullPointerException.

You'll also want to look into state saving and restoration if you have data that needs to be saved/restored on orientation change, such as the count.

Hopefully this helps. If not I can try to clarify things.

Body:
Since I made a lot of changes to the app, I am starting this thread to reflect them.  I am still having problems changing orientation.

Here's the code

Activity

    package com.flash;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class QuizActivity extends Activity {

private static final String TAG = "QuizActivity";

private Button mTrueButton;
private Button mFalseButton;
private ImageButton mPrevButton;
private ImageButton mNextButton;
private TextView mQuestionTextView;

private TrueFalse[] mQuestionBank;
private int mCurrentIndex = 0;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(Bundle)");
    setQuestionBank();
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.activity_quiz);
        ProcessPortrait();
    } else {
        if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
        }
    }
}

private void ProcessPortrait() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mPrevButton = (ImageButton) findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCurrentIndex == 0) {
                mCurrentIndex = mQuestionBank.length - 1;
            } else {
                mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            }
            updateQuestion();
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void ProcessLandscape() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void setQuestionBank() {
    mQuestionBank = new TrueFalse[]{
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
    };
}

private void updateQuestion() {
    int question = mQuestionBank[mCurrentIndex].getmQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].ismTrueQuestion();

    int messageResId = 0;

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_Toast;
    } else {
        messageResId = R.string.incorrect_Toast;
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart() called");
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "onStart() called");
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume() called");
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop() called");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy() called");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.main);
        ProcessPortrait();
    } else if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
    }
}

}

XML

Portrait

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

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/prev_button"
            android:src="@drawable/arrow_left"/>

        <ImageButton
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/next_button"
            android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </LinearLayout>

Landscape

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

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/next_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="10sp"
                android:contentDescription="@string/next_button"
                android:gravity="bottom|right"
                android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </FrameLayout>

Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.flash"
        android:versionCode="1"
        android:versionName="1.0"
    >
        <application android:label="@string/app_name"
                 android:icon="@drawable/ic_launcher" >
            <activity android:name=".QuizActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|
        keyboardHidden|screenSize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>

When I debug using my phone, landscape works, although it may by my phone that is adjusting to the new orientation and not the app.

I am currently unable to get the debugger to work when using the emulator, so that is an issue I need help with as well.

When I run/debug the app, the home page displays and I have to press the recent apps button on the emulator and then double click on the app to bring it forward, hmmm, yet another issue.

Anyway, any help will be greatly appreciated

Body:
It seems like you're trying to fight against the system when an orientation change comes about.

I would suggest not overriding onConfigurationChanged() method.

I would suggest not checking what the orientation of the activity is in the onCreate() method.

Use resource qualifiers to determine what layout is used.

That all said when you rotate the activity this way the activity will be destroyed and recreated. Unless you have a big reason for not allowing the activity to be destroyed/re-created, I'd advise not handling orientation manually as you are. If you want to use orientation changes in this fashion you'll want to change your code to something similar to this:

First, rename your xml layout files to be the same name, eg activity_quiz. Then place them into different directories in your res folder like res/layout/activity_quiz.xml and res/layout-land/activity_quiz.xml.

Second change is to remove the android:configChanges="orientation" option. You can safely leave the other two configChanges options though.

Third change your activity code by removing the onConfigurationChanged() method completely. The system will handle that. And your onCreate() method should look like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setQuestionBank();
    setContentView(R.layout.activity_quiz);
}

Once you change your activity code, you should be able to merge your ProcessPortrait() and ProcessLandscape() methods into a singular method pretty much keeping your exact logic as it is now, just make sure to do a null check before accessing your views to ensure the app doesn't crash due to a NullPointerException.

You'll also want to look into state saving and restoration if you have data that needs to be saved/restored on orientation change, such as the count.

Hopefully this helps. If not I can try to clarify things.


问:
Delete commit which had no changes
In my git repository I have a commit to merge a branch into master. However the only commit on that branch was added to master before the merge, so the merge changed nothing. There have now been several other commits after the merge.

I would like to delete the merge to make the network graph cleaner.

Network graph:

```<code>- @a ---- @b ---- @merge --- .... more commits
  |               |
  \------ @b ---- /
</code>```

where @a is where the branch was created, @b is a commit with content and @merge has no changes

The desired state is:

```<code>- @a ---- @b ---- ... more commits
</code>```

Command git log --graph --oneline --all gives:

```<code>* 1b1076a Add while statement
* 3d7ae6a add logical shortcircuit operators
* 96d0631 add if statement
* a56529e tidy up, add context free grammar file
* 0ba080a add javadoc comments to whole project - yay!
* 5a376b1 Add scoped variables and error when reading uninitialised variable
*   a52e685 Merge branch 'master' of https://github.com/SparkleCode/Java-Interpreter
|\
| * 6cb6c07 globl variables!
* | 9a1c395 global variables
|/
* 5e5913f fixed netbeans
* 5aecfa8 initialize from old repo
* 8b30840 Initial commit
</code>```

in this log 6cb6c07 committed the same code as 9a1c395, making both 6cb6c07 and a52e685 unnecessary

答:
So, what you need to do is to rebase but please read my answer till the end before running any commands. Rebasing in git is.. changing the base of a commit - this is a typical operation that is used in day-to-day work. However sometimes - like in this scenario - rebase may result in rewriting the history of git, so changing the commit IDs. This may result in need to push the changes to remote repo with -f or --force-with-lease switches. And now, if you work alone in a project this should not be a matter. However in a team it will result in incoherent state of remote repo and other users may have they work lost if they are not cautious enough.

That said, current state is:

```<code>* 1b1076a 2017-11-14 18:22:46 +0000 ScratchOs (HEAD -> master, origin/master, origin/HEAD) Add while statement
* 3d7ae6a 2017-11-12 17:38:26 +0000 ScratchOs add logical shortcircuit operators
* 96d0631 2017-11-12 14:01:27 +0000 ScratchOs add if statement
* a56529e 2017-11-12 13:42:05 +0000 ScratchOs tidy up, add context free grammar file
* 0ba080a 2017-11-12 12:47:24 +0000 ScratchOs add javadoc comments to whole project - yay!
* 5a376b1 2017-11-09 20:11:48 +0000 ScratchOs Add scoped variables and error when reading uninitialised variable
*   a52e685 2017-11-08 20:47:52 +0000 ScratchOs Merge branch 'master' of https://github.com/SparkleCode/Java-Interpreter
|\
| * 6cb6c07 2017-11-08 20:45:12 +0000 ScratchOs globl variables!
* | 9a1c395 2017-11-08 20:45:12 +0000 ScratchOs global variables
|/
* 5e5913f 2017-11-08 20:02:43 +0000 ScratchOs fixed netbeans
* 5aecfa8 2017-11-08 16:40:17 +0000 ScratchOs initialize from old repo
* 8b30840 2017-11-08 16:31:54 +0000 William Moreton Initial commit
</code>```

You need to rebase - change the parent of commit a52e685 so you need to run:

```<code>git rebase 9a1c395
</code>```

Which results in:

```<code> /tmp/Java-Interpreter/ [master] git rebase 9a1c395
First, rewinding head to replay your work on top of it...
Applying: globl variables!
Using index info to reconstruct a base tree...
M   src/sparklecode/AstPrinter.java
M   src/sparklecode/Expr.java
M   src/sparklecode/Interpreter.java
M   src/sparklecode/Parser.java
M   src/tool/generateAst.java
Falling back to patching base and 3-way merge...
No changes -- Patch already applied.
Applying: Add scoped variables and error when reading uninitialised variable
Applying: add javadoc comments to whole project - yay!
Applying: tidy up, add context free grammar file
Applying: add if statement
Applying: add logical shortcircuit operators
Applying: Add while statement
</code>```

And the new state is:

```<code>* b909b74 2017-11-14 18:22:46 +0000 ScratchOs (HEAD -> master) Add while statement
* 53b9e9b 2017-11-12 17:38:26 +0000 ScratchOs add logical shortcircuit operators
* 9df0bd6 2017-11-12 14:01:27 +0000 ScratchOs add if statement
* 4795c73 2017-11-12 13:42:05 +0000 ScratchOs tidy up, add context free grammar file
* 43d4cdf 2017-11-12 12:47:24 +0000 ScratchOs add javadoc comments to whole project - yay!
* 8323a42 2017-11-09 20:11:48 +0000 ScratchOs Add scoped variables and error when reading uninitialised variable
| * 1b1076a 2017-11-14 18:22:46 +0000 ScratchOs (origin/master, origin/HEAD) Add while statement
| * 3d7ae6a 2017-11-12 17:38:26 +0000 ScratchOs add logical shortcircuit operators
| * 96d0631 2017-11-12 14:01:27 +0000 ScratchOs add if statement
| * a56529e 2017-11-12 13:42:05 +0000 ScratchOs tidy up, add context free grammar file
| * 0ba080a 2017-11-12 12:47:24 +0000 ScratchOs add javadoc comments to whole project - yay!
| * 5a376b1 2017-11-09 20:11:48 +0000 ScratchOs Add scoped variables and error when reading uninitialised variable
| *   a52e685 2017-11-08 20:47:52 +0000 ScratchOs Merge branch 'master' of https://github.com/SparkleCode/Java-Interpreter
| |\
|/ /
| * 6cb6c07 2017-11-08 20:45:12 +0000 ScratchOs globl variables!
* | 9a1c395 2017-11-08 20:45:12 +0000 ScratchOs global variables
|/
* 5e5913f 2017-11-08 20:02:43 +0000 ScratchOs fixed netbeans
* 5aecfa8 2017-11-08 16:40:17 +0000 ScratchOs initialize from old repo
* 8b30840 2017-11-08 16:31:54 +0000 William Moreton Initial commit
</code>```

Notice that above commit 9a1c395 hashes have changed and the state of the repository HEAD -> master vs (origin/master, origin/HEAD) is incoherent. Now you need to push the changes:

```<code>git push --force-with-lease
</code>```

Title: Delete commit which had no changes

Body:
In my git repository I have a commit to merge a branch into master. However the only commit on that branch was added to master before the merge, so the merge changed nothing. There have now been several other commits after the merge.

I would like to delete the merge to make the network graph cleaner.

Network graph:

- @a ---- @b ---- @merge --- .... more commits
  |               |
  \------ @b ---- /

where @a is where the branch was created, @b is a commit with content and @merge has no changes

The desired state is:

- @a ---- @b ---- ... more commits

Command git log --graph --oneline --all gives:

* 1b1076a Add while statement
* 3d7ae6a add logical shortcircuit operators
* 96d0631 add if statement
* a56529e tidy up, add context free grammar file
* 0ba080a add javadoc comments to whole project - yay!
* 5a376b1 Add scoped variables and error when reading uninitialised variable
*   a52e685 Merge branch 'master' of https://github.com/SparkleCode/Java-Interpreter
|\
| * 6cb6c07 globl variables!
* | 9a1c395 global variables
|/
* 5e5913f fixed netbeans
* 5aecfa8 initialize from old repo
* 8b30840 Initial commit

in this log 6cb6c07 committed the same code as 9a1c395, making both 6cb6c07 and a52e685 unnecessary

Body:
So, what you need to do is to rebase but please read my answer till the end before running any commands. Rebasing in git is.. changing the base of a commit - this is a typical operation that is used in day-to-day work. However sometimes - like in this scenario - rebase may result in rewriting the history of git, so changing the commit IDs. This may result in need to push the changes to remote repo with -f or --force-with-lease switches. And now, if you work alone in a project this should not be a matter. However in a team it will result in incoherent state of remote repo and other users may have they work lost if they are not cautious enough.

That said, current state is:

* 1b1076a 2017-11-14 18:22:46 +0000 ScratchOs (HEAD -> master, origin/master, origin/HEAD) Add while statement
* 3d7ae6a 2017-11-12 17:38:26 +0000 ScratchOs add logical shortcircuit operators
* 96d0631 2017-11-12 14:01:27 +0000 ScratchOs add if statement
* a56529e 2017-11-12 13:42:05 +0000 ScratchOs tidy up, add context free grammar file
* 0ba080a 2017-11-12 12:47:24 +0000 ScratchOs add javadoc comments to whole project - yay!
* 5a376b1 2017-11-09 20:11:48 +0000 ScratchOs Add scoped variables and error when reading uninitialised variable
*   a52e685 2017-11-08 20:47:52 +0000 ScratchOs Merge branch 'master' of https://github.com/SparkleCode/Java-Interpreter
|\
| * 6cb6c07 2017-11-08 20:45:12 +0000 ScratchOs globl variables!
* | 9a1c395 2017-11-08 20:45:12 +0000 ScratchOs global variables
|/
* 5e5913f 2017-11-08 20:02:43 +0000 ScratchOs fixed netbeans
* 5aecfa8 2017-11-08 16:40:17 +0000 ScratchOs initialize from old repo
* 8b30840 2017-11-08 16:31:54 +0000 William Moreton Initial commit

You need to rebase - change the parent of commit a52e685 so you need to run:

git rebase 9a1c395

Which results in:

 /tmp/Java-Interpreter/ [master] git rebase 9a1c395
First, rewinding head to replay your work on top of it...
Applying: globl variables!
Using index info to reconstruct a base tree...
M   src/sparklecode/AstPrinter.java
M   src/sparklecode/Expr.java
M   src/sparklecode/Interpreter.java
M   src/sparklecode/Parser.java
M   src/tool/generateAst.java
Falling back to patching base and 3-way merge...
No changes -- Patch already applied.
Applying: Add scoped variables and error when reading uninitialised variable
Applying: add javadoc comments to whole project - yay!
Applying: tidy up, add context free grammar file
Applying: add if statement
Applying: add logical shortcircuit operators
Applying: Add while statement

And the new state is:

* b909b74 2017-11-14 18:22:46 +0000 ScratchOs (HEAD -> master) Add while statement
* 53b9e9b 2017-11-12 17:38:26 +0000 ScratchOs add logical shortcircuit operators
* 9df0bd6 2017-11-12 14:01:27 +0000 ScratchOs add if statement
* 4795c73 2017-11-12 13:42:05 +0000 ScratchOs tidy up, add context free grammar file
* 43d4cdf 2017-11-12 12:47:24 +0000 ScratchOs add javadoc comments to whole project - yay!
* 8323a42 2017-11-09 20:11:48 +0000 ScratchOs Add scoped variables and error when reading uninitialised variable
| * 1b1076a 2017-11-14 18:22:46 +0000 ScratchOs (origin/master, origin/HEAD) Add while statement
| * 3d7ae6a 2017-11-12 17:38:26 +0000 ScratchOs add logical shortcircuit operators
| * 96d0631 2017-11-12 14:01:27 +0000 ScratchOs add if statement
| * a56529e 2017-11-12 13:42:05 +0000 ScratchOs tidy up, add context free grammar file
| * 0ba080a 2017-11-12 12:47:24 +0000 ScratchOs add javadoc comments to whole project - yay!
| * 5a376b1 2017-11-09 20:11:48 +0000 ScratchOs Add scoped variables and error when reading uninitialised variable
| *   a52e685 2017-11-08 20:47:52 +0000 ScratchOs Merge branch 'master' of https://github.com/SparkleCode/Java-Interpreter
| |\
|/ /
| * 6cb6c07 2017-11-08 20:45:12 +0000 ScratchOs globl variables!
* | 9a1c395 2017-11-08 20:45:12 +0000 ScratchOs global variables
|/
* 5e5913f 2017-11-08 20:02:43 +0000 ScratchOs fixed netbeans
* 5aecfa8 2017-11-08 16:40:17 +0000 ScratchOs initialize from old repo
* 8b30840 2017-11-08 16:31:54 +0000 William Moreton Initial commit

Notice that above commit 9a1c395 hashes have changed and the state of the repository HEAD -> master vs (origin/master, origin/HEAD) is incoherent. Now you need to push the changes:

git push --force-with-lease


问:
How to add an and clause when using inSetBind
Trying to add a '&&' clause to my filter when using inSetBind but I can't.

This works:

```<code>db.run(lists.filter(f => f.id inSetBind(listIds)).result)
</code>```

When I try to add a && clause I get an error:

db.run(lists.filter(f => f.id inSetBind(listIds) && (f.locationId === locationId)).result)

Error is:

```<code>ambiguous implicit values:
[error]  both value BooleanOptionColumnCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[slick.lifted.Rep[Option[Boolean]]]
[error]  and value BooleanCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[Boolean]
[error]  match expected type slick.lifted.CanBeQueryCondition[Nothing]
</code>```

答:
From what I can tell, it's a simple parse error. Scala sees

```<code>lists.filter(f => f.id inSetBind(listIds) && (f.locationId === locationId))
</code>```

and parses it as

```<code>lists.filter(f => f.id (inSetBind(listIds) && (f.locationId === locationId)))
</code>```

so it's understandably confused. Try

```<code>lists.filter(f => (f.id inSetBind(listIds)) && (f.locationId === locationId))
</code>```

Or, probably more clear in this case

```<code>lists.filter(f => f.id.inSetBind(listIds) && (f.locationId === locationId))
</code>```

Scala's precedence rules can be found here. Infix operators that begin with a letter (such as inSetBind) have lower precedence than any other (infix) operator, which is why && binds more tightly than it.

Body:
Trying to add a '&&' clause to my filter when using inSetBind but I can't.

This works:

db.run(lists.filter(f => f.id inSetBind(listIds)).result)

When I try to add a && clause I get an error:

db.run(lists.filter(f => f.id inSetBind(listIds) && (f.locationId === locationId)).result)

Error is:

ambiguous implicit values:
[error]  both value BooleanOptionColumnCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[slick.lifted.Rep[Option[Boolean]]]
[error]  and value BooleanCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[Boolean]
[error]  match expected type slick.lifted.CanBeQueryCondition[Nothing]

Body:
From what I can tell, it's a simple parse error. Scala sees

lists.filter(f => f.id inSetBind(listIds) && (f.locationId === locationId))

and parses it as

lists.filter(f => f.id (inSetBind(listIds) && (f.locationId === locationId)))

so it's understandably confused. Try

lists.filter(f => (f.id inSetBind(listIds)) && (f.locationId === locationId))

Or, probably more clear in this case

lists.filter(f => f.id.inSetBind(listIds) && (f.locationId === locationId))

Scala's precedence rules can be found here. Infix operators that begin with a letter (such as inSetBind) have lower precedence than any other (infix) operator, which is why && binds more tightly than it.


问:
Title and Navigation bars white in iOS 11 on view using ABNewPersonViewController
I've inherited a legacy app and was tasked with updating it for iOS 11. In one view, the user can click on a name and add that user to their contacts. However, when going to the 'add contact' view in iOS 11, the navigation and status bars are showing up as white. It works fine on iOS 10 and below.

Here's a screenshot comparing iOS 10 (left) to iOS 11 (right):

Note that this view is created programmatically, and not through the storyboard:

```<code>ABRecordRef person = ABPersonCreate();
//...
ABNewPersonViewController *newPersonViewController = [[ABNewPersonViewController alloc] init];
[newPersonViewController setDisplayedPerson:person];
newPersonViewController.newPersonViewDelegate = self;
UINavigationController *newNavigationController = [[UINavigationController alloc] initWithRootViewController:newPersonViewController];
[self presentViewController:newNavigationController animated:YES completion:nil];
CFRelease(person);
</code>```

I've tried a few different things based on what I found online:

I found I can manually set the background color of the navigation bar, but that leaves the status bar white.

I've tried adding a HeightConstraint to the new view. I confirmed the constraint is added, but it didn't help. However, I had to set the value with a constant (tried 0, 100, 1000 just for testing) and couldn't get the relative constraint working properly. Regardless, not sure if it was worth going down that path.

I saw some articles online that iOS 11 changes how the status/nav bars work and recommended setting setContentInsetAdjustmentBehavior to NEVER. However, this looks like it only works on ScrollViews or TableViews. This contact add view appears just to be a UIView.

Tried switching to CNContactViewController (as ABNewPersonViewController is deprecated), and ran into the same issue.

Any advice would be helpful.

Edit: The Navigation bar colors get set in the AppDelegate in the didFinishLaunchingWithOptions method as seen below. I tried removing all the custom logic that gets set here. This somewhat fixed the navigation bar, but the status bar was still white with white text.

```<code>-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

if ([MPUtils isIOS7OrHigher]) {
    [[UIToolbar appearance] setBarTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];
    [[UINavigationBar appearance] setBarTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];

    //color of text on buttons:
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{UITextAttributeTextColor : [UIColor whiteColor]}];
} else {
    [[UIToolbar appearance] setTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];
    [[UINavigationBar appearance] setTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];
}

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

[MPUserDataSynchronizer syncUserData];

return YES;
}
</code>```

答: ABNewPersonViewController is deprecated in iOS 9. Use CNContactViewController instead.

Body:
I've inherited a legacy app and was tasked with updating it for iOS 11. In one view, the user can click on a name and add that user to their contacts. However, when going to the 'add contact' view in iOS 11, the navigation and status bars are showing up as white. It works fine on iOS 10 and below.

Here's a screenshot comparing iOS 10 (left) to iOS 11 (right):

Note that this view is created programmatically, and not through the storyboard:

ABRecordRef person = ABPersonCreate();
//...
ABNewPersonViewController *newPersonViewController = [[ABNewPersonViewController alloc] init];
[newPersonViewController setDisplayedPerson:person];
newPersonViewController.newPersonViewDelegate = self;
UINavigationController *newNavigationController = [[UINavigationController alloc] initWithRootViewController:newPersonViewController];
[self presentViewController:newNavigationController animated:YES completion:nil];
CFRelease(person);

I've tried a few different things based on what I found online:

I found I can manually set the background color of the navigation bar, but that leaves the status bar white.

I've tried adding a HeightConstraint to the new view. I confirmed the constraint is added, but it didn't help. However, I had to set the value with a constant (tried 0, 100, 1000 just for testing) and couldn't get the relative constraint working properly. Regardless, not sure if it was worth going down that path.

I saw some articles online that iOS 11 changes how the status/nav bars work and recommended setting setContentInsetAdjustmentBehavior to NEVER. However, this looks like it only works on ScrollViews or TableViews. This contact add view appears just to be a UIView.

Tried switching to CNContactViewController (as ABNewPersonViewController is deprecated), and ran into the same issue.

Any advice would be helpful.

Edit: The Navigation bar colors get set in the AppDelegate in the didFinishLaunchingWithOptions method as seen below. I tried removing all the custom logic that gets set here. This somewhat fixed the navigation bar, but the status bar was still white with white text.

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

if ([MPUtils isIOS7OrHigher]) {
    [[UIToolbar appearance] setBarTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];
    [[UINavigationBar appearance] setBarTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];

    //color of text on buttons:
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{UITextAttributeTextColor : [UIColor whiteColor]}];
} else {
    [[UIToolbar appearance] setTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];
    [[UINavigationBar appearance] setTintColor:[MPColors colorWithColorString:MPColorString0A3B77]];
}

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

[MPUserDataSynchronizer syncUserData];

return YES;
}


问:
How do I remove the DocuSign watermark from a signed PDF?
I have implemented DocuSign in my application for signing the PDF but after making signature some details regarding DocuSign information is displaying in PDF in red color. Please find the Image. Can anyone suggest me how to hide this information from the PDF after making signature?

答:
To elaborate upon Drew's answer:

You're seeing the red watermark on the documents because the Envelope was sent using DocuSign's "demo" environment, which is free and intended for use only as a development/testing environment. (They add the watermark to documents in the "demo" environment to discourage folks from using the "demo" environment for production scenarios without paying for the DocuSign service.)

If you want to send Envelopes and not have the red watermark appear on the documents, you'll need to pay for a DocuSign subscription, and then send your Envelopes using DocuSign's "production" environment.

Also worth noting: if you're using the DocuSign API to send and/or manage Envelopes, you'll need to complete the "API Certification" process to get your Integrator Key approved for use in the production environment, before your API calls will work against production endpoints. For information about that process, see the Go Live with Your DocuSign Integration section here: https://www.docusign.com/developer-center/api-overview#go-live.


问:
Recursive Method Not Returning Expected Results (JAVA)
I was assisting a student with a question about for loops, essentially you have 2 numbers x and y and you want to sum every value from x to y together to get a total. For example 5 to 10 would print 45 (5+6+7+8+9+10). While helping this person I decided to write the program recursively for some practice and noticed that my recursive method wasn't returning 45, instead it just keeps returning 5. If anyone could explain to me what's going on I'd appreciate it! Thanks!</p>

```<code>public class forLoops {

    public static void main(String[] args) {

        int sum = calc(5,10);
        System.out.println(sum);

    }

    public static int calc(int num1, int num2) {

        int sum = calc(num1, num2, 0 );

        return sum;
    }

    public static int calc(int num1, int num2, int total) {

        if(num1 <= num2)
        {
            total += num1;
            num1++;
            System.out.println(num1);
            calc(num1, num2,total);
        }

        return total;
    }

}
</code>```

答:
When calling recursively, assign the result to total. That's the mistake. Java is pass by value. So you have to assign the value to total. </p>

```<code>if(num1 <= num2){
    total += num1;
    num1++;
    System.out.println(num1);
    total=calc(num1, num2,total);
 }
</code>```

<p>Or you can return directly instead of assigning to total. </p>

Body:
I was assisting a student with a question about for loops, essentially you have 2 numbers x and y and you want to sum every value from x to y together to get a total. For example 5 to 10 would print 45 (5+6+7+8+9+10). While helping this person I decided to write the program recursively for some practice and noticed that my recursive method wasn't returning 45, instead it just keeps returning 5. If anyone could explain to me what's going on I'd appreciate it! Thanks!

public class forLoops {

    public static void main(String[] args) {

        int sum = calc(5,10);
        System.out.println(sum);

    }

    public static int calc(int num1, int num2) {

        int sum = calc(num1, num2, 0 );

        return sum;
    }

    public static int calc(int num1, int num2, int total) {

        if(num1 <= num2)
        {
            total += num1;
            num1++;
            System.out.println(num1);
            calc(num1, num2,total);
        }

        return total;
    }

}

Body:
When calling recursively, assign the result to total. That's the mistake. Java is pass by value. So you have to assign the value to total.

if(num1 <= num2){
    total += num1;
    num1++;
    System.out.println(num1);
    total=calc(num1, num2,total);
 }

Or you can return directly instead of assigning to total.


问:
Any drawbacks or gotchas to using Jinja2 templates in Django?
After reading the Jinja2 documentation, I'm interested in employing it in future Django projects.  However, I'm wondering if anyone has encountered any drawbacks or gotchas when using Jinja2 templates with Django?  If so, how did you work around them?

I wouldn't mind hearing about positive experiences either, just to get a good cross section of the best and worst of Jinja2.

答:
Extending Jinja2 is much harder than Django template system (I'm talking about templatetags). While most of inclusion tags functionality can be achieved using macros in Jinja (they even seem to be more appropriate), writing bit more complicated tags is really hard in Jinja (see the docs for yourself).

Other than that, the only obstacle are Django-based habits... ;)

OwnerDisplayName: Soviut

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Soviut

OwnerDisplayName: zgoda


问:
Vim for Windows - What do I type to save and exit from a file?
Using Windows XP I accidentally typed git commit -a instead of git commit -am "My commit message", and now I'm viewing my CMD prompt filled with the file version of my commit message ("Please enter the commit message for your..."). I've added my message to the top, but now I can't figure out how to save and leave. I tried to press Ctrl + W + Q, but it doesn't do anything, but add ^ where the cursor is.

I also tried Esc first, and then Ctrl + W + Q, but it says No write since last change (add ! to override).

答:
Instead of telling you how you could execute a certain command (Esc:wq), I can provide you two links that may help you with VIM:

http://bullium.com/support/vim.html provides an HTML quick reference card

http://tnerual.eriogerg.free.fr/vim.html provides a PDF quick reference card in several languages, optimized for print-out, fold and put on your desk drawer

However, the best way to learn Vim is not only using it for Git commits, but as a regular editor for your everyday work.

If you're not going to switch to Vim, it's nonsense to keep its commands in mind. In that case, go and set up your favourite editor to use with Git.

ContentLicense: CC BY-SA 4.0


问:
How can I most easily authenticate with gspread in a Jupyter notebook?
Many of my partners at work are comfortable mainly with spreadsheets, and not python, scala, java, SQL, etc. These people are non-technical, but they need data and it's my job to get it in their hands. Reading about Google colaboratory, and their example notebook on io, I discovered gspread and the apparent ease of authentication:

```<code>from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())
</code>```

We use a local deployment of Jupyter with several customizations for simplifying access to Presto, Hive, Spark, etc, so I tried installing colab in our environment to no avail (it's not open source). The next best approach I found was using oauth2, but this seems to require a GCP account for access to the Google Developer's Console. This seems overly complicated for something that boils down to authenticating with a remote service.

So, group mind, how do you most easily authenticate with gspread in a jupyter notebook?

答:
I can explain the ingredients that make this work in Colab:

the call to authenticate_user invokes gcloud auth login --enable-gdrive-access (with other args).

We then set the GOOGLE_APPLICATION_CREDENTIALS environment variable to an exported copy of those credentials.

Any code using the Application Default Credentials can now discover those credentials; in particular, oauth2client finds them (as in the sample above).

As always, you should be careful about where you put credentials; in the case of Colab, we have a fairly controlled system, and are OK with this setup (though as with all things, it could change in the future).

Body:
Many of my partners at work are comfortable mainly with spreadsheets, and not python, scala, java, SQL, etc. These people are non-technical, but they need data and it's my job to get it in their hands. Reading about Google colaboratory, and their example notebook on io, I discovered gspread and the apparent ease of authentication:

from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())

We use a local deployment of Jupyter with several customizations for simplifying access to Presto, Hive, Spark, etc, so I tried installing colab in our environment to no avail (it's not open source). The next best approach I found was using oauth2, but this seems to require a GCP account for access to the Google Developer's Console. This seems overly complicated for something that boils down to authenticating with a remote service.

So, group mind, how do you most easily authenticate with gspread in a jupyter notebook?


问:
Getting a select's value with javascript
I have the following condensed form

```<code><form name="thecars">
<select name="cars">
    <option value="mustang">Mustang</option>
    <option value="pinto">Pinto</option>
    <option value="pinto">Chevelle</option>
    <option value="pinto">Other</option>
</select>
</form>
</code>```

I am trying to get the value of the selected car by the following but it is not working

```<code>selectedCar = document.forms["thecars"].elements["cars"].options[thecars.cars.options.selectedIndex].value;
</code>```

答:
Correct code would be:

```<code>var oForm = document.forms["thecars"];
var oDDL = oForm.elements["cars"];
var selectedCar = oDDL.value;
</code>```

You can't get reference to the form by just using its name.

Body:
I have the following condensed form

<form name="thecars">
<select name="cars">
    <option value="mustang">Mustang</option>
    <option value="pinto">Pinto</option>
    <option value="pinto">Chevelle</option>
    <option value="pinto">Other</option>
</select>
</form>

I am trying to get the value of the selected car by the following but it is not working

selectedCar = document.forms["thecars"].elements["cars"].options[thecars.cars.options.selectedIndex].value;

Body:
Correct code would be:

var oForm = document.forms["thecars"];
var oDDL = oForm.elements["cars"];
var selectedCar = oDDL.value;

You can't get reference to the form by just using its name.


问:
Full Text query run slow first time and then fast
Anyone has some info about this behaviour? I'm running on the same db this query

```<code>SELECT
                mk.IdMedia
            FROM
                mediakeyword mk
            WHERE
                MATCH(mk.SearchText) AGAINST('+"france"' IN BOOLEAN MODE) > 0
</code>```

The plan for this

```<code>"id"    "select_type"   "table" "type"  "possible_keys" "key"   "key_len"   "ref"   "rows"  "Extra"
"1" "SIMPLE"    "mk"    "fulltext"  "SearchText"    "SearchText"    "0" \N  "1" "Using where"
</code>```

SearchText has a FullText Index and the engine is MyISAM

The strange behavior is that first time i run the query the computed time is 2,324 s the second time is 0,015 , why?

There is a way to instruct mysql to have the same second behaviour?

答:
FULLTEXT is available in InnoDB; consider migrating.

There are two things that can lead to "first is slow; second is fast":

The first time you run a query, it may need to fetch index and/or data blocks from disk.  The second time, those blocks are cached in RAM, therefore much faster.

The "Query cache", if enabled, records queries and their resultsets.  So, if exactly the same SELECT is run a second time, it can simply look up the result that was previously computed.

Body:
Anyone has some info about this behaviour? I'm running on the same db this query

SELECT
                mk.IdMedia
            FROM
                mediakeyword mk
            WHERE
                MATCH(mk.SearchText) AGAINST('+"france"' IN BOOLEAN MODE) > 0

The plan for this

"id"    "select_type"   "table" "type"  "possible_keys" "key"   "key_len"   "ref"   "rows"  "Extra"
"1" "SIMPLE"    "mk"    "fulltext"  "SearchText"    "SearchText"    "0" \N  "1" "Using where"

SearchText has a FullText Index and the engine is MyISAM

The strange behavior is that first time i run the query the computed time is 2,324 s the second time is 0,015 , why?

There is a way to instruct mysql to have the same second behaviour?


问:
Mips32 printing a string that is stores on the stack
I push each character on the stack and I call print_s function:
The output is h instead of hel

```<code>sub $sp, $sp, 4
li $t9, 'h'
sb $t9, 0($sp)
li $t9, 'e'
sb $t9, -1($sp)
li $t9, 'l'
sb $t9, -2($sp)
li $t9, 0      #tried $zero, '0' '\0'
sb $t9, -3($sp)
la $a0, 0($sp)
jal print_s
#code that exits here.
print_s:
    li $v0, 4
    syscall
    jr $ra
</code>```

Any ideas why it doesn't print the string ?

答:
I found the solution:

the reason that this code did not work is because the stack grows downwards(e.g addresses go from high to low. The correct way is to store the string in the opposite order:

```<code>sub $sp, $sp, 4
li $t9, '\0'
sb $t9, 0($sp)
li $t9, 'l'
sb $t9, -1($sp)
li $t9, 'e'
sb $t9, -2($sp)
li $t9, 'h'
sb $t9, -3($sp)
la $a0, -3($sp)
jal print_s
#code that exits here.
print_s:
    li $v0, 4
    syscall
    jr $ra
</code>```

Body:
I push each character on the stack and I call print_s function:
The output is h instead of hel

sub $sp, $sp, 4
li $t9, 'h'
sb $t9, 0($sp)
li $t9, 'e'
sb $t9, -1($sp)
li $t9, 'l'
sb $t9, -2($sp)
li $t9, 0      #tried $zero, '0' '\0'
sb $t9, -3($sp)
la $a0, 0($sp)
jal print_s
#code that exits here.
print_s:
    li $v0, 4
    syscall
    jr $ra

Any ideas why it doesn't print the string ?

Body:
I found the solution:

the reason that this code did not work is because the stack grows downwards(e.g addresses go from high to low. The correct way is to store the string in the opposite order:

sub $sp, $sp, 4
li $t9, '\0'
sb $t9, 0($sp)
li $t9, 'l'
sb $t9, -1($sp)
li $t9, 'e'
sb $t9, -2($sp)
li $t9, 'h'
sb $t9, -3($sp)
la $a0, -3($sp)
jal print_s
#code that exits here.
print_s:
    li $v0, 4
    syscall
    jr $ra


问:
PHP Simplehtmldom: Extra image url from data-src
I am trying to scrape a few images from a website by using the PHP Simplehtmldom library. Normally the image url is found in the 'src' but in this case the image url is found in the 'data-url'. I am having trouble to access the data-url value and I was hoping some could help me out.

Let's say I have the following code:

```<code><section id="imagesContainer">
    <div class="img">
        <img data-src="https://example.com/image1.jpg" alt="imageAlt1">
    </div>
    <div class="img">
        <img data-src="https://example.com/image2.jpg" alt="imageAlt2">
    </div>
    <div class="img">
        <img data-src="https://example.com/image3.jpg" alt="imageAlt3">
    </div>
</section>
</code>```

I attempted to extract the image urls from the data-src with the following code but it doesn't return the image url:

```<code>foreach($html->find('#imagesContainer') as $imagesContainer) {
    foreach($imagesContainer->find('img') as $image) {
        echo $image->data-src;

    }

}
</code>```

How can I extract the image url from the data-src? Is it possible with the simplehtmldom or do I need a regex?

答:
many thanks for your suggestion. This code, using XPath, works to extract the value of the data-url:</p>

```<code> $image->getAttribute('data-src')
</code>```

Body:
I am trying to scrape a few images from a website by using the PHP Simplehtmldom library. Normally the image url is found in the 'src' but in this case the image url is found in the 'data-url'. I am having trouble to access the data-url value and I was hoping some could help me out.

Let's say I have the following code:

I attempted to extract the image urls from the data-src with the following code but it doesn't return the image url:

foreach($html->find('#imagesContainer') as $imagesContainer) {
    foreach($imagesContainer->find('img') as $image) {
        echo $image->data-src;

    }

}

How can I extract the image url from the data-src? Is it possible with the simplehtmldom or do I need a regex?

Body:
many thanks for your suggestion. This code, using XPath, works to extract the value of the data-url:

 $image->getAttribute('data-src')


问:
Ruby on rails - unable to create comments. NoMethodError
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

```<code>class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end
</code>```

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

```<code>class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end
</code>```

Below is the form for section from the show.html.erb for the forum page

```<code><h2>Comments</h2>

<% @forum.comments.each do |comment| %>
<p>
    <%= comment.body %>
</p>

<% end %>

<h2>Add a comment</h2>

<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
    <%= f.label :body %><br/>
    <%= f.text_area :body %>
</p>
<p>
    <%= f.submit %>
</p>
<% end %>
</code>```

And this is the error from rails:

```<code>undefined method `comment' for #<Forum:0x444d518>
</code>```

with the following extract:

```<code>end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end
</code>```

答:
Make sure you have a comments association in the Forum model:

```<code>class Forum < ApplicationRecord
  has_many :comments
end
</code>```

Body:
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end

Below is the form for section from the show.html.erb for the forum page

Comments

<% @forum.comments.each do |comment| %>

    <%= comment.body %>

<% end %>

Add a comment

<%= form_for([@forum, @forum.comments.build]) do |f| %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

And this is the error from rails:

undefined method `comment' for #<Forum:0x444d518>

with the following extract:

end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end

Body:
Make sure you have a comments association in the Forum model:

class Forum < ApplicationRecord
  has_many :comments
end


问:
What does "The dwarfdump binary must exist and must be executable" mean?
I'm trying to build an app for submission to the AppStore..

Each time I try to build it I get a warning during Validate saying:

The dwarfdump binary must exist and
  must be executable: /usr/bin/dwarfdump
  (-19036)

And Apple doesn't allow me to submit the app binary because of this warning. Does anyone know what's wrong?

I tried to Google it but I can't find anything useful..

答:
Try to search for the file dwarfdump on your computer(i.e. using spotlight). In my case it was located in /Developer/usr/bin. Make a symbolic link into /usr/bin

```<code>sudo ln -s /Developer/usr/bin/dwarfdump /usr/bin/
</code>```

Body:
Try to search for the file dwarfdump on your computer(i.e. using spotlight). In my case it was located in /Developer/usr/bin. Make a symbolic link into /usr/bin

sudo ln -s /Developer/usr/bin/dwarfdump /usr/bin/


问:
EntityFrameworkCore Mapping Relationships
I have the following two entities:

```<code>public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }
}
</code>```

This corresponds to two DB tables:

```<code>Company:
  Id uniqueidentifier
  Name varchar

Address:
  Id uniqueidentifier
  Town varchar
  Country varchar
  RelationId uniqueidentifier
</code>```

RelationId is the foreign key which stores the link back to CompanyId.

I can not change either the classes or the tables.

I am trying to figure out how to represent this construct in code first EFCore.

```<code>    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>().ToTable("Companies");
        modelBuilder.Entity<Address>().ToTable("Addresses");

        modelBuilder.Entity<Company>().HasKey(c => c.Id);
        modelBuilder.Entity<Address>().HasKey(c => c.Id);

        ???????????????????????
    }
</code>```

What am I missing in the code above to prevent the creation of a CompanyId foreign key and use the 'RelationId' instead.

答:
Create a Guid RelationId and a Company Company properties in Address, as purposed by @TanvirArjel and use the following fluent configuration:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    .....

    modelBuilder.Entity<Company>()
        .HasOne(c => c.Address)
        .WithOne(a => a.Company)
        .HasForeignKey(a => a.RelationId);
}
</code>```

If an address can have more than one company, change the WithOne by WithMany and the Company property type to ICollection<Company>

Body:
I have the following two entities:

public class Company
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid Id { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }
}

This corresponds to two DB tables:

Company:
  Id uniqueidentifier
  Name varchar

Address:
  Id uniqueidentifier
  Town varchar
  Country varchar
  RelationId uniqueidentifier

RelationId is the foreign key which stores the link back to CompanyId.

I can not change either the classes or the tables.

I am trying to figure out how to represent this construct in code first EFCore.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>().ToTable("Companies");
        modelBuilder.Entity<Address>().ToTable("Addresses");

        modelBuilder.Entity<Company>().HasKey(c => c.Id);
        modelBuilder.Entity<Address>().HasKey(c => c.Id);

        ???????????????????????
    }

What am I missing in the code above to prevent the creation of a CompanyId foreign key and use the 'RelationId' instead.

Body:
Create a Guid RelationId and a Company Company properties in Address, as purposed by @TanvirArjel and use the following fluent configuration:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    .....

    modelBuilder.Entity<Company>()
        .HasOne(c => c.Address)
        .WithOne(a => a.Company)
        .HasForeignKey(a => a.RelationId);
}

If an address can have more than one company, change the WithOne by WithMany and the Company property type to ICollection<Company>