问:
Failed to convert value of type java.util.HashMap to String but no hashmap in code?
I am trying to display data that has been added to my Firebase database to android. The data is uploaded to the database fine, but I get the following error when I try to display it through a phone or emulator:

com.google.firebase.database.DatabaseException: Failed to convert
  value of type java.util.HashMap to String

at the following:

com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:147)

This is the code at line 146 and 147:

```<code>protected T parseSnapshot(DataSnapshot snapshot) {
    return snapshot.getValue(mModelClass);
}
</code>```

This error causes the application to crash and not run. I believe the error is to due with this piece of code in my MainActivity class as when I remove the .child element the app will run, but obviously not display the data.

```<code>mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
</code>```

I'm not sure why this error is being thrown as the only data types I have in the database are Strings, and the child "Blog" is spelled correctly in my database.

Another important piece of info:
The app will run when I delete the "Blog" child in firebase. However, once I submit data to firebase the error occurs and my app crashes.

Any help would be appreciated,

This class displays the data:

```<code>public class MainActivity extends AppCompatActivity {

    private RecyclerView mPostList;
    private DatabaseReference mDatabase;

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

        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

        mPostList = (RecyclerView) findViewById(R.id.post_list);
        mPostList.setHasFixedSize(true);
        mPostList.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
                Blog.class,
                R.layout.post_row,
                BlogViewHolder.class,
                mDatabase
                ) {
            @Override
            protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {

                viewHolder.setTitle(model.getTitle());
                viewHolder.setDesc(model.getDesc());
                viewHolder.setImage(getApplicationContext(), model.getImage());
            }
        };

        mPostList.setAdapter(firebaseRecyclerAdapter);
    }

    public static class BlogViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public BlogViewHolder(View itemView) {
            super(itemView);

            mView = itemView;
        }

        public void setTitle(String title) {
            TextView post_title = (TextView)mView.findViewById(R.id.post_title);
            post_title.setText(title);
        }

        public void setDesc(String desc) {
            TextView post_desc = (TextView)mView.findViewById(R.id.post_desc);
            post_desc.setText(desc);
        }

        public void setImage(Context ctx, String image) {
            ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
            Picasso.with(ctx).load(image).into(post_image);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId()== R.id.action_add){
            startActivity(new Intent(MainActivity.this, PostActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

This class posts data to firebase:

```<code>package infectionapp.com.infectionui;

public class PostActivity extends AppCompatActivity {

    private ImageButton mSelectImage;
    private Uri  mImageUri = null;
    private EditText mPostTitle;
    private EditText mPostDesc;
    private Button mSubmitBtn;

    private StorageReference mStorage;
    private DatabaseReference mDatabase;

   // private ProgressBar mProgress;
    private static final int GALLERY_REQUEST = 1;

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

        //Directs to root firebase storage
        mSelectImage = (ImageButton) findViewById(R.id.imageSelect);

        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

        mPostTitle = (EditText) findViewById(R.id.titleField);
        mPostDesc = (EditText)findViewById(R.id.descField);
        mSubmitBtn = (Button) findViewById(R.id.submitBtn);

    //    mProgress = new ProgressBar(this);

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startPosting();

            }
        });

        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, GALLERY_REQUEST);
            }
        });
    }

    private void startPosting() {

       final String title_val = mPostTitle.getText().toString().trim();
       final String desc_val = mPostDesc.getText().toString().trim();

        if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null){
                StorageReference filepath = mStorage.child("Post_Images").child(mImageUri.getLastPathSegment());

                filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Uri downloadUrl = taskSnapshot.getDownloadUrl();

                        //Creates unique ID for post
                        DatabaseReference newPost = mDatabase.push();
                        newPost.child("title").setValue(title_val);
                        newPost.child("desc").setValue(desc_val);
                        newPost.child("image").setValue(downloadUrl).toString();

                        startActivity(new Intent(PostActivity.this, MainActivity.class));
                    }
                });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
            mImageUri = data.getData();
            mSelectImage.setImageURI(mImageUri);

        }
    }
}
</code>```

Database structure:

Child nodes within children:

Code screenshot

Error of updated code

答:
To get that data in the simplest way, i recomand you using this code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference blogRef = rootRef.child("Blog");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String desc = ds.child("desc").getValue(String.class);
            String title = ds.child("title").getValue(String.class);
            String image = ds.child("image").child("path").getValue(String.class);
            Log.d("TAG", desc + " / " + title + " / " + image);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
blogRef.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be:

```<code>tst / test / /v0/b/infectionui...
</code>```

As you see, i have used String class. This is what you need to use also in your FirebaseRecyclerAdapter.

If you want to get antoher value from image, just change .child("path") with another child, let's say .child("schemeSpecificPart").

Body:
I am trying to display data that has been added to my Firebase database to android. The data is uploaded to the database fine, but I get the following error when I try to display it through a phone or emulator:

com.google.firebase.database.DatabaseException: Failed to convert
  value of type java.util.HashMap to String

at the following:

com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:147)

This is the code at line 146 and 147:

protected T parseSnapshot(DataSnapshot snapshot) {
    return snapshot.getValue(mModelClass);
}

This error causes the application to crash and not run. I believe the error is to due with this piece of code in my MainActivity class as when I remove the .child element the app will run, but obviously not display the data.

mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

I'm not sure why this error is being thrown as the only data types I have in the database are Strings, and the child "Blog" is spelled correctly in my database.

Another important piece of info:
The app will run when I delete the "Blog" child in firebase. However, once I submit data to firebase the error occurs and my app crashes.

Any help would be appreciated,

This class displays the data:

public class MainActivity extends AppCompatActivity {

    private RecyclerView mPostList;
    private DatabaseReference mDatabase;

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

        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

        mPostList = (RecyclerView) findViewById(R.id.post_list);
        mPostList.setHasFixedSize(true);
        mPostList.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
                Blog.class,
                R.layout.post_row,
                BlogViewHolder.class,
                mDatabase
                ) {
            @Override
            protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {

                viewHolder.setTitle(model.getTitle());
                viewHolder.setDesc(model.getDesc());
                viewHolder.setImage(getApplicationContext(), model.getImage());
            }
        };

        mPostList.setAdapter(firebaseRecyclerAdapter);
    }

    public static class BlogViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public BlogViewHolder(View itemView) {
            super(itemView);

            mView = itemView;
        }

        public void setTitle(String title) {
            TextView post_title = (TextView)mView.findViewById(R.id.post_title);
            post_title.setText(title);
        }

        public void setDesc(String desc) {
            TextView post_desc = (TextView)mView.findViewById(R.id.post_desc);
            post_desc.setText(desc);
        }

        public void setImage(Context ctx, String image) {
            ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
            Picasso.with(ctx).load(image).into(post_image);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId()== R.id.action_add){
            startActivity(new Intent(MainActivity.this, PostActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }
}

This class posts data to firebase:

package infectionapp.com.infectionui;

public class PostActivity extends AppCompatActivity {

    private ImageButton mSelectImage;
    private Uri  mImageUri = null;
    private EditText mPostTitle;
    private EditText mPostDesc;
    private Button mSubmitBtn;

    private StorageReference mStorage;
    private DatabaseReference mDatabase;

   // private ProgressBar mProgress;
    private static final int GALLERY_REQUEST = 1;

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

        //Directs to root firebase storage
        mSelectImage = (ImageButton) findViewById(R.id.imageSelect);

        mStorage = FirebaseStorage.getInstance().getReference();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");

        mPostTitle = (EditText) findViewById(R.id.titleField);
        mPostDesc = (EditText)findViewById(R.id.descField);
        mSubmitBtn = (Button) findViewById(R.id.submitBtn);

    //    mProgress = new ProgressBar(this);

        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startPosting();

            }
        });

        mSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, GALLERY_REQUEST);
            }
        });
    }

    private void startPosting() {

       final String title_val = mPostTitle.getText().toString().trim();
       final String desc_val = mPostDesc.getText().toString().trim();

        if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null){
                StorageReference filepath = mStorage.child("Post_Images").child(mImageUri.getLastPathSegment());

                filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    Uri downloadUrl = taskSnapshot.getDownloadUrl();

                        //Creates unique ID for post
                        DatabaseReference newPost = mDatabase.push();
                        newPost.child("title").setValue(title_val);
                        newPost.child("desc").setValue(desc_val);
                        newPost.child("image").setValue(downloadUrl).toString();

                        startActivity(new Intent(PostActivity.this, MainActivity.class));
                    }
                });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
            mImageUri = data.getData();
            mSelectImage.setImageURI(mImageUri);

        }
    }
}

Database structure:

Child nodes within children:

Code screenshot

Error of updated code

Body:
To get that data in the simplest way, i recomand you using this code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference blogRef = rootRef.child("Blog");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String desc = ds.child("desc").getValue(String.class);
            String title = ds.child("title").getValue(String.class);
            String image = ds.child("image").child("path").getValue(String.class);
            Log.d("TAG", desc + " / " + title + " / " + image);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
blogRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

tst / test / /v0/b/infectionui...

As you see, i have used String class. This is what you need to use also in your FirebaseRecyclerAdapter.

If you want to get antoher value from image, just change .child("path") with another child, let's say .child("schemeSpecificPart").


来源: stackexchange

问:
setinterval vs settimeout
How can run a countdown timer at 7:50 AM for 10 minutes until 8:00AM everyday. After that the shift will close. the timer will be a warning for finishing the work.

I used different flavours of setinterval and settimeout code snippets for some hours now. but i don't know how to proceed.My main question is to use setinterval or setimeout.

1) setinterval: is checking the that the time is 7:50 after every few minutes is ok?

2) settimeout: is it ok to count the seconds of the day. and then proceed with calling the function after those seconds?

This works for me

```<code>window.setInterval(function() {
    var date = new Date();
    if (date.getHours() === 8 && date.getMinutes() === 0) {}
}, 60000);

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
    millisTill10 += 86400000;
}
setTimeout(function() {
    alert("It's 10am!")
}, millisTill10);
</code>```

答:
Run a timer for every minute. Show your warning if the current time falls within your allocation. The problem with this code is that it is only accurate up to a minute - not up to the second.

And running this every second is not a good practice.

```<code>setInterval(function(){

   var d = new Date();
   var h = d.getHours();
   var m = d.getMinutes();

   //Rough estimation for the time between 7.50 and 8.00 here
   if (h === 7 && m >= 50)
      console.log('Warning!');

}, 1000)
</code>```

Now we can do more...

We can get the above routine to kick-start a timeout function which is going to be precise in the interval. It will trigger a countdown timer at the correct time and set alarm for another 24 hours.

var starter = setInterval(function(){

```<code>   var d = new Date();
   var h = d.getHours();
   var m = d.getMinutes();

   //Rough estimation for the time between 7.50 and 8.00 here
   if (h === 7 && m >= 50)
      setTimeout(timer24(), 1000 * 60 * 24)

}, 1000)

