问:
400(Bad request) status code when making request with axios in reactjs
It's working when making a request with postman for when trying to with axios in reactjs its showing 400 status code

I have already tried
- adding removing headers
- adding boundary:--foo

```<code>handleSubmit(event) {
let data = new FormData();
      data.append("username", this.state.username)
      data.append("password", this.state.password)
      data.append("confirm_password", this.state.confirm_password)
      data.append("email", this.state.email)
      event.preventDefault();
      axios({
         method: 'post',
         url: 'http://localhost:8000/api/account/register/',
         data: data,
      headers:{
         "Content-Type":"application/x-www-form-urlencoded; boundary:XXboundaryXX"
      }
      })
         .then((response) => {
             console.log('bitchhh');

         })
         .catch((response) => {
            //handle error
            console.log(response);
         });
   }
</code>```

[]3

答:
If there are any errors in data, rest framework does not return 2xx status codes it always returns 400 bad request. It means there are errors in request you sent.

Postman is also receiving 400 bad request but it is showing response data (error messages).

axios treats 400 status code as error so you would have to handle it in catch block. If you want to access response sent with errors you can access it from

```<code>.catch((err) => {
    //handle error
    console.log(err.response.data);
 });
</code>```

Body:
It's working when making a request with postman for when trying to with axios in reactjs its showing 400 status code

I have already tried
- adding removing headers
- adding boundary:--foo

handleSubmit(event) {
let data = new FormData();
      data.append("username", this.state.username)
      data.append("password", this.state.password)
      data.append("confirm_password", this.state.confirm_password)
      data.append("email", this.state.email)
      event.preventDefault();
      axios({
         method: 'post',
         url: 'http://localhost:8000/api/account/register/',
         data: data,
      headers:{
         "Content-Type":"application/x-www-form-urlencoded; boundary:XXboundaryXX"
      }
      })
         .then((response) => {
             console.log('bitchhh');

         })
         .catch((response) => {
            //handle error
            console.log(response);
         });
   }

[]3

Body:
If there are any errors in data, rest framework does not return 2xx status codes it always returns 400 bad request. It means there are errors in request you sent.

Postman is also receiving 400 bad request but it is showing response data (error messages).

axios treats 400 status code as error so you would have to handle it in catch block. If you want to access response sent with errors you can access it from

.catch((err) => {
    //handle error
    console.log(err.response.data);
 });


来源: stackexchange

问:
What's the formula for Welford's Algorithm for Variance/Std with Batch Updates?
I want to extend Welford's online algorithm to be able to be updated with multiple numbers (in batch) instead of just one at a time: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance

I tried to update the algorithm from the wiki page like this:

```<code># my attempt.
def update1(existingAggregate, newValues):
    (count, mean, M2) = existingAggregate
    count += len(newValues)
    delta = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    mean += delta / count
    delta2 = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    M2 += delta * delta2

    return (count, mean, M2)

# The original two functions from wikipedia.
def update(existingAggregate, newValue):
    (count, mean, M2) = existingAggregate
    count += 1
    delta = newValue - mean
    mean += delta / count
    delta2 = newValue - mean
    M2 += delta * delta2

def finalize(existingAggregate):
    (count, mean, M2) = existingAggregate
    (mean, variance, sampleVariance) = (mean, M2/count, M2/(count - 1))
    if count < 2:
        return float('nan')
    else:
        return (mean, variance, sampleVariance)
</code>```

However, I must not understand it correctly, because the result is wrong:

```<code># example x that might have led to an a = (2, 2.0, 2.0).
x = [1.0, 3.0]
mean = np.mean(x)
count = len(x)
m2 = np.sum(np.subtract(x, [mean] * count)**2)

a = (count, mean, m2)
print(a)
# new batch of values.
b = [5, 3]

</code>```

Note that a = (2, 2.0, 2.0) means that we had 2 observations, and their mean was 2.0.

```<code># update one at a time.
temp = update(a, newValues[0])
result_single = update(temp, newValues[1])
print(finalize(result_single))

# update with my faulty batch function.
result_batch = update1(a, newValues)
print(finalize(result_batch))

</code>```

The correct output should be the one from applying the single number update twice:

```<code>(3.0, 2.0, 2.6666666666666665)
(3.0, 2.5, 3.3333333333333335)
</code>```

What am I missing regarding the correct variance updates? Do I need to update the finalize function as well somehow?

The reason I need to do this, is because I am working with extremely large monthly files (with varying numbers of observations) and I need to get to yearly means and variances.

答:
I am not too familiar with Python, so I will rather stick to a mathematical notation.

To update the mean, you have to do:

```<code>s = sum of new values
c = number of new values
newMean = oldMean + sum_i (newValue[i] - oldMean) / newCount
</code>```

For M2, you have to add another summation:

```<code>newM2 = oldM2 + sum_i ((newValue[i] - newMean) * (newValue[i] - oldMean))
</code>```

I am not sure if you actually save anything with this bulk update as you still have a loop inside.

ContentLicense: CC BY-SA 4.0

Body:
I want to extend Welford's online algorithm to be able to be updated with multiple numbers (in batch) instead of just one at a time: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance

I tried to update the algorithm from the wiki page like this:

# my attempt.
def update1(existingAggregate, newValues):
    (count, mean, M2) = existingAggregate
    count += len(newValues)
    delta = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    mean += delta / count
    delta2 = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    M2 += delta * delta2

    return (count, mean, M2)

# The original two functions from wikipedia.
def update(existingAggregate, newValue):
    (count, mean, M2) = existingAggregate
    count += 1
    delta = newValue - mean
    mean += delta / count
    delta2 = newValue - mean
    M2 += delta * delta2

def finalize(existingAggregate):
    (count, mean, M2) = existingAggregate
    (mean, variance, sampleVariance) = (mean, M2/count, M2/(count - 1))
    if count < 2:
        return float('nan')
    else:
        return (mean, variance, sampleVariance)

However, I must not understand it correctly, because the result is wrong:

# example x that might have led to an a = (2, 2.0, 2.0).
x = [1.0, 3.0]
mean = np.mean(x)
count = len(x)
m2 = np.sum(np.subtract(x, [mean] * count)**2)

a = (count, mean, m2)
print(a)
# new batch of values.
b = [5, 3]

Note that a = (2, 2.0, 2.0) means that we had 2 observations, and their mean was 2.0.

# update one at a time.
temp = update(a, newValues[0])
result_single = update(temp, newValues[1])
print(finalize(result_single))

# update with my faulty batch function.
result_batch = update1(a, newValues)
print(finalize(result_batch))

The correct output should be the one from applying the single number update twice:

(3.0, 2.0, 2.6666666666666665)
(3.0, 2.5, 3.3333333333333335)

What am I missing regarding the correct variance updates? Do I need to update the finalize function as well somehow?

The reason I need to do this, is because I am working with extremely large monthly files (with varying numbers of observations) and I need to get to yearly means and variances.

Body:
I am not too familiar with Python, so I will rather stick to a mathematical notation.

To update the mean, you have to do:

s = sum of new values
c = number of new values
newMean = oldMean + sum_i (newValue[i] - oldMean) / newCount

For M2, you have to add another summation:

newM2 = oldM2 + sum_i ((newValue[i] - newMean) * (newValue[i] - oldMean))

I am not sure if you actually save anything with this bulk update as you still have a loop inside.


问:
laravel can't load pdf file in blade page for diplaying
i tried  to display pdf in "home.blade.php" page but it not displayed
 pdf but showing empty blank page.

i stored pdf file in "public" folder

i tried below 2 different  codes but not work

```<code><iframe src="{{URL::to('/WEBSITE-FILE')}}/test.pdf" width="100%" height="600"></iframe>

<iframe src="WEBSITE-FILE/test.pdf" class="pdf-spacing-verify pdf-view-for-mainnet-verify" id="pdf_display_frame" width="100%" height="500px"></iframe>
</code>```

答:
Alright i thought something was wrong with my code when i try to display pdf in the browser, it was opening in google chrome browser but not in mozilla firefox so it turns out my pdf is in download mode and then i changed it into "Preview in firefox".
Please check in both browser that pdf is in viewing mode.

Firefox browser

Chrome browser

After that  please check that you're pdf file is accessible via URL.

```<code><html>
<body>
<iframe
    src="{{ url('storage/images/sample.pdf') }}"
    style="width:400px; height:500px;"
    frameborder="0"
></iframe>
<object data="{{ url('storage/images/sample.pdf') }}" type="application/pdf"   style="width:400px; height:500px;">
    <p>Alternative text - include a link <a href="{{ url('storage/images/sample.pdf') }}">to the PDF!</a></p>
</object>
<embed src= "{{ url('storage/images/sample.pdf') }}"   style="width:400px; height:500px;">
</body>
</html>
</code>```