function timer24(){

   //Warn every 10 seconds
   var countdown = setInterval(function(){

       console.log('Warning!');

       var d = new Date();
       var h = d.getHours();

       if (h == 8)
          clearInterval(countdown)

    }, 10)

    setTimeout(timer, 1000 * 60 * 24)

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: setinterval vs settimeout

Body:
How can run a countdown timer at 7:50 AM for 10 minutes until 8:00AM everyday. After that the shift will close. the timer will be a warning for finishing the work.

I used different flavours of setinterval and settimeout code snippets for some hours now. but i don't know how to proceed.My main question is to use setinterval or setimeout.

1) setinterval: is checking the that the time is 7:50 after every few minutes is ok?

2) settimeout: is it ok to count the seconds of the day. and then proceed with calling the function after those seconds?

This works for me

window.setInterval(function() {
    var date = new Date();
    if (date.getHours() === 8 && date.getMinutes() === 0) {}
}, 60000);

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
    millisTill10 += 86400000;
}
setTimeout(function() {
    alert("It's 10am!")
}, millisTill10);

Body:
Run a timer for every minute. Show your warning if the current time falls within your allocation. The problem with this code is that it is only accurate up to a minute - not up to the second.

And running this every second is not a good practice.

setInterval(function(){

   var d = new Date();
   var h = d.getHours();
   var m = d.getMinutes();

   //Rough estimation for the time between 7.50 and 8.00 here
   if (h === 7 && m >= 50)
      console.log('Warning!');

}, 1000)

Now we can do more...

We can get the above routine to kick-start a timeout function which is going to be precise in the interval. It will trigger a countdown timer at the correct time and set alarm for another 24 hours.

var starter = setInterval(function(){

   var d = new Date();
   var h = d.getHours();
   var m = d.getMinutes();

   //Rough estimation for the time between 7.50 and 8.00 here
   if (h === 7 && m >= 50)
      setTimeout(timer24(), 1000 * 60 * 24)

}, 1000)

function timer24(){

   //Warn every 10 seconds
   var countdown = setInterval(function(){

       console.log('Warning!');

       var d = new Date();
       var h = d.getHours();

       if (h == 8)
          clearInterval(countdown)

    }, 10)

    setTimeout(timer, 1000 * 60 * 24)

}


问:
traceroute mac in mininet
In mininet I want to find out through which switches ping goes. For example from PC1 (h1) to PC3 (h3). I already tried:

```<code>h1 traceroute mac ip h3
</code>```

or

```<code>11:00:00:00:00:00 traceroute mac 33:00:00:00:00:00
</code>```

But it didnt work. "Normal" traceroute (h1 traceroute h2) is working (only destination address is in output). But I need to find out the path of ping.

答: try to traceroute via the host using xterm, not from mininet cli. try with more than two hosts. </p>

Title: traceroute mac in mininet

Body:
In mininet I want to find out through which switches ping goes. For example from PC1 (h1) to PC3 (h3). I already tried:

h1 traceroute mac ip h3

or

11:00:00:00:00:00 traceroute mac 33:00:00:00:00:00

But it didnt work. "Normal" traceroute (h1 traceroute h2) is working (only destination address is in output). But I need to find out the path of ping.


问:
How to assign static values into the query result - codeigniter
So I have this site which has a select box containing:

```<code>1
2
3
4
</code>```

But I want to change them into a static value like:

```<code>Travel
Housing
Gourmet
Medical
</code>```

There is no specified field name in the database, like Travel,etc. It's purely number. So I have to assign static values representing each number.

The only field names in the db is id, industry_id, company_name. the one I specified above(numbers 1-4) are industry_id.

In my Controller:

```<code>$params["filter"] = $this->Users->get_category();
</code>```

Model:

```<code>$sql = "SELECT industry_id FROM company GROUP BY industry_id ORDER BY industry_id ASC";
$query = $this->db->query($sql);
return $query->result();
</code>```

View:

```<code><select class="form-control" name="field">
<?php foreach($filter as $cat)
{
    echo '<option value="'.$cat->industry_id.'">'.$cat->industry_id.'</option>';
}
?>
</select>
</code>```

How can I do it?

答:
```<code><?php
$a = array();
$b = ['Travel', 'Housing', 'Gourmet','Medical'];
$i = 0;
foreach ($filter as $cat) {
    $a[$cat->industry_id] = $b[$i];
    $i++;
}

?>
<select class="form-control" name="field">
    <?php foreach ($a as $k => $val) {
        echo '<option value="' . $k . '">' . $val . '</option>';
    }
    ?>
</select>
</code>```

Body:
So I have this site which has a select box containing:

1
2
3
4

But I want to change them into a static value like:

Travel
Housing
Gourmet
Medical

There is no specified field name in the database, like Travel,etc. It's purely number. So I have to assign static values representing each number.

The only field names in the db is id, industry_id, company_name. the one I specified above(numbers 1-4) are industry_id.

In my Controller:

$params["filter"] = $this->Users->get_category();

Model:

$sql = "SELECT industry_id FROM company GROUP BY industry_id ORDER BY industry_id ASC";
$query = $this->db->query($sql);
return $query->result();

View:

<select class="form-control" name="field">
<?php foreach($filter as $cat)
{
    echo '<option value="'.$cat->industry_id.'">'.$cat->industry_id.'</option>';
}
?>
</select>

How can I do it?


问:
Portforwarding not working
I recently tried to portforward port 80 on my local IP, but as the tutorial said, it should be open on my external IP, which it's not. But it is open on my local ip thought.

I have portforwarded port 80, range 80 UDP and TCP on my local IP: 192.168.1.170

This is the tutorial i followed: https://www.youtube.com/watch?v=RZTYqTGqtjI

I portforwarded my IP in the router settings.

https://image.ibb.co/hGW4fm/Sk_rmbild_345.png
https://image.ibb.co/exWFmR/Sk_rmbild_344.png

答:
IF THE suggested METHOD DOESN'T WORK FOR YOU , DO THIS :-

GOTO -> SECURITY TAB -> REMOTE MANAGEMENT

Enable the Remote Management (or enter 255.255.255.255 in the field) .

This will enable the you to access your LAN from WAN.

For the record :-

Internal Port is the PORT on which the device in your LAN is serving .
External Port is the port which the user enters in the browser . exp :-  127.184.184.19:8080 .
Here 8080 is the external port . And if a device in your LAN runs a http web server at port 80 , then the internal port would be 22.

If the Above methods don't work , then your ISP might be using Carrier NAT which means you would have a different PUBLIC and WAP ip address .
In this case , you should use the WAN ip address  shown in your router configuration page to access your LAN from internet.  s

Title: Portforwarding not working


问:
MIPS reads 2 integer numbers and then print out the larger one
I'm having trouble trying to complete a MIPS program that take to input integers and prints the larger of the two out.
My code:</p>

```<code>#read 2 integer numbers and print out the larger one
.data # data section
    mes1: .asciiz "\n\nEnter the first integer number: "
    mes2: .asciiz "Enter the second integer number: "
    mes3: .asciiz "The larger integer number is: "
.text # code section
    li $v0, 4 #print a string "mes1"
    la $a0, mes1
    syscall

    li $v0, 5 #read the first integer
    syscall
    move $t0, $v0

    li $v0, 4 #print a string "mes2"
    la $a0, mes2
    syscall

    li $v0, 5 #read the second integer
    syscall
    move $t1, $v0

    addi $t0, $zero, -100  #Get larger integer (the first or the second)
    addi $t1, $zero, -100

    slt $s0, $t0, $t1
    bne $s0, $zero, mes3
    syscall

    li $v0, 4 #print a string "mes3"
    la $a0, mes3
    syscall

    li $v1, 1 #print the larger int number
    move $a0, $v0
    syscall

    li $v0, 10 # system call for exit
    syscall
</code>```

答:
```<code>.data # data section
    mes1: .asciiz "\n\nEnter the first integer number: "
    mes2: .asciiz "Enter the second integer number: "
    mes3: .asciiz "The larger integer number is: "

.text # code section
    li $v0, 4 #print a string "mes1"
    la $a0, mes1
    syscall

    li $v0, 5 #read the first integer
    syscall
    move $t0, $v0

    li $v0, 4 #print a string "mes2"
    la $a0, mes2
    syscall

    li $v0, 5 #read the second integer
    syscall
    move $t1, $v0

    slt $s0, $t0, $t1
    bne $s0, $zero, print_num  #jumps to print_num if $t0 is larger
    move $t1, $t0  #else: $t1 is larger

print_num:
    li $v0, 4 #print a string "mes3"
    la $a0, mes3
    syscall`enter code here`

    li $v0, 1 #print the larger int number
    move $a0, $t1
    syscall
</code>```

Body:
I'm having trouble trying to complete a MIPS program that take to input integers and prints the larger of the two out.
My code:

#read 2 integer numbers and print out the larger one
.data # data section
    mes1: .asciiz "\n\nEnter the first integer number: "
    mes2: .asciiz "Enter the second integer number: "
    mes3: .asciiz "The larger integer number is: "
.text # code section
    li $v0, 4 #print a string "mes1"
    la $a0, mes1
    syscall

    li $v0, 5 #read the first integer
    syscall
    move $t0, $v0

    li $v0, 4 #print a string "mes2"
    la $a0, mes2
    syscall

    li $v0, 5 #read the second integer
    syscall
    move $t1, $v0

    addi $t0, $zero, -100  #Get larger integer (the first or the second)
    addi $t1, $zero, -100

    slt $s0, $t0, $t1
    bne $s0, $zero, mes3
    syscall

    li $v0, 4 #print a string "mes3"
    la $a0, mes3
    syscall

    li $v1, 1 #print the larger int number
    move $a0, $v0
    syscall

    li $v0, 10 # system call for exit
    syscall


问:
Move Files with S3BotoStorage
I'm using S3BotoStorage from django-storages to handle my media and static files on my S3 Bucket for my Django backend.

Everything works as expected, but the backend raises a not ImplementedError because it is not a local filesystem when I call self.image.path on a where Image is a models.Image Field. This is expected behavior.

However I'm using the path to move the image with os.rename (which wouldnt work on my bucket as well). What would be the approach to move that file on the bucket?

答:
Instead of using os to move your file, you should use the storage

To move your file, you can use the read() method on your FileField (or in this case, ImageField), (and eventually use the storage to delete the old file).

```<code>file_content = my_model.my_image.read()
file_name = my_model.my_image.name

# Renaming the file
my_model.my_image = my_model.my_image.save('new_file_name', ContentFile(file_content))

# If you want to delete the original file afterwards:
from django.core.files.storage import default_storage
default_storage.delete(file_name)
</code>```

Title: Move Files with S3BotoStorage

Body:
Instead of using os to move your file, you should use the storage

To move your file, you can use the read() method on your FileField (or in this case, ImageField), (and eventually use the storage to delete the old file).

file_content = my_model.my_image.read()
file_name = my_model.my_image.name

# Renaming the file
my_model.my_image = my_model.my_image.save('new_file_name', ContentFile(file_content))

# If you want to delete the original file afterwards:
from django.core.files.storage import default_storage
default_storage.delete(file_name)


问:
.htaccess processing certain letters
I have an .htaccess file with a rewrite rule that works pretty much everywhere, but when I uploaded the site to a GoDaddy hosting environment, certain letters from the URL disappear. Has anyone ever come across this before? If so, what is the solution?

Thanks in advance!

My .htaccess rule

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

And when I paste URL parameters, here's what shows up

```<code>Array ( [0] => privy_poliy )
</code>```

Instead of

```<code>Array ( [0] => privacy_policy )
</code>```

答: Maybe you have mod_speling loaded on the failing server and that stray miss-spelling exists in the filesystem?</p>

ContentLicense: CC BY-SA 2.5

Title: .htaccess processing certain letters

Body:
I have an .htaccess file with a rewrite rule that works pretty much everywhere, but when I uploaded the site to a GoDaddy hosting environment, certain letters from the URL disappear. Has anyone ever come across this before? If so, what is the solution?

Thanks in advance!

My .htaccess rule

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

And when I paste URL parameters, here's what shows up

Array ( [0] => privy_poliy )

Instead of

Array ( [0] => privacy_policy )


问:
Tagret parent of parent on click Javascript
I have the following html:

```<code><div class="parent-portlet
     ng-mouseenter="hoverIn($event)" ng-mouseleave="hoverOut($event)">
    <div class="portlet-titlebar" ng-click="toggleCollapsed($event)">
        <span class="remove" ng-click="removePortlet()">
               Remove
        </span>
        <span class="add-back" ng-click="addPortlet()">
               Add Back
        </span>
    </div>
</div>
</code>```

I want to somehow catch the "parent-portlet" element when either of the spans are clicked. That is the parent of their parent. Is there a way similar to:

angular.element(event.currentTarget).parentElement();

to do that, but for the parent of the parent?

Thanks in advance.

答:
With jQuery use this code     </p>

```<code>$(“span”).on(“click”,function(){
  $(this).parent().parent().hide();
});
</code>```

<p>Note:- here I use span tag as a selector change it </p>

Body:
I have the following html:

               Remove

               Add Back

I want to somehow catch the "parent-portlet" element when either of the spans are clicked. That is the parent of their parent. Is there a way similar to:

angular.element(event.currentTarget).parentElement();

to do that, but for the parent of the parent?

Thanks in advance.

Body:
With jQuery use this code

$(“span”).on(“click”,function(){
  $(this).parent().parent().hide();
});

Note:- here I use span tag as a selector change it


问:
PHP login access doesn't working in web server
I am making a login system. But, I don't know whats the problem. When I checked by the right email and password or wrong email and password it show my error message Please enter valid Email/Password!! . I am using Php 7.1.7 . Also when I add wrong db username, password and table it doesn't show any error.
My Php code:

```<code>$mysqli = new mysqli('localhost', 'db4245454', 'missed$', 'db424545444');

$query = "SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='";
$result = $mysqli->query($query);
$num_log = $result->num_rows;

if($num_log == 1){

        while($row = $result->fetch_object()){
            echo "Welcome " .   $row->First_Name . ' '. $row->Last_Name;

        }
}else{

    echo "Please enter valid Email/Password!!";
}
</code>```

My database table structure:

答:
Your code is okey problem should be here in your query, maybe you gived data with is not availble in database so num_rows >=0  and != 1

```<code>$query = "SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='";
</code>```

you can use var_dump($result); then die() to see if you got anything from database

PS never use code like this

Body:
I am making a login system. But, I don't know whats the problem. When I checked by the right email and password or wrong email and password it show my error message Please enter valid Email/Password!! . I am using Php 7.1.7 . Also when I add wrong db username, password and table it doesn't show any error.
My Php code:

$mysqli = new mysqli('localhost', 'db4245454', 'missed$', 'db424545444');

$query = "SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='";
$result = $mysqli->query($query);
$num_log = $result->num_rows;

if($num_log == 1){

        while($row = $result->fetch_object()){
            echo "Welcome " .   $row->First_Name . ' '. $row->Last_Name;

        }
}else{

    echo "Please enter valid Email/Password!!";
}

My database table structure:

Body:
Your code is okey problem should be here in your query, maybe you gived data with is not availble in database so num_rows >=0  and != 1

$query = "SELECT * FROM User WHERE Email = 'support@admin.com' AND password = 'Rml2ZXJyMSQ='";

you can use var_dump($result); then die() to see if you got anything from database

PS never use code like this


问:
Qt3D 2.0 billboard transformation
Billboard transformation was depricated since Qt3D 1.0. Now it is replaced with lookAt transformation.
I have created plane inside Qt3D context. (took it from Qt3D example found  here) and added QLookAtTransform to it.
But both:

```<code>planeEntity->lookAtTransform()->setViewCenter(cameraEntity->position());
</code>```

and

```<code>planeEntity->lookAtTransform()->setViewVector(cameraEntity->position());
</code>```

give no result. Plane disappear from scene.

Class reference found here give no explanation of how to use it.

How must QLookAtTransform be used to act like billboard transformation?

答: See my answer at Gamedev, the procedure is quite simple once you have the view matrix. The view matrix can be acquired through the appropriate getter of your Camera object. If you want to know more, there is also a link which gives you the detailed derivation.

Title: Qt3D 2.0 billboard transformation

Body:
Billboard transformation was depricated since Qt3D 1.0. Now it is replaced with lookAt transformation.
I have created plane inside Qt3D context. (took it from Qt3D example found  here) and added QLookAtTransform to it.
But both:

planeEntity->lookAtTransform()->setViewCenter(cameraEntity->position());

and

planeEntity->lookAtTransform()->setViewVector(cameraEntity->position());

give no result. Plane disappear from scene.

Class reference found here give no explanation of how to use it.