In case if you're not be able to access pdf via url, make sure you're path is correct in case of storage : make sure symlink is created.

I hope this helps.

Body:
Alright i thought something was wrong with my code when i try to display pdf in the browser, it was opening in google chrome browser but not in mozilla firefox so it turns out my pdf is in download mode and then i changed it into "Preview in firefox".
Please check in both browser that pdf is in viewing mode.

Firefox browser

Chrome browser

After that  please check that you're pdf file is accessible via URL.

<html>
<body>
<iframe
    src="{{ url('storage/images/sample.pdf') }}"
    style="width:400px; height:500px;"
    frameborder="0"
></iframe>
<object data="{{ url('storage/images/sample.pdf') }}" type="application/pdf"   style="width:400px; height:500px;">
    <p>Alternative text - include a link <a href="{{ url('storage/images/sample.pdf') }}">to the PDF!</a></p>
</object>
<embed src= "{{ url('storage/images/sample.pdf') }}"   style="width:400px; height:500px;">
</body>
</html>

In case if you're not be able to access pdf via url, make sure you're path is correct in case of storage : make sure symlink is created.

I hope this helps.


问:
How Can I Use Order By In Aggregate Function
I have a sql table seems like below

```<code>ID  AccountName Credit Debit CurrentBalance
1   John         10     0     10
2   Smith        20     0     20
3   Angel        0      10    20
4   John         30     0     40
5   Smith        0      10    10
6   Angel        30     0     50
</code>```

Expected Result

```<code>AccountName TotalCredit TotalDebit CurrentBalance
John        40          0          40
Smith       20          10         10
Angel       30          10         50
</code>```

I want the sum of credit and debit of every account and also the latest currentbalance of each account.

I have used this query

```<code>select AccountName,
       SUM(CreditAmount) As CreditAmount,
       SUM(DebitAmount) As DebitAmount,
       MAX(CurrentBalance) As CurrentBalance
from TransactionInfo
GROUP BY AccountName;
</code>```

答:
You can try this-

NOTE: Considering MAX(ID) for a user will be the latest.

```<code>SELECT AccountName,
SUM(CreditAmount) As CreditAmount,
SUM(DebitAmount) As DebitAmount,
(   SELECT CurrentBalance
    FROM TransactionInfo B
    WHERE B.AccountName = A.AccountName
    AND B.ID = (SELECT MAX(C.ID) FROM TransactionInfo C WHERE C.AccountName = A.AccountName)
) AS CurrentBalance
FROM TransactionInfo A GROUP BY AccountName;
</code>```

Body:
I have a sql table seems like below

ID  AccountName Credit Debit CurrentBalance
1   John         10     0     10
2   Smith        20     0     20
3   Angel        0      10    20
4   John         30     0     40
5   Smith        0      10    10
6   Angel        30     0     50

Expected Result

AccountName TotalCredit TotalDebit CurrentBalance
John        40          0          40
Smith       20          10         10
Angel       30          10         50

I want the sum of credit and debit of every account and also the latest currentbalance of each account.

I have used this query

select AccountName,
       SUM(CreditAmount) As CreditAmount,
       SUM(DebitAmount) As DebitAmount,
       MAX(CurrentBalance) As CurrentBalance
from TransactionInfo
GROUP BY AccountName;

Body:
You can try this-

NOTE: Considering MAX(ID) for a user will be the latest.

SELECT AccountName,
SUM(CreditAmount) As CreditAmount,
SUM(DebitAmount) As DebitAmount,
(   SELECT CurrentBalance
    FROM TransactionInfo B
    WHERE B.AccountName = A.AccountName
    AND B.ID = (SELECT MAX(C.ID) FROM TransactionInfo C WHERE C.AccountName = A.AccountName)
) AS CurrentBalance
FROM TransactionInfo A GROUP BY AccountName;


问:
How can I do padding in Form made Button on my Controller
I wanna make a small padding in my Button so i can divide the Send Button the form my Mensagem box.

Here is a pic for more details:

I already tried making a style for it didnt seem work.

If there is any other code i should provide, ill edit.

Here is the function that makes the Whole form

```<code>public function contactus(Request $request)
            {
                //Formulário para enviar dados com estilos do w3 css
                $mensagem_default = ['message' => ''];//mensagem default a ser enviada
                //cria um form type
                $form = $this->createFormBuilder($mensagem_default)
                //Adiciona o campo nome
                ->add('name', TextType::class, [
                    'label'=> 'O seu Nome', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])
                //adiciona a empresa
                ->add('enterprise', TextType::class, [
                    'label'=> 'A sua Empresa', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //adiciona o telemovel
                ->add('phone', TextType::class, [
                    'label'=> 'O seu Telemovel', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //Adiciona o campo email
                ->add('email', TextareaType::class, [
                    'label'=> 'Email', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //adiciona o assunto
                ->add('subject', TextType::class, [
                    'label'=> 'Assunto', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //Adiciona o campo mensagem
                ->add('message', TextareaType::class, [
                    'label'=> 'Mensagem', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])
                //Adiciona o campo botão enviar dados
                ->add('send', SubmitType::class, [
                     'attr'=>['class' => 'btn btn-primary']
                ])
                ->getForm();

                // Renderiza os arreio para a página principal e Renderiza o formulario para o body
                return $this -> render('contactus.html.twig', ['page'=> 'contactus', 'form'=> $form ->createView(),]);
                }
</code>```

答:
It looks like you are using bootstrap. If so, you can add a bootstrap utility class for padding .p-1 .p-2 .p-3. But, what I think you really want is a margin above the button, for that you can use .mt-1, I have had problems with the .mt- classes and usually end up using .m-1 combined with .ml-0 to keep the left margin at zero. See here for reference.

```<code>->add('send', SubmitType::class, [
    'attr'=>['class' => 'btn btn-primary m-1 ml-0']
])
</code>```

Alternatively, you should also be able to add an inline style declaration like so:

```<code>->add('send', SubmitType::class, [
    'attr'=>[
        'class' => 'btn btn-primary',
        'style' => 'margin-top:1em;',
    ]
])
</code>```

You can also use customized form rendering in your template, see How to Customize Form Rendering

Body:
I wanna make a small padding in my Button so i can divide the Send Button the form my Mensagem box.

Here is a pic for more details:

I already tried making a style for it didnt seem work.

If there is any other code i should provide, ill edit.

Here is the function that makes the Whole form