How must QLookAtTransform be used to act like billboard transformation?


问:
Box height is not as desired size in smaller devices- css
I'm facing an issue in matching the size of a  box to mobile(using bootstrap)
I have got 3 boxes, number 1 and 2 are images and number 3 has text,
and it looks like this

when I resize the screen to mobile size this is what happens(box number 3 is higher or in some devices shorter than box number 2, like here:error

I need it to look like that (box number 3 in the same height as 2):desired output

I tried to set max height and min hight to box3 but this is not the solution because it doesn't match to all the devices.

html:

```<code> <section id="carousel-section">

  <div class="container-fluid">

     <div class="row feature">
         <div class="col-lg-8 col-xl-8 col-md-12 col-xs-12 col-sm-12 ">
             <div class="carousel-margin">
<div id="myCarousel" class="carousel1 slide container-carousel" data-
 ride="carousel1">
  <!-- Indicators -->
 <ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
 </ol>

 <!-- Wrapper for slides -->
 <div class="carousel-inner">
<div class="item active">
  <img src="images/dragon_hunter_pic.png" alt="dragon_hunter_pic"
   id="mainImage1" >
</div>

 </div>

    </div>
         </div>
         </div>
            <div class="col-lg-4 col-xl-4 col-md-5 col-xs-5 col-sm-5 ">

       <div class="women-margin">
  <img src="images/women_3.png" alt="live" id="women-eyes1" >
            </div>
            </div>

  <div class="col-lg-4 col-xl-4 col-md-7 col-xs-7 col-sm-7 ">

      <div class="yellow-box">

      <h2 id="change_h2">THE DRAGON HUNTER</h2>
            <br/>
            <p id="change_p"> Lorem ipsum dolor sit amet, consectetur
       adipiscing elit, sed do eiusmod tempor incididunt ut labore et
        dolor aliqua. </p>

         </div>

      </div>

  </div>
 </div>

  </section>
</code>```

this is the problematic box, box number 3:

```<code>    <div class="yellow-box">
</code>```

css:

```<code>  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }
</code>```

this is box number 2:

```<code>  .women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }
</code>```

答:
```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example of Bootstrap 3 Nested Rows and Columns</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
    /* Some custom styles to beautify this example */
    .main-content{
        min-height: 330px;
        background: #dbdfe5;
    }
    .sidebar-content{
        min-height: 150px;
        margin-bottom: 30px;
        background: #b4bac0;
    }
    .left{
        background: red;
    }
    .box2{
        background: green;
        height: 100%;
    }
    .box3{
        height: 100%;
        background: blue;
    }
    .right{
        background:green;
        margin:0;
        padding:0;
    }
</style>
</head>
<body>
    <section id="carousel-section">
        <div class="container-fluid">
            <div class="row feature">
            <div class="col-lg-8 col-xl-8 col-md-12 col-xs-12 col-sm-12 left">
                <div class="carousel-margin">
                    <div id="myCarousel" class="carousel1 slide container-carousel" data-
                 ride="carousel1">
                      <!-- Indicators -->
                        <ol class="carousel-indicators">
                            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                            <li data-target="#myCarousel" data-slide-to="1"></li>
                            <li data-target="#myCarousel" data-slide-to="2"></li>
                        </ol>

                         <!-- Wrapper for slides -->
                        <div class="carousel-inner">
                            <div class="item active">
                              <img src="images/dragon_hunter_pic.png" alt="dragon_hunter_pic"
                               id="mainImage1" >
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="right col-lg-4 col-xl-4 col-md-12 col-xs-12 col-sm-12">
                <div class="col-lg-12 col-md-6 box2">
                   <div class="women-margin">
                      <img src="images/women_3.png" alt="live" id="women-eyes1" >
                    </div>
                </div>
                <div class="col-lg-12 col-md-6 box3">
                    <div class="yellow-box">
                        <h2 id="change_h2">THE DRAGON HUNTER</h2>
                            <br/>
                            <p id="change_p"> Lorem ipsum dolor sit amet, consectetur
                       adipiscing elit, sed do eiusmod tempor incididunt ut labore et
                        dolor aliqua. </p>

                    </div>
                </div>
            </div>
        </div>
    </div>
  </section>
</body>
</html>
</code>```

Body:
I'm facing an issue in matching the size of a  box to mobile(using bootstrap)
I have got 3 boxes, number 1 and 2 are images and number 3 has text,
and it looks like this

when I resize the screen to mobile size this is what happens(box number 3 is higher or in some devices shorter than box number 2, like here:error

I need it to look like that (box number 3 in the same height as 2):desired output

I tried to set max height and min hight to box3 but this is not the solution because it doesn't match to all the devices.

html:

THE DRAGON HUNTER

 Lorem ipsum dolor sit amet, consectetur
       adipiscing elit, sed do eiusmod tempor incididunt ut labore et
        dolor aliqua.

this is the problematic box, box number 3:

css:

  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }

this is box number 2:

  .women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }


问:
Play youtube video on hover
I just need to play the youtube video only when hovered

I have here a fiddle and can't get it to work.

```<code>$(document).ready(function(){
  $(function() {

      var playersrc = jQuery(iframe).attr('src');

          $('div').hover(function(){
          $('iframe').attr('src',playersrc+'&autoplay=1');
      }, function(){
          $('iframe').attr('src',playersrc);
      });
  });
});
</code>```

https://jsfiddle.net/rhr5p0pg/2/

updated fiddle: https://jsfiddle.net/rhr5p0pg/4/

now it plays all and when your mouse leaves the it does not go back to its originial video

答:
You need to add the video using Iframe Youtube Api, follow the examples here.

Initialize your player and the use this Jquery code:

```<code>//Hover play
$('iframe').on('mouseover',function(){
    player.playVideo();
});

//Blur Pause

$('iframe').on('mouseout',function(){
    player.playVideo();
});
</code>```

Title: Play youtube video on hover

Body:
I just need to play the youtube video only when hovered

I have here a fiddle and can't get it to work.

$(document).ready(function(){
  $(function() {

      var playersrc = jQuery(iframe).attr('src');

          $('div').hover(function(){
          $('iframe').attr('src',playersrc+'&autoplay=1');
      }, function(){
          $('iframe').attr('src',playersrc);
      });
  });
});

https://jsfiddle.net/rhr5p0pg/2/

updated fiddle: https://jsfiddle.net/rhr5p0pg/4/

now it plays all and when your mouse leaves the it does not go back to its originial video

Body:
You need to add the video using Iframe Youtube Api, follow the examples here.

Initialize your player and the use this Jquery code:

//Hover play
$('iframe').on('mouseover',function(){
    player.playVideo();
});

//Blur Pause

$('iframe').on('mouseout',function(){
    player.playVideo();
});


问:
IObservable doesnt Contain the defintion, but actualy there is the definition in there
I Try to load cached data via Akavache, but i dont know why i cant get it right. i try to get FullName and Email that i already cached after login , so i getobject in my "CachedUser" model but dont know why its says there is no definition for FullName and Email in there.
Here is my CachedUser Model

```<code>namespace KGVC.Models
{
    public class CachedUsers
    {
        public string FullName { get; set; }
        public string Email { get; set; }
    }
}
</code>```

and here is the code to getobject in Akavache that i try to implement

```<code>   public void GetDataCache(object sender, EventArgs e)
        {
            var loaded =  BlobCache.LocalMachine.GetObject<CachedUsers>("usercached");

            txtemail.Text = loaded.FullName;
            txtfullname.Text = loaded.FullName.ToString();
        }
</code>```

and here is the cache user code

```<code> public  void CacheUser(AuthenticationResult ar)
        {
            JObject user = ParseIdToken(ar.IdToken);
            var cache = new CachedUsers
            {
                FullName = user["name"]?.ToString(),
                Email = user["emails"]?.ToString()

            };
             BlobCache.LocalMachine.InsertObject("usercached", cache);

        }
</code>```

and here is the full error message that i get

```<code>'IObservable<CachedUsers>' does not contain a definition for 'FullName' and no extension method 'FullName' accepting a first argument of type 'IObservable<CachedUsers>' could be found (are you missing a using directive or an assembly reference?)
</code>```

what is the problem in here , because i think there is nothing wrong in my code. can you figure this out ?

答:
You either need to await it

```<code> public async void GetDataCache(object sender, EventArgs e)
 {
    var loaded = await BlobCache.LocalMachine.GetObject<CachedUsers>("usercached");

    txtemail.Text = loaded.FullName;
    txtfullname.Text = loaded.FullName.ToString();
 }
</code>```

or subscribe to the IObservable:

```<code> public async void GetDataCache(object sender, EventArgs e)
 {
    var loaded = await BlobCache.LocalMachine.GetObject<CachedUsers>("usercached").Subscribe(user => {
        // TODO might need to wrap this in a Device.BeginInvokeOnMainThread
        txtemail.Text = user.FullName;
        txtfullname.Text = user.FullName.ToString();
    });
 }
</code>```

Look into the concepts of async/await and the IObservable object to get a better understanding of the concepts and what the problem is in this specific case.

Body:
I Try to load cached data via Akavache, but i dont know why i cant get it right. i try to get FullName and Email that i already cached after login , so i getobject in my "CachedUser" model but dont know why its says there is no definition for FullName and Email in there.
Here is my CachedUser Model

namespace KGVC.Models
{
    public class CachedUsers
    {
        public string FullName { get; set; }
        public string Email { get; set; }
    }
}

and here is the code to getobject in Akavache that i try to implement

   public void GetDataCache(object sender, EventArgs e)
        {
            var loaded =  BlobCache.LocalMachine.GetObject<CachedUsers>("usercached");

            txtemail.Text = loaded.FullName;
            txtfullname.Text = loaded.FullName.ToString();
        }

and here is the cache user code

 public  void CacheUser(AuthenticationResult ar)
        {
            JObject user = ParseIdToken(ar.IdToken);
            var cache = new CachedUsers
            {
                FullName = user["name"]?.ToString(),
                Email = user["emails"]?.ToString()

            };
             BlobCache.LocalMachine.InsertObject("usercached", cache);

        }

and here is the full error message that i get

'IObservable<CachedUsers>' does not contain a definition for 'FullName' and no extension method 'FullName' accepting a first argument of type 'IObservable<CachedUsers>' could be found (are you missing a using directive or an assembly reference?)

what is the problem in here , because i think there is nothing wrong in my code. can you figure this out ?

Body:
You either need to await it

 public async void GetDataCache(object sender, EventArgs e)
 {
    var loaded = await BlobCache.LocalMachine.GetObject<CachedUsers>("usercached");

    txtemail.Text = loaded.FullName;
    txtfullname.Text = loaded.FullName.ToString();
 }

or subscribe to the IObservable:

 public async void GetDataCache(object sender, EventArgs e)
 {
    var loaded = await BlobCache.LocalMachine.GetObject<CachedUsers>("usercached").Subscribe(user => {
        // TODO might need to wrap this in a Device.BeginInvokeOnMainThread
        txtemail.Text = user.FullName;
        txtfullname.Text = user.FullName.ToString();
    });
 }

Look into the concepts of async/await and the IObservable object to get a better understanding of the concepts and what the problem is in this specific case.


问:
Separate a string with different delimiters in python
I came across a csv file which made me wonder what should be the correct processes to get the info out of it. I want to read each line and then each row in variables lastname, firstname and department but,

structure of the csv file is like this

```<code>lastname, firstname (department)
</code>```

lets say we have a name Jean-Claude Van Damme

```<code>Van Damme, Jean-Claude (Karate-Master)
</code>```

what would be the best way to separate such string and store in variables lastname, firstname and the department?

```<code>import csv
import string
import re

file = open('path/testing_delimiters.csv', 'rb')
reader = csv.reader(file)
for row in reader:
    data = map(string.strip, row)
print data
# output so far
# ['Van Damme', 'Jean-Claude (Karate-Master)']
</code>```

task is to separate Jean-Claude and (Karate-Master)

```<code># expected output
# ['Van Damme', 'Jean-Claude', 'Karate-Master']
</code>```

答: if it's from a csv file, then I think you can import csv module. Then you can iterate it row by row and each row you need to split it by comma. On last name you can search word between the bracket using regex <code>\((.*?)\)</code>. at last you need to remove the bracket. </p>

Body:
I came across a csv file which made me wonder what should be the correct processes to get the info out of it. I want to read each line and then each row in variables lastname, firstname and department but,

structure of the csv file is like this

lastname, firstname (department)

lets say we have a name Jean-Claude Van Damme

Van Damme, Jean-Claude (Karate-Master)

what would be the best way to separate such string and store in variables lastname, firstname and the department?

import csv
import string
import re

file = open('path/testing_delimiters.csv', 'rb')
reader = csv.reader(file)
for row in reader:
    data = map(string.strip, row)
print data
# output so far
# ['Van Damme', 'Jean-Claude (Karate-Master)']

task is to separate Jean-Claude and (Karate-Master)

# expected output
# ['Van Damme', 'Jean-Claude', 'Karate-Master']

Body: if it's from a csv file, then I think you can import csv module. Then you can iterate it row by row and each row you need to split it by comma. On last name you can search word between the bracket using regex \((.*?)\). at last you need to remove the bracket.


问:
How do I pass id of post request from mid to the top layer to return it in header location 201?
So, basically. I have 3 layers in my app: low, mid and the top. Top is for controllers and mid for some logic. The problem.is that whenever I add something to database and got the id on the mid layer, ive got no idea how to let the top controller layer know about it, so that I could put it into header location as a response with status code 201. If more info is needed, let me know. Using EF if it helps. And I do not wanna to pass httpcontext down.</p>

答:
As I heard you want to add some data with mid layer and top layer should know about this.

I would do this that :
Top layer should handle dbcontext for data transfering.
Mid Layer should handle data (models) for Top Layer.

if you have some code share  and answer will be concrete


问:
Share folder content between two containers in same pod
I have a Pod with two containers, Nginx and Rails. I want to share the public folder from the rails to the nginx container, but the public contains already files, I don't want the folder be empty.

Is there a way with a shared-volume?

I tried:

```<code>- name: rails-assets
    hostPath:
      path: /app/public
</code>```

But im getting this error:

```<code>Error: failed to start container "nginx": Error response from daemon: {"message":"error while creating mount source path '/app/public': mkdir /app: read-only file system"}
Error syncing pod
Back-off restarting failed container
</code>```

Thanks,

答:
I fixed that problem creating a shared-volument shared-assets/ on the rails app. On the rails dockerfile I created a ENTRYPOINT with a bash script to copy the public/ files on the shared-assets/ folder. With this I can see the files now on the Nginx Container.

```<code>---
kind: Deployment
apiVersion: apps/v1beta1
metadata:
  name: staging-deployment
spec:
  replicas: 1
  revisionHistoryLimit: 2
  template:
    metadata:
      labels:
        app: staging
    spec:
      containers:
      - name: staging
        image: some/container:v5
        volumeMounts:
        - mountPath: /var/run/
          name: rails-socket
        - mountPath: /app/shared-assets
          name: rails-assets
      - name: nginx
        image: some/nginx:latest
        volumeMounts:
        - mountPath: /var/run/
          name: rails-socket
        - mountPath: /app
          name: rails-assets
      imagePullSecrets:
      - name: app-backend-secret
      volumes:
      - name: rails-socket
        emptyDir: {}
      - name: rails-assets
        emptyDir: {}
</code>```

And the script ENTRYPOINT:

```<code>cp -r /app/public/ /app/shared-assets/
</code>```

Body:
I have a Pod with two containers, Nginx and Rails. I want to share the public folder from the rails to the nginx container, but the public contains already files, I don't want the folder be empty.

Is there a way with a shared-volume?

I tried:

- name: rails-assets
    hostPath:
      path: /app/public

But im getting this error:

Error: failed to start container "nginx": Error response from daemon: {"message":"error while creating mount source path '/app/public': mkdir /app: read-only file system"}
Error syncing pod
Back-off restarting failed container

Thanks,

Body:
I fixed that problem creating a shared-volument shared-assets/ on the rails app. On the rails dockerfile I created a ENTRYPOINT with a bash script to copy the public/ files on the shared-assets/ folder. With this I can see the files now on the Nginx Container.

---
kind: Deployment
apiVersion: apps/v1beta1
metadata:
  name: staging-deployment
spec:
  replicas: 1
  revisionHistoryLimit: 2
  template:
    metadata:
      labels:
        app: staging
    spec:
      containers:
      - name: staging
        image: some/container:v5
        volumeMounts:
        - mountPath: /var/run/
          name: rails-socket
        - mountPath: /app/shared-assets
          name: rails-assets
      - name: nginx
        image: some/nginx:latest
        volumeMounts:
        - mountPath: /var/run/
          name: rails-socket
        - mountPath: /app
          name: rails-assets
      imagePullSecrets:
      - name: app-backend-secret
      volumes:
      - name: rails-socket
        emptyDir: {}
      - name: rails-assets
        emptyDir: {}

And the script ENTRYPOINT:

cp -r /app/public/ /app/shared-assets/


问:
CoordinatorLayout and toolbar and TabLayout sometimes cannot work move right and left scroll
I make the collapse toolbar activity use the CoordinatorLayout.

1. main_activity

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:background="@android:color/white"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="75dp"
            android:background="?attr/colorPrimary"
            android:paddingLeft="@dimen/layout_margin"
            android:theme="@style/ThemeToolbar"
            app:layout_scrollFlags="scroll|enterAlways"
            app:layout_collapseMode="pin"/>
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="@color/text_space"
            app:tabSelectedTextColor="@android:color/white"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="2dp"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </android.support.v4.widget.SwipeRefreshLayout>
    <android.support.design.widget.FloatingActionButton
        android:visibility="gone"
        android:id="@+id/fabButton_menu"
        android:src="@drawable/plus"
        app:fabSize="normal"
        app:backgroundTint="@color/color_family"
        app:borderWidth="0dp"
        style="@style/FabStyle_Normal"/>
</android.support.design.widget.CoordinatorLayout>
</code>```

2. code

```<code>pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new TabFragment_Home(), "T1");
pagerAdapter.addFragment(new TabFragment_Pharm(),"T2");
pagerAdapter.addFragment(new TabFragment_Family(), "T3");
pagerAdapter.addFragment(new TabFragment_Board(), "T4");