public function contactus(Request $request)
            {
                //Formulário para enviar dados com estilos do w3 css
                $mensagem_default = ['message' => ''];//mensagem default a ser enviada
                //cria um form type
                $form = $this->createFormBuilder($mensagem_default)
                //Adiciona o campo nome
                ->add('name', TextType::class, [
                    'label'=> 'O seu Nome', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])
                //adiciona a empresa
                ->add('enterprise', TextType::class, [
                    'label'=> 'A sua Empresa', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //adiciona o telemovel
                ->add('phone', TextType::class, [
                    'label'=> 'O seu Telemovel', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //Adiciona o campo email
                ->add('email', TextareaType::class, [
                    'label'=> 'Email', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //adiciona o assunto
                ->add('subject', TextType::class, [
                    'label'=> 'Assunto', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])

                //Adiciona o campo mensagem
                ->add('message', TextareaType::class, [
                    'label'=> 'Mensagem', 'attr'=>[ 'class' => 'form-control'], 'required' => false
                ])
                //Adiciona o campo botão enviar dados
                ->add('send', SubmitType::class, [
                     'attr'=>['class' => 'btn btn-primary']
                ])
                ->getForm();

                // Renderiza os arreio para a página principal e Renderiza o formulario para o body
                return $this -> render('contactus.html.twig', ['page'=> 'contactus', 'form'=> $form ->createView(),]);
                }

Body:
It looks like you are using bootstrap. If so, you can add a bootstrap utility class for padding .p-1 .p-2 .p-3. But, what I think you really want is a margin above the button, for that you can use .mt-1, I have had problems with the .mt- classes and usually end up using .m-1 combined with .ml-0 to keep the left margin at zero. See here for reference.

->add('send', SubmitType::class, [
    'attr'=>['class' => 'btn btn-primary m-1 ml-0']
])

Alternatively, you should also be able to add an inline style declaration like so:

->add('send', SubmitType::class, [
    'attr'=>[
        'class' => 'btn btn-primary',
        'style' => 'margin-top:1em;',
    ]
])

You can also use customized form rendering in your template, see How to Customize Form Rendering


问:
Git - Diff between branches in old commits
I have this:

```<code>branch: commit 1, commit 2, 3,4
master: commit 1, commit 2, 3,4,5,6,7
</code>```

How can you make a diff between branch after commit 2 (in that point of history) and master in commit 3?

答:
The detailed answer could be:

First checkout branch: git checkout branch

Then run: git log

Get the SHA/commit-id of the commit you want and copy it. (I am calling it SHA1)

Then go back to the master branch: git checkout master

Then run: git log

Get the SHA/commit-id of the commit you want and copy it. (I am calling it SHA2)

Then while staying on Master, you can run: git diff SHA1 SHA2

ContentLicense: CC BY-SA 3.0

Body:
I have this:

branch: commit 1, commit 2, 3,4
master: commit 1, commit 2, 3,4,5,6,7

How can you make a diff between branch after commit 2 (in that point of history) and master in commit 3?


问:
How to raise Exceptions in a COM Server?
How do I raise exceptions in a COM server to be consumed be a COM client? My server and client are written in Delphi if that makes any difference? Basically I have a background thread checking various things in my server. When it is not happy, it should stop whatever the server is doing, and raise an exception. This exception needs to be caught by the client. Not sure how to handle it though.</p>

答:
The simple answer is that you don't. Exceptions are not part of the COM interop specification and so should not cross module boundaries. You indicate errors with status codes.

Catch the exception just before your method exits (in each COM interface method). Turn the result into an error code. If you use an HRESULT then you can consume it as safecall and get the Delphi compiler to re-raise an exception on the other side of the fence.

The always knowledgeable Rob Kennedy points out in a comment that safecall can be used "both sides of the fence" which makes life even easier than outlined above.

I'm not an expert on this at all (hence the need to be educated by Rob's comment). However, the documentation indicates that when you are implementing safecall routines you should override TObject.SafeCallException to convert exceptions into HRESULT error codes. Some of the standard COM related classes provide overriden versions but you may need to add some of your own logic to the mix. The compiler writes implicit Try/Except blocks in safecall routines that handle exceptions by calling this virtual function.


问:
has_many through associations where and select results
So I'm trying to filter results using WHERE condition but it's not working.

```<code>class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
 end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
 end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end
</code>```

and what I'm doing here is:

```<code>patients = Patient.joins(:physicians).includes(:physicians).where(:appointments => {:sick => true })
</code>```

However, what I'm getting is the following:

```<code>"results": {
  "patient": {
    "id": 2,
    "patient_name": "Rob"
   },
   "physicians": [
    {
      "id": 4,
      "physicians_name":...
      "sick":false
    ... ,
    {
      "id": 7,
     "physicians_name":...
     "sick":true
     ...
     ... ,
      {
      "id": 7,
      "physicians_name":...
      "sick":false
     ...
     ]
    }
</code>```

So as you noticed, I'm NOT getting only physicians with sick=true. any suggestions?

Update:
This is my serializer

```<code>class PatientSerializer < ActiveModel::Serializer
  attributes :records

 def records
    { info: records_info }
 end

 def records_info
  object.appointments.map do |a|
  a.attributes.merge(a.physician.attributes)
 end
</code>```

end
end

答:
As the sick attribute is stored on the appointment, you should joins(:appointments), instead of joins(:physicians).

Given that, this should return the results that you're looking for:

```<code>patients = Patient.joins(:appointments).includes(:physicians).where(appointments: { sick: true })
</code>```

The reason for this is that the conditions in the where clause need to reference the joined tables.  Since the physicians table isn't used in the where clause, it's not needed to be explicitly joined; however, the appointments table does need to be explicitly joined.

The includes(:physicians) allows "eager loading" of the physicians records, which prevents this from becoming an N+1 query when accessing each physician's data in the serializer.

Body:
So I'm trying to filter results using WHERE condition but it's not working.

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
 end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
 end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

and what I'm doing here is:

patients = Patient.joins(:physicians).includes(:physicians).where(:appointments => {:sick => true })

However, what I'm getting is the following:

"results": {
  "patient": {
    "id": 2,
    "patient_name": "Rob"
   },
   "physicians": [
    {
      "id": 4,
      "physicians_name":...
      "sick":false
    ... ,
    {
      "id": 7,
     "physicians_name":...
     "sick":true
     ...
     ... ,
      {
      "id": 7,
      "physicians_name":...
      "sick":false
     ...
     ]
    }

So as you noticed, I'm NOT getting only physicians with sick=true. any suggestions?

Update:
This is my serializer

class PatientSerializer < ActiveModel::Serializer
  attributes :records

 def records
    { info: records_info }
 end

 def records_info
  object.appointments.map do |a|
  a.attributes.merge(a.physician.attributes)
 end

end
end

Body:
As the sick attribute is stored on the appointment, you should joins(:appointments), instead of joins(:physicians).

Given that, this should return the results that you're looking for:

patients = Patient.joins(:appointments).includes(:physicians).where(appointments: { sick: true })

The reason for this is that the conditions in the where clause need to reference the joined tables.  Since the physicians table isn't used in the where clause, it's not needed to be explicitly joined; however, the appointments table does need to be explicitly joined.

The includes(:physicians) allows "eager loading" of the physicians records, which prevents this from becoming an N+1 query when accessing each physician's data in the serializer.


问:
Is there any way to make a method check if there is existing unique data in database?
My goal is to create a method in android studio that checks if there is an existing username (which is unique) in my database. But my problem is, I have no idea why my implemented code does not work and returns an error in logcat. The app does not crash however.

In fact, I have tried implementing 2 different methods. The first one is to put all selected existing usernames from the database into an arraylist and use the ArrayList.contains(username) method to see if the arraylist contains the similar username.

The other method I have tried using is to select a username in the database that is the same as my inputted username and see if they are the same. (Might sound confusing but I will show you the code).

MainActivity.java

```<code>DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 1);

UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

            if (mydb.existingUsername(tvUsername.getText().toString()) == false) {
                mydb.insertTable(userInfo);
                Intent intent = new Intent(MainActivity.this, Lobby.class);
                intent.putExtra("username", userInfo.getUsername());
                startActivity(intent);
            } else {
                // some code
            }
</code>```

DatabaseHelper.java

```<code>@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + "(" +
            COLUMN_ID + " integer primary key autoincrement, " +
            COLUMN_USERNAME + " text not null unique, " +
            COLUMN_PASSWORD + " text)");
}

// Method 1 (Commented out)
public ArrayList<UserInfo> existingUsername() {
    UserInfo userInfo;
    ArrayList<UserInfo> userArray = new ArrayList<UserInfo>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        userInfo = new UserInfo(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
        userArray.add(userInfo);
        cursor.moveToNext();
    }
    return userArray;
}

// Method 2 (Currently in use)
public boolean existingUsername(String username) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME + " WHERE " + COLUMN_USERNAME + " = ?", new String[]{username});
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {

        if (cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username) {
            return true;
        } else {
            cursor.moveToNext();
        }
    }
    return false;
}
</code>```

Expected results:

I want it to check if the "username" I put already exists in the database or not. If no, run the "if" statement and go to the next activity. If yes, run the "else" statement.

Actual results:

However, it turns out the code keeps running the "if" statement and goes the next activity whether the inputted username already exists in the database or not. If the inputted username already exists in the database, it gives me this error in the logcat.

Logcat

```<code>019-06-01 14:06:19.774 27199-27199/com.karimun.myapplication E/SQLiteDatabase: Error inserting password=232323 username=Igor
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: users.username (code 2067 SQLITE_CONSTRAINT_UNIQUE)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
    at com.karimun.myapplication.DatabaseHelper.insertTable(DatabaseHelper.java:70)
    at com.karimun.myapplication.MainActivity$2.onClick(MainActivity.java:58)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

答:
You should let SQL do all of the work for you:

```<code>Select count(*) from sometable where username = @username
</code>```

This will return the number of records that contain @username. If the number is 0, then the username does not exist in the table. If it's 1, then the username exists and is unique. If it's greater than 1, then the username exists and is not unique.

Body:
My goal is to create a method in android studio that checks if there is an existing username (which is unique) in my database. But my problem is, I have no idea why my implemented code does not work and returns an error in logcat. The app does not crash however.

In fact, I have tried implementing 2 different methods. The first one is to put all selected existing usernames from the database into an arraylist and use the ArrayList.contains(username) method to see if the arraylist contains the similar username.

The other method I have tried using is to select a username in the database that is the same as my inputted username and see if they are the same. (Might sound confusing but I will show you the code).

MainActivity.java

DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 1);

UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

            if (mydb.existingUsername(tvUsername.getText().toString()) == false) {
                mydb.insertTable(userInfo);
                Intent intent = new Intent(MainActivity.this, Lobby.class);
                intent.putExtra("username", userInfo.getUsername());
                startActivity(intent);
            } else {
                // some code
            }

DatabaseHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + "(" +
            COLUMN_ID + " integer primary key autoincrement, " +
            COLUMN_USERNAME + " text not null unique, " +
            COLUMN_PASSWORD + " text)");
}

// Method 1 (Commented out)
public ArrayList<UserInfo> existingUsername() {
    UserInfo userInfo;
    ArrayList<UserInfo> userArray = new ArrayList<UserInfo>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        userInfo = new UserInfo(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
        userArray.add(userInfo);
        cursor.moveToNext();
    }
    return userArray;
}

// Method 2 (Currently in use)
public boolean existingUsername(String username) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME + " WHERE " + COLUMN_USERNAME + " = ?", new String[]{username});
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {

        if (cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username) {
            return true;
        } else {
            cursor.moveToNext();
        }
    }
    return false;
}

Expected results:

I want it to check if the "username" I put already exists in the database or not. If no, run the "if" statement and go to the next activity. If yes, run the "else" statement.

Actual results:

However, it turns out the code keeps running the "if" statement and goes the next activity whether the inputted username already exists in the database or not. If the inputted username already exists in the database, it gives me this error in the logcat.

Logcat

019-06-01 14:06:19.774 27199-27199/com.karimun.myapplication E/SQLiteDatabase: Error inserting password=232323 username=Igor
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: users.username (code 2067 SQLITE_CONSTRAINT_UNIQUE)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
    at com.karimun.myapplication.DatabaseHelper.insertTable(DatabaseHelper.java:70)
    at com.karimun.myapplication.MainActivity$2.onClick(MainActivity.java:58)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Body:
You should let SQL do all of the work for you:

Select count(*) from sometable where username = @username

This will return the number of records that contain @username. If the number is 0, then the username does not exist in the table. If it's 1, then the username exists and is unique. If it's greater than 1, then the username exists and is not unique.


问:
Custom infoView for array of markers swift
I have an application where I am working with Googlemaps, I am able to create markers for all the coordinates needed but the issue I am facing now is I want to show a custom UIView when a user taps on a marker to show the info associated with that marker

```<code>func showFeaturedProperties(properties: [FeaturedProperties]) {
        self.properties = properties
        properties.forEach { (props) in
            var lat = Double(props.latitude!) as! Double
            var lng = Double(props.longitude!) as! Double

            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude: lat,
                                                     longitude: lng)
            marker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
            marker.isFlat = true
            marker.map = mapView
            if props.typeId == 1 {
                marker.icon = #imageLiteral(resourceName: "_map_rent_icon")
            } else {
                marker.icon = #imageLiteral(resourceName: "_map_buy_icon")
            }

            marker.setIconSize(scaledToSize: .init(width: 25, height: 25))
            marker.iconView?.contentMode = .scaleAspectFit
            self.markers.append(marker)
        }

    }
</code>```

The above code shows the marker on the map, how can I show Details when the marker is clicked?

I have so far extended the GMSMapViewDelegate

```<code>func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? {

        if let index = markers.index(of: marker) {
            let tappedState = properties[index]
            log(tappedState.id)
        }

        let infoView = BaseCardView()

        return infoView
    }
</code>```

this does not work still any help is welcomed

答:
Create infowindow marker view with xib file

```<code>import UIKit
import GoogleMaps
class InfoMarkerView: UIView {

var view:UIView!
var parentVC:StartRideViewController?

override init(frame: CGRect) {
super.init(frame: frame)
setup()
}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}

func setup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = UIViewAutoresizing.flexibleWidth
view.autoresizingMask = UIViewAutoresizing.flexibleHeight
addSubview(view)
}

func loadViewFromNib() -> UIView {
let bundle = Bundle(for:type(of: self))
let nib = UINib(nibName: "InfoMarkerView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}

func UpdateView(marker:GMSMarker){
// set values to labels here
}
}
</code>```

Add GMSMapViewDelegate to your viewcontroller file

```<code>var mapView: GMSMapView!
var infoMarkerView:InfoMarkerView?

 if(latitude != 0 && longitude != 0){
                let position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
                let marker = GMSMarker(position: position)

                var myData = Dictionary<String, Any>()
                myData["title"] = ridername
                myData["snippet"] = ridertime
                myData["photoUrl"] = photoUrl
                myData["position"] = position
                myData["accuracy"] = accuracy
                myData["uid"] = riderUID
                myData["status"] = riderStatus
                marker.userData = myData

                marker.title = ridername
                marker.snippet = ridertime
                marker.position = position
                marker.iconView = self.showImageonMap(imgPath:photoUrl)

                marker.map = self.mapView

            }

// MARK: GMSMapViewDelegate method implementation

func mapView(_ mapView: GMSMapView!, didTapAt coordinate: CLLocationCoordinate2D) {
print("here")
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}

func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay)
{
print(overlay.zIndex)
print("User Tapped Layer: \(overlay)")
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool     {
//let update = GMSCameraUpdate.zoom(by: zoomLevel)
//mapView.animate(with: update)

if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
infoMarkerView = InfoMarkerView(frame: CGRect(x: marker.infoWindowAnchor.x, y: marker.infoWindowAnchor.y, width:180, height: 120))
infoMarkerView?.parentVC = self
// Offset the info window to be directly above the tapped marker
infoMarkerView?.center = mapView.projection.point(for: marker.position)
infoMarkerView?.center.y = (infoMarkerView?.center.y)! - 125
infoMarkerView?.UpdateView(marker: marker)

mapView.addSubview(infoMarkerView!)
return true
}

func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker) {
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}
</code>```

Body:
I have an application where I am working with Googlemaps, I am able to create markers for all the coordinates needed but the issue I am facing now is I want to show a custom UIView when a user taps on a marker to show the info associated with that marker

func showFeaturedProperties(properties: [FeaturedProperties]) {
        self.properties = properties
        properties.forEach { (props) in
            var lat = Double(props.latitude!) as! Double
            var lng = Double(props.longitude!) as! Double

            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude: lat,
                                                     longitude: lng)
            marker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
            marker.isFlat = true
            marker.map = mapView
            if props.typeId == 1 {
                marker.icon = #imageLiteral(resourceName: "_map_rent_icon")
            } else {
                marker.icon = #imageLiteral(resourceName: "_map_buy_icon")
            }

            marker.setIconSize(scaledToSize: .init(width: 25, height: 25))
            marker.iconView?.contentMode = .scaleAspectFit
            self.markers.append(marker)
        }

    }

The above code shows the marker on the map, how can I show Details when the marker is clicked?

I have so far extended the GMSMapViewDelegate

func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? {

        if let index = markers.index(of: marker) {
            let tappedState = properties[index]
            log(tappedState.id)
        }

        let infoView = BaseCardView()

        return infoView
    }

this does not work still any help is welcomed

Body:
Create infowindow marker view with xib file

import UIKit
import GoogleMaps
class InfoMarkerView: UIView {

var view:UIView!
var parentVC:StartRideViewController?

override init(frame: CGRect) {
super.init(frame: frame)
setup()
}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}

func setup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = UIViewAutoresizing.flexibleWidth
view.autoresizingMask = UIViewAutoresizing.flexibleHeight
addSubview(view)
}

func loadViewFromNib() -> UIView {
let bundle = Bundle(for:type(of: self))
let nib = UINib(nibName: "InfoMarkerView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}

func UpdateView(marker:GMSMarker){
// set values to labels here
}
}

Add GMSMapViewDelegate to your viewcontroller file

var mapView: GMSMapView!
var infoMarkerView:InfoMarkerView?

 if(latitude != 0 && longitude != 0){
                let position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
                let marker = GMSMarker(position: position)

                var myData = Dictionary<String, Any>()
                myData["title"] = ridername
                myData["snippet"] = ridertime
                myData["photoUrl"] = photoUrl
                myData["position"] = position
                myData["accuracy"] = accuracy
                myData["uid"] = riderUID
                myData["status"] = riderStatus
                marker.userData = myData

                marker.title = ridername
                marker.snippet = ridertime
                marker.position = position
                marker.iconView = self.showImageonMap(imgPath:photoUrl)

                marker.map = self.mapView

            }

// MARK: GMSMapViewDelegate method implementation

func mapView(_ mapView: GMSMapView!, didTapAt coordinate: CLLocationCoordinate2D) {
print("here")
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}

func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay)
{
print(overlay.zIndex)
print("User Tapped Layer: \(overlay)")
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool     {
//let update = GMSCameraUpdate.zoom(by: zoomLevel)
//mapView.animate(with: update)

if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
infoMarkerView = InfoMarkerView(frame: CGRect(x: marker.infoWindowAnchor.x, y: marker.infoWindowAnchor.y, width:180, height: 120))
infoMarkerView?.parentVC = self
// Offset the info window to be directly above the tapped marker
infoMarkerView?.center = mapView.projection.point(for: marker.position)
infoMarkerView?.center.y = (infoMarkerView?.center.y)! - 125
infoMarkerView?.UpdateView(marker: marker)

mapView.addSubview(infoMarkerView!)
return true
}

func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker) {
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
if infoMarkerView != nil {
    infoMarkerView?.removeFromSuperview()
}
}


问:
Pytorch expected type Long but got type int
I revived an error

```<code> Expected object of scalar type Long but got scalar type Int for argument #3 'index'
</code>```

This is from this line.

```<code>targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1)
</code>```

I am not sure what to do as I tried to convert this to a long using several places. I tried putting a

```<code>.long
</code>```

at the end as well as setting the dtype to be torch.long which still didn't work.

Very similar to this but he didn't do anything to get the answer
"Expected Long but got Int" while running PyTorch script

I have change a lot of the code and here is my last rendition, but is now giving me the same issue.

```<code>    def forward(self, inputs, targets):
            """
            Args:
                inputs: prediction matrix (before softmax) with shape (batch_size, num_classes)
                targets: ground truth labels with shape (num_classes)
            """
            log_probs = self.logsoftmax(inputs)
            targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1)
            if self.use_gpu: targets = targets.to(torch.device('cuda'))
            targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
            loss = (- targets * log_probs).mean(0).sum()
            return loss
</code>```

答:
The dtype of your index argument (i.e., targets.unsqueeze(1).data.cpu()) needs to be torch.int64.

(The error message is a bit confusing: torch.long doesn't exist. But "Long" in PyTorch internals means int64).

Body:
I revived an error

 Expected object of scalar type Long but got scalar type Int for argument #3 'index'

This is from this line.

targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1)

I am not sure what to do as I tried to convert this to a long using several places. I tried putting a

.long

at the end as well as setting the dtype to be torch.long which still didn't work.

Very similar to this but he didn't do anything to get the answer
"Expected Long but got Int" while running PyTorch script

I have change a lot of the code and here is my last rendition, but is now giving me the same issue.

    def forward(self, inputs, targets):
            """
            Args:
                inputs: prediction matrix (before softmax) with shape (batch_size, num_classes)
                targets: ground truth labels with shape (num_classes)
            """
            log_probs = self.logsoftmax(inputs)
            targets = torch.zeros(log_probs.size()).scatter_(1, targets.unsqueeze(1).data.cpu(), 1)
            if self.use_gpu: targets = targets.to(torch.device('cuda'))
            targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
            loss = (- targets * log_probs).mean(0).sum()
            return loss


问:
Make div use all the remaining height of the screen
I need to make the .content div use the remaining screen height.
I don´t know what´s the height of .header - I can´t use calc(100vh - headerHeight)

HTML structure

```<code><html>
    <body>
        <div class="header">header</div>
        <div class="content">content</div>
    </body>
</html>
</code>```

CSS

```<code>html, body {
    height: 100%;
}
</code>```

Tried with

```<code>.content {
    display: flex;
    flex-grow: 1;
}
</code>```

using 100vh didn´t work because it generated some vertical scroll (with the height of the .header)

```<code>.content {
    height: 100vh
}
</code>```

it should look like this

```<code>+-------------------------------+
|            header             |
+-------------------------------+
|                               |
|                               |
|            content            |
|                               |
|                               |
+-------------------------------+
</code>```

答:
Set the  element as your flex container.

Then you can set .content so it's able to grow.

html,
body {
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  flex-direction: column;
}

.header {
  background-color: lightgreen;
}

.content {
  flex: 1 0 auto;
  background-color: lightblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">header</div>
<div class="content">content</div></code>```

For reference, see Basic concepts of flexbox.

Body:
I need to make the .content div use the remaining screen height.
I don´t know what´s the height of .header - I can´t use calc(100vh - headerHeight)

HTML structure

header

content

CSS

html, body {
    height: 100%;
}

Tried with

.content {
    display: flex;
    flex-grow: 1;
}

using 100vh didn´t work because it generated some vertical scroll (with the height of the .header)

.content {
    height: 100vh
}

it should look like this

+-------------------------------+
|            header             |
+-------------------------------+
|                               |
|                               |
|            content            |
|                               |
|                               |
+-------------------------------+

Body:
Set the <body> element as your flex container.

Then you can set .content so it's able to grow.

html,
body {
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  flex-direction: column;
}

.header {
  background-color: lightgreen;
}

.content {
  flex: 1 0 auto;
  background-color: lightblue;
}

<div class="header">header</div>
<div class="content">content</div>

For reference, see Basic concepts of flexbox.


问:
How to source a script with environment variables in a docker build process?
I'm creating an image that has a similar problem like the following docker project:

Dockerfile

```<code>FROM alpine:3.9.3

COPY ./env.sh /env.sh
RUN source /env.sh
CMD env
</code>```

env.sh

```<code>TEST=test123
</code>```

I built the image with

```<code>docker build -t sandbox .
</code>```

and run it with

```<code>docker run --rm sandbox
</code>```

The output is

```<code>HOSTNAME=72405c43801b
SHLVL=1
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/
</code>```

My environment variable is missing.

In the real project I have to source a longer complex script for the installation for IBM DB2 client that also sets environment variables. How can I achieve it without reading the whole installation process and setting all variables with ENV in the dockerfile?

EDIT:
In the real project the file env.sh is created as part of the installation process and it is not available from outside of the container. The environment variables are set depending on the system it is executed on. If I run it on the host it will set wrong variables in the guest.

Part of the real script is

```<code>if [ -f ${INST_DIR?}/tools/clpplus.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/tools/clpplus.jar a
fi

if [ -f ${INST_DIR?}/tools/antlr-3.2.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/tools/antlr-3.2.jar a
fi

if [ -f ${INST_DIR?}/tools/jline-0.9.93.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/tools/jline-0.9.93.jar a
fi

if [ -f ${INST_DIR?}/java/db2jcc.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/java/db2jcc.jar a
fi

if [ -f ${INST_DIR?}/java/db2jcc_license_cisuz.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/java/db2jcc_license_cisuz.jar a
fi
</code>```

It checks the installation and sets the variables depending on this. Since on the host is no DB2 installation the variables wouldn't be set.

答:
I ended up do a multistep build of the dockerfile in a bash script:

Setup your Dockerfile to include everything up to the point where you need to source a file for environment variables.

In the docker file, source the environment variables and echo the environment to a file.

```<code>RUN  source $(pwd)/buildstepenv_rhel72_64.sh && source /opt/rh/devtoolset-8/enable && env | sort -u  > /tmp.env"
</code>```

Build the image with a tag: docker build -t ${image}_dev .

Run the image using the tag to get the environment variables
and add them to the end of the docker file

```<code>docker run --rm  ${image}_dev cat /tmp.env | sed 's/$/"/;s/=/="/;s/^/ENV /'  >>  logs/docker/Dockerfile.${step}
</code>```

Construct the remainder of your dockerfile.

Body:
I'm creating an image that has a similar problem like the following docker project:

Dockerfile

FROM alpine:3.9.3

COPY ./env.sh /env.sh
RUN source /env.sh
CMD env

env.sh

TEST=test123

I built the image with

docker build -t sandbox .

and run it with

docker run --rm sandbox

The output is

HOSTNAME=72405c43801b
SHLVL=1
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/

My environment variable is missing.

In the real project I have to source a longer complex script for the installation for IBM DB2 client that also sets environment variables. How can I achieve it without reading the whole installation process and setting all variables with ENV in the dockerfile?

EDIT:
In the real project the file env.sh is created as part of the installation process and it is not available from outside of the container. The environment variables are set depending on the system it is executed on. If I run it on the host it will set wrong variables in the guest.

Part of the real script is

if [ -f ${INST_DIR?}/tools/clpplus.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/tools/clpplus.jar a
fi

if [ -f ${INST_DIR?}/tools/antlr-3.2.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/tools/antlr-3.2.jar a
fi

if [ -f ${INST_DIR?}/tools/jline-0.9.93.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/tools/jline-0.9.93.jar a
fi

if [ -f ${INST_DIR?}/java/db2jcc.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/java/db2jcc.jar a
fi

if [ -f ${INST_DIR?}/java/db2jcc_license_cisuz.jar ]; then
    AddRemoveString CLASSPATH ${INST_DIR?}/java/db2jcc_license_cisuz.jar a
fi

It checks the installation and sets the variables depending on this. Since on the host is no DB2 installation the variables wouldn't be set.

Body:
I ended up do a multistep build of the dockerfile in a bash script:

Setup your Dockerfile to include everything up to the point where you need to source a file for environment variables.

In the docker file, source the environment variables and echo the environment to a file.

RUN  source $(pwd)/buildstepenv_rhel72_64.sh && source /opt/rh/devtoolset-8/enable && env | sort -u  > /tmp.env"

Build the image with a tag: docker build -t ${image}_dev .

Run the image using the tag to get the environment variables
and add them to the end of the docker file

docker run --rm  ${image}_dev cat /tmp.env | sed 's/$/"/;s/=/="/;s/^/ENV /'  >>  logs/docker/Dockerfile.${step}

Construct the remainder of your dockerfile.


问:
Automatically checking for a new version of my application
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.

The problem is that I have no idea about what have to be done on the server side.

I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?

Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?

@pilif : thanks for your detailed answer. There is still something which is unclear for me :

like

http://www.example.com/update?version=1.2.4

Then you can return what ever you want, probably also the download-URL of the installer of the new version.

How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the ?version=1.2.4 part in order to return something accordingly ?

答:
The simplest way to make this happen is to fire an HTTP request using a library like libcurl and make it download an ini or xml file which contains the online version and where a new version would be available online.

After parsing the xml file you can determine if a new version is needed and download the new version with libcurl and install it.

OwnerDisplayName: Jérôme

LastEditorDisplayName: Jérôme

OwnerDisplayName: StormRider

ContentLicense: CC BY-SA 2.5


问:
Is there a speed difference in MySQL operations?
I was discussing speed of MySQL statements and someone asked me: Between SELECT, INSERT, UPDATE, and DELETE, which is faster and why?

I didn't know the answer. Does anyone know if one is faster than the other, and if so, why? Or are they all generally the same speed?

答:
Assuming simple queries and common usage scenarios and configurations, SELECTs will be fastest because they're both most easily cached (by everything - the CPU, disk, OS, MySQL memory, and the MySQL query cache) and most frequently executed (allowing said caches to be useful).

All other operations are writes, which are much more time consuming and cannot be cached. The operating time of even simple write queries is often highly dependent on how much read load (SELECT queries) the server is under.

OwnerDisplayName: rocket

OwnerDisplayName: wuputah


问:
Asserting an exception thrown from a mock object constructor
Assume: VS2010, .NET 4, C#, NUnit, Moq

I am new to TDD and came across this issue while working through a project.

Given the class:

```<code>public abstract class MyFileType
{
    public MyFileType(String fullPathToFile)
    {
        if (!File.Exists(fullPathToFile))
        {
            throw new FileNotFoundException();
        }

        // method continues

    }
}
</code>```

I am trying to test it using the method:

```<code>[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    String nonexistingPath = "C:\\does\\not\\exist\\file.ext";
    var mock = new Mock<MyFileType>(nonexistingPath);
}
</code>```

The test fails and NUnit reports an exception was never thrown.

I did find a section in the NUnit docs talking about asserting with exceptions, but the examples didn't seem like what I am trying to do. I am still getting started with NUnit and Moq so I may be going about this the wrong way.

UPDATE:

To help clarify why this example uses an abstract class, it is the base class of a series file types where only the loading and disposing of the data would differ between subclassed types. My initial thought was to put the logic for open/setup into a base class since it is the same for all types.

答:
Assuming you're using the latest version of NUnit (you should) then the ExpectedException attribute has been deprecated.

You should instead use the following:

```<code>var exception = Assert.Throws<FileNotFoundException> (() => new MyFileType (nonExistingPath));
Assert.That (exception, Is.Not.Null);  // Or you can check for exception text...
</code>```

No need to use a mock there.
In fact, the mock does nothing interesting in your example.

Body:
Assume: VS2010, .NET 4, C#, NUnit, Moq

I am new to TDD and came across this issue while working through a project.

Given the class:

public abstract class MyFileType
{
    public MyFileType(String fullPathToFile)
    {
        if (!File.Exists(fullPathToFile))
        {
            throw new FileNotFoundException();
        }

        // method continues

    }
}

I am trying to test it using the method:

[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    String nonexistingPath = "C:\\does\\not\\exist\\file.ext";
    var mock = new Mock<MyFileType>(nonexistingPath);
}

The test fails and NUnit reports an exception was never thrown.

I did find a section in the NUnit docs talking about asserting with exceptions, but the examples didn't seem like what I am trying to do. I am still getting started with NUnit and Moq so I may be going about this the wrong way.

UPDATE:

To help clarify why this example uses an abstract class, it is the base class of a series file types where only the loading and disposing of the data would differ between subclassed types. My initial thought was to put the logic for open/setup into a base class since it is the same for all types.

Body:
Assuming you're using the latest version of NUnit (you should) then the ExpectedException attribute has been deprecated.

You should instead use the following:

var exception = Assert.Throws<FileNotFoundException> (() => new MyFileType (nonExistingPath));
Assert.That (exception, Is.Not.Null);  // Or you can check for exception text...

No need to use a mock there.
In fact, the mock does nothing interesting in your example.


问:
My BottomAppBar is covering the last row in my RecyclerView
My reclerview's last row is being covered by my bottom app bar.

My code is as follows:

activity_home.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"/>

            <com.google.android.material.bottomappbar.BottomAppBar
                    android:id="@id/BottomAppBar_fromHomeActivity_Main"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    app:fabAlignmentMode="center"
                    app:navigationIcon="@drawable/ic_menu_dark"
                    app:menu="@menu/menu_bottomappbar_main"/>

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                    android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_add_dark"
                    android:backgroundTint="@color/colorAccent"
                    app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>
</code>```

My reclerview is in a fragment from my home activity:

fragment.xml

```<code><layout
    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">

<androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/todoList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</layout>
</code>```

However, the last row is only half visible as such:

From the material guidelines, the Bottom App Bar and FAB SHOULD be inside a coordinator layout for them to work together. So how am i supposed to lift my recyclerview above the bottom app bar so that the last row is visible too?

I don't want to add padding or margin at the end because it doesn't seem to be good coding...

Please help!

答:
Try to add a constraint for the recyclerView to the bottom of the parent
app:layout_constraintBottom_toBottomof="parent"</p>

Body:
My reclerview's last row is being covered by my bottom app bar.

My code is as follows:

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>

<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"/>

            <com.google.android.material.bottomappbar.BottomAppBar
                    android:id="@id/BottomAppBar_fromHomeActivity_Main"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    app:fabAlignmentMode="center"
                    app:navigationIcon="@drawable/ic_menu_dark"
                    app:menu="@menu/menu_bottomappbar_main"/>

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                    android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_add_dark"
                    android:backgroundTint="@color/colorAccent"
                    app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>

My reclerview is in a fragment from my home activity:

fragment.xml

<layout
    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">

<androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/todoList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</layout>

However, the last row is only half visible as such:

From the material guidelines, the Bottom App Bar and FAB SHOULD be inside a coordinator layout for them to work together. So how am i supposed to lift my recyclerview above the bottom app bar so that the last row is visible too?

I don't want to add padding or margin at the end because it doesn't seem to be good coding...

Please help!


答:
You don't show your insertTable(userInfo) method but if you use (assuming you are using the execSQL method to insert) then using INSERT OR IGNORE instead of INSERT then the duplicate will be ignored.

However, if instead you use the insert method (this effectively uses INSERT OR IGNORE). It returns the rowid, as a long, of the inserted row, if the row wasn't inserted then it returns -1. So checking the return value will tell you that for some reason (likely a duplicate) that the row wasn't inserted (so negates the need for a pre-check and the associated overheads).

As you have defined the ID columns using integer primary key autoincrement, this column is an alias of the rowid column (so the value of rowid will be the same as the ID column).

The following is the code as it could perhaps be, based upon what can be gleaned from the available code.

```<code>public long insertTable(UserInfo userInfo) {

    ContentValues cv = new ContentValues();
    SQliteDatabase db = this.getWritableDatabase();
    cv.put(COLUMN_USERNAME,userInfo.getUserName());
    cv.put(COLUMN_PASSWORD,userInfo.getPassword());
    return db.insert(TABLE_NAME,null,cv);
}
</code>```

Note as this has the same name and signature this would have to replace your existing method or be named differently.

Note getPassword may be the wrong method used to get the password value from the UserInfo

The code in MainActivity.java could then be :-

```<code>        UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

        long id;
        if (id = mydb.insertTable(userInfo) > 0) {
            Intent intent = new Intent(MainActivity.this, Lobby.class);
            intent.putExtra("username", userInfo.getUsername());
            intent.putExtra("userid",id); //<<<<<<<<<< you now have the id
            startActivity(intent);
        } else {
            // some code because user was not added
        }
</code>```

Note the above is in-principle code and may contain some errors as it hasn;t been tested or run.

Title: Is there any way to make a method check if there is existing unique data in database?

Body:
You don't show your insertTable(userInfo) method but if you use (assuming you are using the execSQL method to insert) then using INSERT OR IGNORE instead of INSERT then the duplicate will be ignored.

However, if instead you use the insert method (this effectively uses INSERT OR IGNORE). It returns the rowid, as a long, of the inserted row, if the row wasn't inserted then it returns -1. So checking the return value will tell you that for some reason (likely a duplicate) that the row wasn't inserted (so negates the need for a pre-check and the associated overheads).

As you have defined the ID columns using integer primary key autoincrement, this column is an alias of the rowid column (so the value of rowid will be the same as the ID column).

The following is the code as it could perhaps be, based upon what can be gleaned from the available code.

public long insertTable(UserInfo userInfo) {

    ContentValues cv = new ContentValues();
    SQliteDatabase db = this.getWritableDatabase();
    cv.put(COLUMN_USERNAME,userInfo.getUserName());
    cv.put(COLUMN_PASSWORD,userInfo.getPassword());
    return db.insert(TABLE_NAME,null,cv);
}

Note as this has the same name and signature this would have to replace your existing method or be named differently.

Note getPassword may be the wrong method used to get the password value from the UserInfo

The code in MainActivity.java could then be :-

        UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

        long id;
        if (id = mydb.insertTable(userInfo) > 0) {
            Intent intent = new Intent(MainActivity.this, Lobby.class);
            intent.putExtra("username", userInfo.getUsername());
            intent.putExtra("userid",id); //<<<<<<<<<< you now have the id
            startActivity(intent);
        } else {
            // some code because user was not added
        }

Note the above is in-principle code and may contain some errors as it hasn;t been tested or run.


问:
iphone: strace, dtruss, dtrace or equivalent?
Does anyone know if there is something like strace, dtruss, or dtrace for iPhone?

tester-iPhone:/tmp root$ apt-cache search dtruss
tester-iPhone:/tmp root$ apt-cache search dtrace
tester-iPhone:/tmp root$ apt-cache search trace
tester-iPhone:/tmp root$ apt-get install strace
```

<blockquote>
<pre class="lang-sh prettyprint-override"><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package strace
</code>```

tester-iPhone:/tmp root$ apt-get install dtrace
```

<blockquote>
<pre class="lang-sh prettyprint-override"><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package dtrace
</code>```

tester-iPhone:/tmp root$ apt-get install ltrace
```

<blockquote>
<pre class="lang-sh prettyprint-override"><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package ltrace
</code>```

tester-iPhone:/tmp root$ apt-get install dtruss
```

<blockquote>
<pre class="lang-sh prettyprint-override"><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package dtruss
</code>```

答:
On a real iOS jailbroken device I used frida-trace.

```<code>frida-trace -m "+[NSUUID UUID]" -U "Debug CrackMe"    // trace UUID
frida-trace -m "*[ComVendorDebugger* *]" -U -f com.robot.demo.app   // wildcard trace on Classes
frida-trace -i "getaddrinfo" -i "SSLSetSessionOption" -U -f com.robot.demo.app      // trace SSL setup options on iOS
frida-trace -m "-[NSURLRequest initWithURL:]" -U -f funky-chicken.hello-swift-4-2      // trace URLs
</code>```

This tool also works on jailed devices.  Refer to frida-gadget.

On an iOS simulator I could dtrace calls:

```<code>sudo dtrace -qn 'syscall::ptrace:entry { printf("%s(%d, %d, %d, %d) from %s\n", probefunc, arg0, arg1, arg2, arg3, execname); }'
Password: // you need sudo

ptrace(31, 0, 0, 0) from debugger_challen
</code>```

Body:
Does anyone know if there is something like strace, dtruss, or dtrace for iPhone?

tester-iPhone:/tmp root$ apt-cache search dtruss
tester-iPhone:/tmp root$ apt-cache search dtrace
tester-iPhone:/tmp root$ apt-cache search trace
tester-iPhone:/tmp root$ apt-get install strace

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package strace

tester-iPhone:/tmp root$ apt-get install dtrace

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package dtrace

tester-iPhone:/tmp root$ apt-get install ltrace

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package ltrace

tester-iPhone:/tmp root$ apt-get install dtruss

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package dtruss

Body:
On a real iOS jailbroken device I used frida-trace.

frida-trace -m "+[NSUUID UUID]" -U "Debug CrackMe"    // trace UUID
frida-trace -m "*[ComVendorDebugger* *]" -U -f com.robot.demo.app   // wildcard trace on Classes
frida-trace -i "getaddrinfo" -i "SSLSetSessionOption" -U -f com.robot.demo.app      // trace SSL setup options on iOS
frida-trace -m "-[NSURLRequest initWithURL:]" -U -f funky-chicken.hello-swift-4-2      // trace URLs

This tool also works on jailed devices.  Refer to frida-gadget.

On an iOS simulator I could dtrace calls:

sudo dtrace -qn 'syscall::ptrace:entry { printf("%s(%d, %d, %d, %d) from %s\n", probefunc, arg0, arg1, arg2, arg3, execname); }'
Password: // you need sudo

ptrace(31, 0, 0, 0) from debugger_challen


问:
Self Web Hosting with cpanel - What are detailed software as well as hardware requirements do I need to meet?
I recently deployed my website in the live shared resource server in Linux environment. The website is a Property Listing Application that allows real estate agents to list their properties with 18 High Definition (HD) images per listing.

My Web Hosting Provider configured the php.ini file for upload_max_filesize at 20MB. I tried different possible configurations to increase the upload size whether through php scripting in cpnel or progammatically but I got connection time out without notification error.
I spoke to Techical Support Team who increased the upload_max_filesize to 50MB that allowed me to only upload 16 images of 3MB size each. But when I tried, the image upload failed still.

I noticed that the cpanel  master settings override all the changes. I wanted to upgrade the package for VPS but its features don't convice my ideal server settings.

I decided to concider a self web hosting with control panel. I investigated some possibilities and did some research online to find out how I can accomplish this, I found a few tips that showed possibilities with drawbacks.

I would like to know if it is possible for the self web hosting. What will be server requirements like number of CPUs, Raid, RAM and HDD sizes, etc. What is the most trusted server manufacturers like Cisco, Dell, etc. For Software between Windows and Linux. What is the best fit and why? What is a good cpanel to consider?

答:
I fixed my upload issues. The problem was not upload_max_filsize but the actual image resolution in my script that needed a slight modication. I just modified the image resolution and the upload file image work fine.

For the ideal cpanel, I found cpanel.net


问:
How do I fix my `itoa` implementation so it doesn't print reversed output?
I want to convert an integer into a string of numeric characters in C.

I've tried using itoa, but it's non-standard and not provided by my C library.

I tried to implement my own itoa, but it's not working properly:

```<code>#include <stdlib.h>
#include <stdio.h>

char *itoa(int val, char *buf, int base)
{
    size_t ctr = 0;
    for( ; val; val /= base )
    {
        buf[ctr++] = '0' + (val % base);
    }
    buf[ctr] = 0;
    return buf;
}

int main(void)
{
    unsigned char c = 201;
    char *buf = malloc(sizeof(c)*8+1);
    itoa(c, buf, 2);
    puts(buf);
    free(buf);
}
</code>```

It gives reversed output.

For example, if c is 'A' and base is 2, the output is this: 0101101

The output I want it to be is this: 1011010

How do I fix this issue?

Similar questions

I've already seen this question: Is there a printf converter to print in binary format?

I do not want a printf format specifier to print an integer as binary, I want to convert the binary to a string.

I've already seen this question: Print an int in binary representation using C

Although the answer does convert an integer into a string of binary digits, that's the only thing it can do.

Restrictions

I want itoa to be able to work with other bases, such as 10, 8, etc. and print correctly (i.e. 12345 translates to "12345" and not to "11000000111001").

I do not want to use printf or sprintf to do this.

I do not care about the length of the string as long is the result is correct.

I do not want to convert the integer into ASCII characters other than numeric ones, with the exception of bases greater than 10, in which case the characters may be alphanumeric.

The answer must fit this prototype exactly:

```<code>char *itoa(int val, char *buf, int base);
</code>```

There may be a function called nitoa that has this prototype and returns the number of characters required to hold the result of itoa:

```<code>size_t nitoa(int val, int base);
</code>```

答:
How do I fix my itoa implementation so it doesn't print reversed output?

Rather than reverse the string, form it right-to-left.  #4 of @user3386109

I recommend the helper function also receives in a size.

```<code>#include <limits.h>

char* itostr(char *dest, size_t size, int a, int base) {
  // Max text needs occur with itostr(dest, size, INT_MIN, 2)
  char buffer[sizeof a * CHAR_BIT + 1 + 1];
  static const char digits[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  if (base < 2 || base > 36) {
    fprintf(stderr, "Invalid base");
    return NULL;
  }

  // Start filling from the end
  char* p = &buffer[sizeof buffer - 1];
  *p = '\0';

  // Work with negative `int`
  int an = a < 0 ? a : -a;

  do {
    *(--p) = digits[-(an % base)];
    an /= base;
  } while (an);

  if (a < 0) {
    *(--p) = '-';
  }

  size_t size_used = &buffer[sizeof(buffer)] - p;
  if (size_used > size) {
    fprintf(stderr, "Scant buffer %zu > %zu", size_used , size);
    return NULL;
  }
  return memcpy(dest, p, size_used);
}
</code>```

Then to provide memory, use a compound literal.

```<code>// compound literal C99 or later
#define INT_STR_SIZE (sizeof(int)*CHAR_BIT + 2)
#define MY_ITOA(x, base) itostr((char [INT_STR_SIZE]){""}, INT_STR_SIZE, (x), (base))
</code>```

Now you can call it multiple times.

```<code>int main(void) {
  printf("%s %s %s %s\n", MY_ITOA(INT_MIN,10), MY_ITOA(-1,10), MY_ITOA(0,10), MY_ITOA(INT_MAX,10));
  printf("%s %s\n", MY_ITOA(INT_MIN,2), MY_ITOA(INT_MIN,36));
  return (0);
}
</code>```

Output

```<code>-2147483648 -1 0 2147483647
-10000000000000000000000000000000 -ZIK0ZK
</code>```

Note: sizeof(c)*8+1 is one too small for INT_MIN, base 2.

Body:
I want to convert an integer into a string of numeric characters in C.

I've tried using itoa, but it's non-standard and not provided by my C library.

I tried to implement my own itoa, but it's not working properly:

#include <stdlib.h>
#include <stdio.h>

char *itoa(int val, char *buf, int base)
{
    size_t ctr = 0;
    for( ; val; val /= base )
    {
        buf[ctr++] = '0' + (val % base);
    }
    buf[ctr] = 0;
    return buf;
}

int main(void)
{
    unsigned char c = 201;
    char *buf = malloc(sizeof(c)*8+1);
    itoa(c, buf, 2);
    puts(buf);
    free(buf);
}

It gives reversed output.

For example, if c is 'A' and base is 2, the output is this: 0101101

The output I want it to be is this: 1011010

How do I fix this issue?

Similar questions

I've already seen this question: Is there a printf converter to print in binary format?

I do not want a printf format specifier to print an integer as binary, I want to convert the binary to a string.

I've already seen this question: Print an int in binary representation using C

Although the answer does convert an integer into a string of binary digits, that's the only thing it can do.

Restrictions

I want itoa to be able to work with other bases, such as 10, 8, etc. and print correctly (i.e. 12345 translates to "12345" and not to "11000000111001").

I do not want to use printf or sprintf to do this.

I do not care about the length of the string as long is the result is correct.

I do not want to convert the integer into ASCII characters other than numeric ones, with the exception of bases greater than 10, in which case the characters may be alphanumeric.

The answer must fit this prototype exactly:

char *itoa(int val, char *buf, int base);

There may be a function called nitoa that has this prototype and returns the number of characters required to hold the result of itoa:

size_t nitoa(int val, int base);

Body:
How do I fix my itoa implementation so it doesn't print reversed output?

Rather than reverse the string, form it right-to-left.  #4 of @user3386109

I recommend the helper function also receives in a size.

#include <limits.h>

char* itostr(char *dest, size_t size, int a, int base) {
  // Max text needs occur with itostr(dest, size, INT_MIN, 2)
  char buffer[sizeof a * CHAR_BIT + 1 + 1];
  static const char digits[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  if (base < 2 || base > 36) {
    fprintf(stderr, "Invalid base");
    return NULL;
  }

  // Start filling from the end
  char* p = &buffer[sizeof buffer - 1];
  *p = '\0';

  // Work with negative `int`
  int an = a < 0 ? a : -a;

  do {
    *(--p) = digits[-(an % base)];
    an /= base;
  } while (an);

  if (a < 0) {
    *(--p) = '-';
  }

  size_t size_used = &buffer[sizeof(buffer)] - p;
  if (size_used > size) {
    fprintf(stderr, "Scant buffer %zu > %zu", size_used , size);
    return NULL;
  }
  return memcpy(dest, p, size_used);
}

Then to provide memory, use a compound literal.

// compound literal C99 or later
#define INT_STR_SIZE (sizeof(int)*CHAR_BIT + 2)
#define MY_ITOA(x, base) itostr((char [INT_STR_SIZE]){""}, INT_STR_SIZE, (x), (base))

Now you can call it multiple times.

int main(void) {
  printf("%s %s %s %s\n", MY_ITOA(INT_MIN,10), MY_ITOA(-1,10), MY_ITOA(0,10), MY_ITOA(INT_MAX,10));
  printf("%s %s\n", MY_ITOA(INT_MIN,2), MY_ITOA(INT_MIN,36));
  return (0);
}

Output

-2147483648 -1 0 2147483647
-10000000000000000000000000000000 -ZIK0ZK

Note: sizeof(c)*8+1 is one too small for INT_MIN, base 2.


问:
tfs: how to unlock changes
I originally edited a file, which did a checkout.  I received a new computer, and now I want to edit the file.  I don't care about the original edit.

TFS reports that another user has an exclusive lock on the file.  It's not actually another user, it's me, but the machine is different, so the workspace is different.

I tried unlocking with the tf commandline using the following command:

tf lock /lock:none /workspace:oldmachinename;domain\me /recursive $/projectname/directory /s:http:tfs:8080/tfs/project

I get no errors, but when I go into Visual studio 2010 (We're using tfs 2010 as well)  The files remain locked.

What am I doing wrong?

答:
Have you tried using TFS powertools?

Once you have that, you can right-click on your folder or file, and choose Find in Source Control -> Status. After you click Find, it should show you all the check-outs, or files that are checked-out

You should then be able to right-click on the checkout and choose "Undo..".

While this is generally issuing the same command line arguments, I've had good luck with it.

Title: tfs: how to unlock changes


问:
how to find no of attributes in an entity class
```<code> public int getColumnCount() {
            return getClass().getDeclaredFields().length;
        }
    this is the code which return no of attributes of same class,but not anaother class
</code>```

In my service class,I want to know the number of attributes of a
    particular entity class.

I have tried a method,which tells the no of attributes present in the
    same class.But i want to know attributes of another class.

could you please help me to reach the requirement.

答:
This is a modified method of the previuos one.

```<code>private int getAllAttributes(Object entityClass) {
        return entityClass.getClass().getDeclaredFields().length;
    }
</code>```

Body:
 public int getColumnCount() {
            return getClass().getDeclaredFields().length;
        }
    this is the code which return no of attributes of same class,but not anaother class

In my service class,I want to know the number of attributes of a
    particular entity class.

I have tried a method,which tells the no of attributes present in the
    same class.But i want to know attributes of another class.

could you please help me to reach the requirement.

Body:
This is a modified method of the previuos one.

private int getAllAttributes(Object entityClass) {
        return entityClass.getClass().getDeclaredFields().length;
    }


答:
If I were you I would consider the following code.

html,
body {
  height: 100%;
}

.content {
  display: flex;
  flex-grow: 1;
  background: khaki;
  height: 100%;
}

.wraper {
  height: 100vh;
  background: pink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<body>
  <div class="wraper">
    <div class="header">header</div>
    <div class="content">content</div>
  </div>
</body>

</html></code>```

Title: Make div use all the remaining height of the screen

Body:
If I were you I would consider the following code.

html,
body {
  height: 100%;
}

.content {
  display: flex;
  flex-grow: 1;
  background: khaki;
  height: 100%;
}

.wraper {
  height: 100vh;
  background: pink;
}

<html>

<body>
  <div class="wraper">
    <div class="header">header</div>
    <div class="content">content</div>
  </div>
</body>

</html>