viewPager.setOffscreenPageLimit(4);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager, false);
</code>```

This code is very simple and basic code.
I have one question the scroll action please see the image below.

Question: why cannot scroll move right? this is bug or my mistake? please let me know. thanks

答:
please add below lines in your tablayout :</p>

```<code><android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@android:color/transparent"
            app:tabGravity="fill"
            app:tabMode="scrollable"
            app:tabTextAppearance="@style/TextAppearance.Design.Tab"
            app:tabSelectedTextColor="@color/myPrimaryColor"
            app:tabIndicatorColor="@color/myPrimaryColor"
            android:overScrollMode="never"
            />
</code>```

Body:
I make the collapse toolbar activity use the CoordinatorLayout.

1. main_activity

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:background="@android:color/white"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="75dp"
            android:background="?attr/colorPrimary"
            android:paddingLeft="@dimen/layout_margin"
            android:theme="@style/ThemeToolbar"
            app:layout_scrollFlags="scroll|enterAlways"
            app:layout_collapseMode="pin"/>
        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="@color/text_space"
            app:tabSelectedTextColor="@android:color/white"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="2dp"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </android.support.v4.widget.SwipeRefreshLayout>
    <android.support.design.widget.FloatingActionButton
        android:visibility="gone"
        android:id="@+id/fabButton_menu"
        android:src="@drawable/plus"
        app:fabSize="normal"
        app:backgroundTint="@color/color_family"
        app:borderWidth="0dp"
        style="@style/FabStyle_Normal"/>
</android.support.design.widget.CoordinatorLayout>

2. code

pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new TabFragment_Home(), "T1");
pagerAdapter.addFragment(new TabFragment_Pharm(),"T2");
pagerAdapter.addFragment(new TabFragment_Family(), "T3");
pagerAdapter.addFragment(new TabFragment_Board(), "T4");

viewPager.setOffscreenPageLimit(4);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager, false);

This code is very simple and basic code.
I have one question the scroll action please see the image below.

Question: why cannot scroll move right? this is bug or my mistake? please let me know. thanks

Body:
please add below lines in your tablayout :

<android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@android:color/transparent"
            app:tabGravity="fill"
            app:tabMode="scrollable"
            app:tabTextAppearance="@style/TextAppearance.Design.Tab"
            app:tabSelectedTextColor="@color/myPrimaryColor"
            app:tabIndicatorColor="@color/myPrimaryColor"
            android:overScrollMode="never"
            />


问:
Node.js 7 how to use sequelize transaction with async / await?
Node.js 7 and up already support async/await syntax. How should I use async/await with sequelize transactions?</p>

答:
The above code has an error in destroy call.

```<code> await Model.destroy({where: {id}, transaction});
</code>```

Transaction is part of the options object.

ContentLicense: CC BY-SA 4.0

Body:
The above code has an error in destroy call.

 await Model.destroy({where: {id}, transaction});

Transaction is part of the options object.


问:
How to get all system/bios information for Windows
I want to know how to get full information about PC and BIOS. I came across this post - https://groups.google.com/forum/#!msg/golang-nuts/pKuFQxAy4P4/62FnqGON1pEJ

Code:

```<code>package main

import (
    "fmt"
    "github.com/ochapman/godmi"
)
func main(){
    BS:=godmi.GetBIOSInformation()
    fmt.Println("BS:",BS)
    sys:=godmi.GetSystemInformation()
    fmt.Println("sys:",sys)
    BB:=godmi.GetBaseboardInformation()
    fmt.Println("BB:",BB)
}
</code>```

I could not compile because there is an error:

```<code># github.com/ochapman/godmi
go\src\github.com\ochapman\godmi\godmi.go:674:13: undefined: syscall.Mmap
go\src\github.com\ochapman\godmi\godmi.go:674:79: undefined: syscall.PROT_RE
go\src\github.com\ochapman\godmi\godmi.go:674:98: undefined: syscall.MAP_SHA
go\src\github.com\ochapman\godmi\godmi.go:680:8: undefined: syscall.Munmap
</code>```

As I understood it only for Linux, for Windows I did not find anything like it at all. Can eat an alternative?

答:
A detour about the methodology in programming

(Sorry for a detour, which follows, but I think I had to make it.)

You're attacking your problem from a wrong angle.
Programming is not about finding a random package, trying it,
seeing it failing and turning for help;
it's rather about inventing a general approach to solving the problem
at hand and then trying to figure out what are there to solve it.

For instance, in your case, it might easily be not fruitful
to search for "BIOS+information+golang" because it's too narrow.

Instead, try to figure out

How to get any information about a system on Windows.

How to do that in Go.

While this is boring, I have to recommend reading
this seriously: this will really help
you getting your future programming challenges solved.

The problem at hand

OK, now back to your problem.

On Windows, the standard way to obtain information about a system
is querying the so-called Windows Management Instrumentation
(or WMI for short)  subsystem.

Once you know this, you should dig into these two directions:

What WMI calls do you need to perform to get the information
which is of interest to you.

This one is easily searcheable.
The first hit I got doing that is this
which I'd say is a pretty good start.

How to do WMI calls from Go.

This one can be done in two ways:

Direct implementation by hand.
Go has very good built-in support for dynamically loading Windows DLLs
and calling functions from them.

This is a good demonstation of the basic concepts.

Using a ready-made package.
Again, quick searching yields github.com/StackExchange/wmi.

So, if I were you, I'd first code up whatever the WMI calls suit my needs
using VBS or JScript (or whatnot) on WSH
and then "ported" that solution to Go using any of the described approaches.

Body:
I want to know how to get full information about PC and BIOS. I came across this post - https://groups.google.com/forum/#!msg/golang-nuts/pKuFQxAy4P4/62FnqGON1pEJ

Code:

package main

import (
    "fmt"
    "github.com/ochapman/godmi"
)
func main(){
    BS:=godmi.GetBIOSInformation()
    fmt.Println("BS:",BS)
    sys:=godmi.GetSystemInformation()
    fmt.Println("sys:",sys)
    BB:=godmi.GetBaseboardInformation()
    fmt.Println("BB:",BB)
}

I could not compile because there is an error:

# github.com/ochapman/godmi
go\src\github.com\ochapman\godmi\godmi.go:674:13: undefined: syscall.Mmap
go\src\github.com\ochapman\godmi\godmi.go:674:79: undefined: syscall.PROT_RE
go\src\github.com\ochapman\godmi\godmi.go:674:98: undefined: syscall.MAP_SHA
go\src\github.com\ochapman\godmi\godmi.go:680:8: undefined: syscall.Munmap

As I understood it only for Linux, for Windows I did not find anything like it at all. Can eat an alternative?


问:
Export array data from MATLAB to C#
is it possible to export an array from MATLAB to C# directly, without the need to copying and pasting the value in C#?

Thanks

答:
MATLAB has a COM automation interface that will let you control an instance of MATLAB programmatically from a .NET program and has functions named PutFullMatrix and GetFullMatrix that facilitate transferring a matrix from C# to MATLAB or vice versa.  See the External Interfaces section of the MATLAB manual for details.

http://www.mathworks.com/help/techdoc/matlab_external/f135590.html#f135616

Title: Export array data from MATLAB to C#


问:
Java - ArrayList<> and LinkedList<> - class as an identifier
https://imgur.com/nb6sjuK

I don't get it what the identifier  does in this example, I'm new with programming and what I realize is that ArrayList<String> creates the list of Strings and same with LinkedList<String> but what happens when you push a class in the identifier, like - LinkedList<Song> - and Song is a class . Thanks in advance.

```<code>public class Main {
    private static ArrayList<Album> albums = new ArrayList<Album>();

    LinkedList<Song> playlist = new LinkedList<Song>();

    public static void main(String[] args) {

    // write your code here

        Album album = new Album("StormBringer" , "Deep Purple");
        album.addSong("Stormbringer" , 4.6);
        album.addSong("Love don't mean a thing" , 4.22);
</code>```

答: String is a class like Song is also a class. It means that you can only insert objects of this class into your List. Objects of other classes are not allowed to be added, because the type does not match. Trying to do so will result in a compile error. So your list is type save. This feature is called generics.

Body:
https://imgur.com/nb6sjuK

I don't get it what the identifier  does in this example, I'm new with programming and what I realize is that ArrayList<String> creates the list of Strings and same with LinkedList<String> but what happens when you push a class in the identifier, like - LinkedList<Song> - and Song is a class . Thanks in advance.

public class Main {
    private static ArrayList<Album> albums = new ArrayList<Album>();

    LinkedList<Song> playlist = new LinkedList<Song>();

    public static void main(String[] args) {

    // write your code here

        Album album = new Album("StormBringer" , "Deep Purple");
        album.addSong("Stormbringer" , 4.6);
        album.addSong("Love don't mean a thing" , 4.22);


问:
Regex to allow max 10 digits followed by only one comma and 3 more digits
I am working on a regex for allowing only max 10 digits before comma and max 3 digits after comma.

So far i have come up with this:

```<code>^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$.
</code>```

I am going to validate input in javascript.

I am using sap.m.input control, and user's keystroke is captured on live change event.

Following examples are accepted as user input:

1234567890,123

  4,1

   234,45

  56457

Input must always begin with a natural number and only comma should be appear.

Using the above mentioned regex, i am able to avoid first digit as zero but it is not considering this input value - 1,23.

I have added the following code in the application:

```<code>var input = oEvent.getSource().getValue();
        var isValid = false;
        var regex = /^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$/;
        isValid = regex.test(input);
        if (isValid == false) {
            //  oEvent.getSource().setValueState("Error");
            input = input.replace(/[^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})]/g,"");
            oEvent.getSource().setValue(input);
            return;
        }
</code>```

I also want to avoid blank entry and space in the input field. I want replace unwanted characters with space on live change event. As of now, i am unable to replace other characters using the above mentioned code.

Please suggest ways to form perfect regex to handle this scenario.

Thanks.

答:
You can even go further if you want to accept negative numbers:

```<code>^-?[1-9]\d{0,9}(,\d{0,3})?$
</code>```

by accepting the - in the beginning of your string.

Last but not least, I would recommend using trim before checking the validity of your input! users tend to add unnecessary spaces at the end or even at the beginning of what they input.

Good luck

Body:
I am working on a regex for allowing only max 10 digits before comma and max 3 digits after comma.

So far i have come up with this:

^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$.

I am going to validate input in javascript.

I am using sap.m.input control, and user's keystroke is captured on live change event.

Following examples are accepted as user input:

1234567890,123

  4,1

   234,45

  56457

Input must always begin with a natural number and only comma should be appear.

Using the above mentioned regex, i am able to avoid first digit as zero but it is not considering this input value - 1,23.

I have added the following code in the application:

var input = oEvent.getSource().getValue();
        var isValid = false;
        var regex = /^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})?$/;
        isValid = regex.test(input);
        if (isValid == false) {
            //  oEvent.getSource().setValueState("Error");
            input = input.replace(/[^[1-9]{1}[0-9]{1,9}(,[0-9]{0,3})]/g,"");
            oEvent.getSource().setValue(input);
            return;
        }

I also want to avoid blank entry and space in the input field. I want replace unwanted characters with space on live change event. As of now, i am unable to replace other characters using the above mentioned code.

Please suggest ways to form perfect regex to handle this scenario.

Thanks.

Body:
You can even go further if you want to accept negative numbers:

^-?[1-9]\d{0,9}(,\d{0,3})?$

by accepting the - in the beginning of your string.

Last but not least, I would recommend using trim before checking the validity of your input! users tend to add unnecessary spaces at the end or even at the beginning of what they input.

Good luck


问:
Lambda causes compile error "incompatible types" in Java 9, compiles in Java 8
The following code compiles with Java 8 but not with Java 9:

```<code>public class CompileErrJdk9 {

    @FunctionalInterface public interface Closure<R> {
        R apply();
    }

    @FunctionalInterface public interface VoidClosure {
        void apply();
    }

    static <R> R call(Closure<R> closure) {
        return closure.apply();
    }

    static void call(VoidClosure closure) {
        call(() -> { closure.apply(); return null; });
    }

    static <T> void myMethod(T data) {
        System.out.println(data);
    }

    public static void main(String[] args) {
        call(() -> myMethod("hello")); //compile error in jdk9
    }
}
</code>```

This is the error:

```<code>CompileErrJdk9.java:24: error: incompatible types: inference variable R has incompatible bounds
        call(() -> myMethod("hello")); //compile error in jdk9
            ^
    upper bounds: Object
    lower bounds: void
  where R is a type-variable:
    R extends Object declared in method <R>call(Closure<R>)
1 error
</code>```

I've narrowed it down to the type parameter <T> of myMethod; if I drop it and use Object for the parameter type the code compiles. Declaring myMethod as static <T> void myMethod() { } fails as well (in 9 only) even though I'm not using the type parameter.

I've checked the Java 9 release notes and searched for an explanation for this behaviour but did not find anything. Am I correct to assume this is a bug in JDK9, or am I missing something?

答:
Oracle has accepted this as a bug with ID JDK-8191290:

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8191290

Update: the bug was closed with the comment "Fixed in 10, won't backport".

Body:
The following code compiles with Java 8 but not with Java 9:

public class CompileErrJdk9 {

    @FunctionalInterface public interface Closure<R> {
        R apply();
    }

    @FunctionalInterface public interface VoidClosure {
        void apply();
    }

    static <R> R call(Closure<R> closure) {
        return closure.apply();
    }

    static void call(VoidClosure closure) {
        call(() -> { closure.apply(); return null; });
    }

    static <T> void myMethod(T data) {
        System.out.println(data);
    }

    public static void main(String[] args) {
        call(() -> myMethod("hello")); //compile error in jdk9
    }
}

This is the error:

CompileErrJdk9.java:24: error: incompatible types: inference variable R has incompatible bounds
        call(() -> myMethod("hello")); //compile error in jdk9
            ^
    upper bounds: Object
    lower bounds: void
  where R is a type-variable:
    R extends Object declared in method <R>call(Closure<R>)
1 error

I've narrowed it down to the type parameter <T> of myMethod; if I drop it and use Object for the parameter type the code compiles. Declaring myMethod as static <T> void myMethod() { } fails as well (in 9 only) even though I'm not using the type parameter.

I've checked the Java 9 release notes and searched for an explanation for this behaviour but did not find anything. Am I correct to assume this is a bug in JDK9, or am I missing something?


问:
Using variables (from user input) for lat/long with Google Maps API
Messing around with the Google Maps API in a browser, however I'm having a bit of trouble putting in a user input for the variables. Essentially, I want to be able to put in a new lat/long from pressing a button on the page and have the map move onto that.

It doesn't work for the actual input variables, but when I use the commented out section it works perfectly fine.

```<code>    <body>
    <form id = "input" method = "get">
        <input type = "text" placeholder = "Latitude" name = "user_lat">
        <input type = "text" placeholder = "Longitude" name = "user_lng"><br>
        <button type = "submit">Mark on Map</button>
    </form>
    <div id = "map"></div>
        <script>
            var lat_in = parseFloat($('#user_lat').val());
            var lng_in = parseFloat($('#user_lng').val());
            /*var lat_in = 37.697948;
            var lng_in = -97.314835;*/
            function initMap() {
                var location = {lat: lat_in, lng: lng_in};
                /*var location = {lat: 37.697948, lng: -97.314835};*/
                var map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 13,
                    center: location
                    });
                var marker = new google.maps.Marker({
                    position: location,
                    map: map
                    });
            }
    </script>
    <script async defer
    src="link with the API key here">
    </script>
</code>```

I suspect it might have something to do how I actual use the submit button and the way I interact with it, but I'm not 100% sure. I've looked up different things, but I'm still a bit new at this. I just started to dabble in javascript, so I'm sure there are better methods to do this, but I just want to get this working to get an understanding of it.

答:
You can do it like this, Add change listener and on change pan to that location by clicking enter

```<code>    <!DOCTYPE html>
 <html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions service</title>
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #floating-panel {
    position: absolute;
    top: 10px;
    left: 25%;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
    text-align: center;
    font-family: 'Roboto','sans-serif';
    line-height: 30px;
    padding-left: 10px;
  }
</style>
</head>
<body>
<div id="floating-panel">
<b>Start: </b>
<input id="start" type="text"
        placeholder="Enter lat">
<b>End: </b>
 <input id="end" type="text"
        placeholder="Enter lng">
</div>
<div id="map"></div>
<script>
  function initMap() {

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: {lat: 0,  lng:  0}
    });

marker = new google.maps.Marker({
                map:map,
                draggable:true,
                animation: google.maps.Animation.DROP,
                position: {lat: 0,  lng:  0}
            });
    var onChangeHandler = function() {
      DisplayPoint(map);
    };
    //document.getElementById('start').addEventListener('change', onChangeHandler);
    document.getElementById('end').addEventListener('change', onChangeHandler);

  function DisplayPoint(map) {

      var lat = document.getElementById('start').value;
      var lng = document.getElementById('end').value;
      var latLng = new google.maps.LatLng(lat, lng);
      marker.setPosition(latLng);
      map.panTo(latLng);

  }
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&callback=initMap">
</script>
</code>```

Body:
Messing around with the Google Maps API in a browser, however I'm having a bit of trouble putting in a user input for the variables. Essentially, I want to be able to put in a new lat/long from pressing a button on the page and have the map move onto that.

It doesn't work for the actual input variables, but when I use the commented out section it works perfectly fine.

    <form id = "input" method = "get">
        <input type = "text" placeholder = "Latitude" name = "user_lat">
        <input type = "text" placeholder = "Longitude" name = "user_lng">

        <button type = "submit">Mark on Map</button>
    </form>

I suspect it might have something to do how I actual use the submit button and the way I interact with it, but I'm not 100% sure. I've looked up different things, but I'm still a bit new at this. I just started to dabble in javascript, so I'm sure there are better methods to do this, but I just want to get this working to get an understanding of it.

Body:
You can do it like this, Add change listener and on change pan to that location by clicking enter

    <!DOCTYPE html>
 <html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions service</title>
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #floating-panel {
    position: absolute;
    top: 10px;
    left: 25%;
    z-index: 5;
    background-color: #fff;
    padding: 5px;
    border: 1px solid #999;
    text-align: center;
    font-family: 'Roboto','sans-serif';
    line-height: 30px;
    padding-left: 10px;
  }
</style>
</head>
<body>
<div id="floating-panel">
<b>Start: </b>
<input id="start" type="text"
        placeholder="Enter lat">
<b>End: </b>
 <input id="end" type="text"
        placeholder="Enter lng">
</div>
<div id="map"></div>
<script>
  function initMap() {

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: {lat: 0,  lng:  0}
    });

marker = new google.maps.Marker({
                map:map,
                draggable:true,
                animation: google.maps.Animation.DROP,
                position: {lat: 0,  lng:  0}
            });
    var onChangeHandler = function() {
      DisplayPoint(map);
    };
    //document.getElementById('start').addEventListener('change', onChangeHandler);
    document.getElementById('end').addEventListener('change', onChangeHandler);

  function DisplayPoint(map) {

      var lat = document.getElementById('start').value;
      var lng = document.getElementById('end').value;
      var latLng = new google.maps.LatLng(lat, lng);
      marker.setPosition(latLng);
      map.panTo(latLng);

  }
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&callback=initMap">
</script>


问:
Create a new branch containing the two first commits(the second commit version) in master branch
I have some commits on my master branch. I want to create another branch which includes just two first commits in masters branch.how can I do this ?</p>

答:
Assume you have a repository like in the image below

If you want create the newbranch at the a5d0f81 commit as shown in the image.

```<code>git checkout -b newbranch a5d0f81
</code>```

should work as show in the picture.

Body:
Assume you have a repository like in the image below

If you want create the newbranch at the a5d0f81 commit as shown in the image.

git checkout -b newbranch a5d0f81

should work as show in the picture.


问:
Identifying http request with KERBEROS from Java runing on Linux
I have some environment with both Linux and Windows servers. Authentication is handled by Kerberos. I want to make some JAVA code which automatically authenticates the http requests it makes as being done by the logged in user executing the program.

For example, if I have this code:

```<code>CloseableHttpClient winHttpclient = WinHttpClients.createDefault();

HttpGet httpget = new HttpGet("http://mykerberos/endpoint");

winHttpclient.execute(httpget).getEntity();
</code>```

when I execute it from windows, it works out of the box. I am identified by http://mykerberos/endpoint and get the response.

Now, I want to do the same from a Linux server.
I found a couple of proposal, like https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/lab/part6.html#Proxy_Authentication but it is not what I look for as it requires my credentials: from Windows, I do not even have to pass them.

Does someone know how I can achieve this ?

Thanks in advance for your help!

答: Following https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/lab/part6.html is working fine when using a proper version of Java (it works for java 8 but not java 6).</p>

Body:
I have some environment with both Linux and Windows servers. Authentication is handled by Kerberos. I want to make some JAVA code which automatically authenticates the http requests it makes as being done by the logged in user executing the program.

For example, if I have this code:

CloseableHttpClient winHttpclient = WinHttpClients.createDefault();

HttpGet httpget = new HttpGet("http://mykerberos/endpoint");

winHttpclient.execute(httpget).getEntity();

when I execute it from windows, it works out of the box. I am identified by http://mykerberos/endpoint and get the response.

Now, I want to do the same from a Linux server.
I found a couple of proposal, like https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/lab/part6.html#Proxy_Authentication but it is not what I look for as it requires my credentials: from Windows, I do not even have to pass them.

Does someone know how I can achieve this ?

Thanks in advance for your help!


问:
How to install Boost.Python using pip on Windows 10?
I want to install boost.python for the installation of dlib library.</p>

答:
I don't believe pip is able to do that (at least not yet).

If you want to avoid learning the boost build system and tools (b2, previously bjam), pre-compiled boost libraries can be installed via an executable:
https://sourceforge.net/projects/boost/files/boost-binaries/

This installs all Boost libraries, including Boost Python, and will use the default Python installation to build Boost Python unless you modify PATH first.

The link seem to only provide Windows executables. For other operating systems, similar solutions probably exists. Here is one for ubuntu: How to Install boost on Ubuntu?


问:
UIScrollView Will not allow scrolling or interaction after rotated
In my

```<code>-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
</code>```

method, I have code to reposition and resize a scrollview as the app rotates with the device. I do it with the following code:

```<code>-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:0.5f];

    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
         //landscape
    [mT.buttonScroll setFrame:CGRectMake(0, 544, 1024, 160)];

    }else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        //landscape
    [mT.buttonScroll setFrame:CGRectMake(0, 544, 1024, 160)];

    }else if (toInterfaceOrientation == UIInterfaceOrientationPortrait){
       //portrait
    [mT.buttonScroll setFrame:CGRectMake(0, 800, 768, 160)];

    }else if (toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
      //portrait
    [mT.buttonScroll setFrame:CGRectMake(0, 800, 768, 160)];

    }
}
</code>```

Everything rotates properly, but once I rotate a second time the scroll view becomes completely untouchable. Cannot scroll it or touch any of the buttons in it. Then if I rotate back to the previous view the touch comes back and so on. Does anyone know why it is doing this?

答:
I too faced same issue
Follow the following steps:
1.Give top, bottom, leading and bottom constraint to scrollview
2.To the wrapper view within scrollview give top, bottom, leading and bottom as well as equal width with the parent view.
3. Very important step: Link all the internal UI elements with leading, trailing, top, bottom and height. Specially for last elemnt remember to add bottom as well as height and trailing too

Body:
In my

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;

method, I have code to reposition and resize a scrollview as the app rotates with the device. I do it with the following code:

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{

    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:0.5f];

    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
         //landscape
    [mT.buttonScroll setFrame:CGRectMake(0, 544, 1024, 160)];

    }else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        //landscape
    [mT.buttonScroll setFrame:CGRectMake(0, 544, 1024, 160)];

    }else if (toInterfaceOrientation == UIInterfaceOrientationPortrait){
       //portrait
    [mT.buttonScroll setFrame:CGRectMake(0, 800, 768, 160)];

    }else if (toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown){
      //portrait
    [mT.buttonScroll setFrame:CGRectMake(0, 800, 768, 160)];

    }
}

Everything rotates properly, but once I rotate a second time the scroll view becomes completely untouchable. Cannot scroll it or touch any of the buttons in it. Then if I rotate back to the previous view the touch comes back and so on. Does anyone know why it is doing this?


问:
How to declare global variable and initialization
how can i declare a global variable and initialize it? .

I have this situation, i am using NEXMO SMS APP in laravel and I have a global variable and I initialize it in my constructor, then i use the global variable in my public functions. After using it in my public functions, it says undefined variable. Why? . Please bare to help me, i am just a beginner.

Here is my code:

```<code> class CheckVerify extends Controller {
         private $client;
         public function __construct() {
            $client = app('Nexmo\Client');
        }

        public function mobile_verification($number) {

        $verification = $client->verify()->start([
            'number' => $number,
            'brand'  => 'Mysite'
        ]);
        }

        public function check_verify($code) {
            $client->verify()->check($verification, $code);
        }
    }
</code>```

答:
This isn't a global variable, it's called a class property, which is defined in the class (see http://php.net/manual/en/language.oop5.properties.php)

When accessing these types of variables, you have to tell PHP which object contains the variable your referring to, and when it's the current object you have to use $this.  So you class should be something like...

```<code>class CheckVerify extends Controller {
    private $client;
    public function __construct()
    {
        $this->client = app('Nexmo\Client');
    }

    public function mobile_verification($number)
    {
        $verification = $client->verify()->start([
            'number' => $number,
            'brand'  => 'Mysite'
        ]);
    }

    public function check_verify($code)
    {
        $this->client->verify()->check($verification, $code);
    }
}
</code>```

As an extra option - consider rather than hard coding the value in the constructor ...

```<code>$this->client = app('Nexmo\Client');
</code>```

Pass this in as a value to the constructor...

```<code>public function __construct( $client ) {
    $this->client = $client;
}
</code>```

This is called dependency injection (DI) and allows much more flexibility.

Body:
how can i declare a global variable and initialize it? .

I have this situation, i am using NEXMO SMS APP in laravel and I have a global variable and I initialize it in my constructor, then i use the global variable in my public functions. After using it in my public functions, it says undefined variable. Why? . Please bare to help me, i am just a beginner.

Here is my code:

 class CheckVerify extends Controller {
         private $client;
         public function __construct() {
            $client = app('Nexmo\Client');
        }

        public function mobile_verification($number) {

        $verification = $client->verify()->start([
            'number' => $number,
            'brand'  => 'Mysite'
        ]);
        }

        public function check_verify($code) {
            $client->verify()->check($verification, $code);
        }
    }

Body:
This isn't a global variable, it's called a class property, which is defined in the class (see http://php.net/manual/en/language.oop5.properties.php)

When accessing these types of variables, you have to tell PHP which object contains the variable your referring to, and when it's the current object you have to use $this.  So you class should be something like...

class CheckVerify extends Controller {
    private $client;
    public function __construct()
    {
        $this->client = app('Nexmo\Client');
    }

    public function mobile_verification($number)
    {
        $verification = $client->verify()->start([
            'number' => $number,
            'brand'  => 'Mysite'
        ]);
    }

    public function check_verify($code)
    {
        $this->client->verify()->check($verification, $code);
    }
}

As an extra option - consider rather than hard coding the value in the constructor ...

$this->client = app('Nexmo\Client');

Pass this in as a value to the constructor...

public function __construct( $client ) {
    $this->client = $client;
}

This is called dependency injection (DI) and allows much more flexibility.