问:
Keil memory window
I need to write data to the program’s internal memory (flash) at an address starting at 0x08000000 for further processing. To do this, I open the memory window with the desired address, select the byte, enter the number, press "Enter", but nothing happens and the data entered is not saved. You can watch the video demonstrating the process here: https://2ch.hk/pr/src/1499956/15818644469750.mp4. In this case, the data at 0x20000000 is recorded without problems. But I need the data exactly in the flash, how to fix it?</p>

答: The debugger is not capable of writing to flash.  You can get your data into that memory location in one of two ways: either by embedding it into your source code and using the linker to control its location, or by writing to the flash from software (assuming the device you're using is able to do this, most are - check the device manual).</p>

Title: Keil memory window


来源: stackexchange

问:
Using up bandwidth when calling readfile() on a different server?
I have a question about how servers communicate with each other and how it takes up bandwidth.  I'll use an example to better explain my question.

I have two sites: www.jojoedad.com and resources.jojoedad.com.  Each site resides on a separate server (with different IPs and on different machines).  "www| is used mainly for handling front-end tasks such as serving up different web pages.  "resources" stores a whole bunch of video files and is meant to only serve up large video files.

Assume that I code it correctly so only "www" can be accessed by the public and "resources" can only be accessed by calling scripts on "www".  Will large bandwidths of "www" be taken up if users retrieve videos on "resources" through www.jojoedad.com like this:

```<code>http://www.jojoedad.com/getVideo.php?filename=myVideo.mp4
</code>```

and in getVideo.php, I have something like this:

```<code>header("Content-Type..."); // I didn't fill in details for this line
header("Content-disposition..."); // I didn't fill in details for this line
header("COntent-description..."); // I didn't fill in details for this line
readfile("http://resources.jojoedad.com/video_files/{$_GET['filename']}");
</code>```

Thanks in advance!

答: Yes, it will use the bandwidth needed by the video once on resources and once again on www</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a question about how servers communicate with each other and how it takes up bandwidth.  I'll use an example to better explain my question.

I have two sites: www.jojoedad.com and resources.jojoedad.com.  Each site resides on a separate server (with different IPs and on different machines).  "www| is used mainly for handling front-end tasks such as serving up different web pages.  "resources" stores a whole bunch of video files and is meant to only serve up large video files.

Assume that I code it correctly so only "www" can be accessed by the public and "resources" can only be accessed by calling scripts on "www".  Will large bandwidths of "www" be taken up if users retrieve videos on "resources" through www.jojoedad.com like this:

http://www.jojoedad.com/getVideo.php?filename=myVideo.mp4

and in getVideo.php, I have something like this:

header("Content-Type..."); // I didn't fill in details for this line
header("Content-disposition..."); // I didn't fill in details for this line
header("COntent-description..."); // I didn't fill in details for this line
readfile("http://resources.jojoedad.com/video_files/{$_GET['filename']}");

Thanks in advance!


问:
Stack class in java.util a violation of Liskov substitution principle?
From the documentation of https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

```<code>public class Stack<E> extends Vector<E>
</code>```

Isn't this a violation of the Liskov substitution principle? The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.

For example: Let us say that I have a function that takes a Vector as an input. If while calling a function I start passing it a Stack then it might break because Stack prevents random access of elements.

```<code>import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(Vector<Book> books) {
        # This should not be allowed for Stack, Stack is FILO
        System.out.println(books.get(1));
    }

    public static void main(String[] args) {
        Vector<Book> books = new Vector<>();
        books.add(new Book());
        books.add(new Book());
        books.add(new Book());
        process(books);
        System.out.println("ok");

        Stack<Book> bookz = new Stack();
        bookz.add(new Book());
        bookz.add(new Book());
        bookz.add(new Book());
        process(bookz);
        System.out.println("ok");
    }
}
</code>```

答:
Having Stack extends Vector implies that it inherits all of the Vector's methods. This violates the principle. Why?

The Stack abstract data type is a LIFO (last in, first out), and it usually supports operations like: pop, push, peek, top, isEmpty, ...

Java's stack supports operations that are not "stack operations", that are inherited from the Vector's class, like insertElementAt, removeElementAt and more.

ContentLicense: CC BY-SA 4.0

Body:
From the documentation of https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

public class Stack<E> extends Vector<E>

Isn't this a violation of the Liskov substitution principle? The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.

For example: Let us say that I have a function that takes a Vector as an input. If while calling a function I start passing it a Stack then it might break because Stack prevents random access of elements.

import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(Vector<Book> books) {
        # This should not be allowed for Stack, Stack is FILO
        System.out.println(books.get(1));
    }

    public static void main(String[] args) {
        Vector<Book> books = new Vector<>();
        books.add(new Book());
        books.add(new Book());
        books.add(new Book());
        process(books);
        System.out.println("ok");

        Stack<Book> bookz = new Stack();
        bookz.add(new Book());
        bookz.add(new Book());
        bookz.add(new Book());
        process(bookz);
        System.out.println("ok");
    }
}


问:
Can i combine unicode categories in Regex?
I want to get such set of symbols:

\P{L} unicode category use as base

add хХxXтТTоОoO0 symbols to \P{L} unicode category

do not use symbols -_.

By that i get such regex in Java:

```<code>[[\P{L}]&&[^-_.]&&[хХxXтТTоОoO0]]
</code>```

But this not working, what's wrong?

答:
Reading this page using &&[хХxXтТTоОoO0] means an intersection.

You could add matching хХxXтТTоОoO0 to the first character class [\\P{L}хХxXтТTоОoO0]

Then use subtraction for that character class using &&[^-_.]

```<code>[[\\P{L}хХxXтТTоОoO0]&&[^-_.]]
</code>```

Java demo

Example

```<code>final String regex = "[[\\P{L}хХxXтТTоОoO0]&&[^-_.]]";
final String string = "aTo-_.#$";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group(0));
}
</code>```

Output

```<code>T
o
#
$
</code>```

Body:
I want to get such set of symbols:

\P{L} unicode category use as base

add хХxXтТTоОoO0 symbols to \P{L} unicode category

do not use symbols -_.

By that i get such regex in Java:

[[\P{L}]&&[^-_.]&&[хХxXтТTоОoO0]]

But this not working, what's wrong?

Body:
Reading this page using &&[хХxXтТTоОoO0] means an intersection.

You could add matching хХxXтТTоОoO0 to the first character class [\\P{L}хХxXтТTоОoO0]

Then use subtraction for that character class using &&[^-_.]

[[\\P{L}хХxXтТTоОoO0]&&[^-_.]]

Java demo

Example

final String regex = "[[\\P{L}хХxXтТTоОoO0]&&[^-_.]]";
final String string = "aTo-_.#$";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group(0));
}

Output

T
o
#
$


问:
OnClickListener in RecyclerView Adapter not initialized
I am trying to add an OnClickListener to a recycler view item i however keep getting this error

```<code>lateinit property listener has not been initialized
</code>```

Here is how my adapter looks like

```<code>class CartAdapter(private val cartItems: List<CartItemEntity>? = null) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    private lateinit var listener: OnItemClickListener

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.cart_item, parent, false)
        return CartViewHolder(view, cartItems!!, listener)
    }

    override fun getItemCount() = cartItems!!.size

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        val cartItem = cartItems?.get(position)
        holder.productPrice.text = cartItem.productPrice.toInt().toString()
        holder.cart = listOf(cartItem)
    }

    class CartViewHolder(val view: View, var cart: List<CartItemEntity>, listener: OnItemClickListener) : RecyclerView.ViewHolder(view) {
        private val cartRemove: TextView = view.findViewById(R.id.cartRemove)

        init {
            cartRemove.setOnClickListener {
                listener.onItemClick(cart)
            }

        }
    }

    interface OnItemClickListener{
        fun onItemClick(cartItems: List<CartItemEntity>?)
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.listener = listener
    }

}
</code>```

This is how i am implementing it in my Fragment

```<code>adapter!!.setOnItemClickListener(object : CartAdapter.OnItemClickListener{
            override fun onItemClick(cartItems: List<CartItemEntity>?) {
                Log.e("Cart Item", ""+ cartItems!![0].id)
            }
        })
</code>```

Not sure what am doing wrong

答:
create constructor inside your Adapter

```<code>  public Adapter(ListenerAdapter click) {
    this.click = click;
}
</code>```

and send object from fragment when you create recyclerView

```<code>private void initRecyclerView(View view) {
    adapter = new Adapter(this);}
</code>```

in my case I create View Holder how another class and i have to send listener to ViewHolder too, like below

```<code> @NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.item_main_activity, parent, false);
    // we send part of ListenerAdapter to ViewHolder
    return new ViewHolder(view,click);
}
</code>```

Body:
I am trying to add an OnClickListener to a recycler view item i however keep getting this error

lateinit property listener has not been initialized

Here is how my adapter looks like

class CartAdapter(private val cartItems: List<CartItemEntity>? = null) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    private lateinit var listener: OnItemClickListener

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.cart_item, parent, false)
        return CartViewHolder(view, cartItems!!, listener)
    }

    override fun getItemCount() = cartItems!!.size

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        val cartItem = cartItems?.get(position)
        holder.productPrice.text = cartItem.productPrice.toInt().toString()
        holder.cart = listOf(cartItem)
    }

    class CartViewHolder(val view: View, var cart: List<CartItemEntity>, listener: OnItemClickListener) : RecyclerView.ViewHolder(view) {
        private val cartRemove: TextView = view.findViewById(R.id.cartRemove)

        init {
            cartRemove.setOnClickListener {
                listener.onItemClick(cart)
            }

        }
    }

    interface OnItemClickListener{
        fun onItemClick(cartItems: List<CartItemEntity>?)
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.listener = listener
    }

}

This is how i am implementing it in my Fragment

adapter!!.setOnItemClickListener(object : CartAdapter.OnItemClickListener{
            override fun onItemClick(cartItems: List<CartItemEntity>?) {
                Log.e("Cart Item", ""+ cartItems!![0].id)
            }
        })

Not sure what am doing wrong

Body:
create constructor inside your Adapter

  public Adapter(ListenerAdapter click) {
    this.click = click;
}

and send object from fragment when you create recyclerView

private void initRecyclerView(View view) {
    adapter = new Adapter(this);}

in my case I create View Holder how another class and i have to send listener to ViewHolder too, like below

 @NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.item_main_activity, parent, false);
    // we send part of ListenerAdapter to ViewHolder
    return new ViewHolder(view,click);
}


问:
PHP setting to enable <?=
I just upgraded my WAMP.

A lot of my code used to use <?=$variable?> for a quick echo statement. Does anyone know the php setting to turn this back on?

答:
In php.ini this variable is called short_open_tag

Check this php manual: http://php.net/manual/en/ini.core.php for turning this ON.

Title: PHP setting to enable <?=


问:
The image overlay is stuck at the bottom of the image and is not moving when the user hovers over
I´m trying to overlay images with a description and when the user hovers the mouse over the overlay it will move down and show the photo that is underneath.

However the overlays seem to be stuck like this. With what looks like the overlays stuck to the bottom adn when you hover the mouse nothing happens.

please excuse the images they´re just a random photo.

my html looks like this

```<code><div class="Portfolio_container">
    <div class="Portfolio">
        <div class="section group">
            <div class="col span_1_of_3">
              <img src="Images/Dundee.jpg" alt="Avatar" class="image">
              <div class="overlay">
                <div class="text">Hello World</div>
              </div>
            </div>
            <div class="col span_1_of_3">
                <img src="Images/Dundee.jpg" alt="Avatar" class="image">
                 <div class="overlay">
                   <div class="text">Hello World</div>
                 </div>
            </div>
            <div class="col span_1_of_3">
                <img src="Images/Dundee.jpg" alt="Avatar" class="image">
                <div class="overlay">
                    <div class="text">Hello World</div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

and my CSS

```<code>.Portfolio_container {
  background-color: #847470;     /* colour of the whole portfolio page */
}

.Portfolio {               /* keeps the examples in the middle with the background colour matching the container that surounds it*/
  width: auto;
  margin-right: 5%;
  margin-left: 5%;
  background-color: #847470;
}

/*  SECTIONS  */
.section {
  clear: both;
  padding: 0px;
  margin: 0px;
}

/*  COLUMN SETUP  */
.col {
  display: block;
  float:left;
  margin: 1% 0 1% 2%;
}
.col:first-child { margin-left: 0; }

/*  GROUPING  */
.group:before,
.group:after { content:""; display:table; }
.group:after { clear:both;}
.group { zoom:1; /* For IE 6/7 */ }

/*  GRID OF THREE  */
.span_3_of_3 { width: 100%; }
.span_2_of_3 { width: 66%; }
.span_1_of_3 { width: 32%; }

/*  GO FULL WIDTH BELOW 480 PIXELS */
@media only screen and (max-width: 480px) {
  .col {  margin: 1% 0 1% 0%; }
  .span_3_of_3, .span_2_of_3, .span_1_of_3 { width: 100%; }
}

.span_1_of_3 {
  height: 100%;
}

.image {
  max-width: 100%;     /* keeps the portfolio images within their divs */
  max-height: 100%;
  display: block;
  width: 100%;
  height: auto;
}

.overlay {

  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: .5s ease;
  opacity: 0.5;
}

.span_1_of_3:hover .overlay {
  height: 0%;
}

.text {
  color: white;
  font-size: 20px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  text-align: center;
}
</code>```

any help would be greatly appreciated.

答:
found the solution. </p>

```<code>.span_1_of_3 {
    height: auto;
    position: relative;
}
</code>```

<p>I had to make the div that was containing the overlays to have a relative position. Hopes this helps anyone who has this problem. </p>

Body:
I´m trying to overlay images with a description and when the user hovers the mouse over the overlay it will move down and show the photo that is underneath.

However the overlays seem to be stuck like this. With what looks like the overlays stuck to the bottom adn when you hover the mouse nothing happens.

please excuse the images they´re just a random photo.

my html looks like this

Hello World

Hello World

Hello World

and my CSS

.Portfolio_container {
  background-color: #847470;     /* colour of the whole portfolio page */
}

.Portfolio {               /* keeps the examples in the middle with the background colour matching the container that surounds it*/
  width: auto;
  margin-right: 5%;
  margin-left: 5%;
  background-color: #847470;
}

/*  SECTIONS  */
.section {
  clear: both;
  padding: 0px;
  margin: 0px;
}

/*  COLUMN SETUP  */
.col {
  display: block;
  float:left;
  margin: 1% 0 1% 2%;
}
.col:first-child { margin-left: 0; }

/*  GROUPING  */
.group:before,
.group:after { content:""; display:table; }
.group:after { clear:both;}
.group { zoom:1; /* For IE 6/7 */ }

/*  GRID OF THREE  */
.span_3_of_3 { width: 100%; }
.span_2_of_3 { width: 66%; }
.span_1_of_3 { width: 32%; }

/*  GO FULL WIDTH BELOW 480 PIXELS */
@media only screen and (max-width: 480px) {
  .col {  margin: 1% 0 1% 0%; }
  .span_3_of_3, .span_2_of_3, .span_1_of_3 { width: 100%; }
}

.span_1_of_3 {
  height: 100%;
}

.image {
  max-width: 100%;     /* keeps the portfolio images within their divs */
  max-height: 100%;
  display: block;
  width: 100%;
  height: auto;
}

.overlay {

  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: .5s ease;
  opacity: 0.5;
}

.span_1_of_3:hover .overlay {
  height: 0%;
}

.text {
  color: white;
  font-size: 20px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  text-align: center;
}

any help would be greatly appreciated.

Body:
found the solution.

.span_1_of_3 {
    height: auto;
    position: relative;
}

I had to make the div that was containing the overlays to have a relative position. Hopes this helps anyone who has this problem.


问:
How to know if SSL established at HAProxy level on app level?
I have an HAProxy instance that is available from the web, and redirects incoming requests to my local app.

The communication between the client and my HAProxy can be secured via ssl but not necessarily, and I need to know at my application level if the communication is secure or not.

Unfortunately, from my understanding, the communication I get in my app is already "decrypted" from all the SSL communications, HAProxy handling the "SSL wrapping".

Is there a way to know for sure that the client is using SSL/TLS or no?

Thank you in advance.

Update The communication is not HTTP but TCP at HAProxy.

答:
This is the purpose of the X-Forwarded-Proto.

You can make HAProxy insert that header if ssl traffic was decrypted by HAProxy:

http-request set-header X-Forwarded-Proto https if { ssl_fc }

Then your application will just have to check the X-Forwarded-Proto.


问:
How to clear the console screen when introducing input in Java?
Is there a way to clear the console when the Java program detects the user it's introducing some data?

I'm executing a program that does the following:

```<code>User: //enter username
//show data of the username
</code>```

I want to make it so the user can search for as many users he want until he ends the execution.
To make it clear and nice, after each username search, I want to clear the screen when the program detects the user is typing something (filling the buffer).

Is there any way to do this?

This is the code I'm using to clear the console (this does not detect when the user is typing):

```<code>public static void clearScreen() {
    System.out.print("\033[H\033[2J");
    System.out.flush();
}
</code>```

Thanks in advance.

答:
You cannot use System.in without pressing the ENTER key at the end. Its the only way. System.in is not aware of the user input until enter is pressed. So if you are using a normal command line to do this, this won't work and you have to stick different raw command lines like jline

For example :

```<code>Terminal terminal = TerminalBuilder.builder().system(true).jna(true).build();
terminal.enterRawMode(); //this enters into a raw mode and get's input on reader
reader = terminal.reader();
//finally
reader.close();
</code>```

You can check it out. Although it highly doesn't make sense to bring in more dependencies unless you really want to and could just stick to a simple while loop

If you are using maven here's the dependency you can use.

```<code><dependency>
    <groupId>org.jline</groupId>
    <artifactId>jline</artifactId>
</dependency>
</code>```

Body:
Is there a way to clear the console when the Java program detects the user it's introducing some data?

I'm executing a program that does the following:

User: //enter username
//show data of the username

I want to make it so the user can search for as many users he want until he ends the execution.
To make it clear and nice, after each username search, I want to clear the screen when the program detects the user is typing something (filling the buffer).

Is there any way to do this?

This is the code I'm using to clear the console (this does not detect when the user is typing):

public static void clearScreen() {
    System.out.print("\033[H\033[2J");
    System.out.flush();
}

Thanks in advance.

Body:
You cannot use System.in without pressing the ENTER key at the end. Its the only way. System.in is not aware of the user input until enter is pressed. So if you are using a normal command line to do this, this won't work and you have to stick different raw command lines like jline

For example :

Terminal terminal = TerminalBuilder.builder().system(true).jna(true).build();
terminal.enterRawMode(); //this enters into a raw mode and get's input on reader
reader = terminal.reader();
//finally
reader.close();

You can check it out. Although it highly doesn't make sense to bring in more dependencies unless you really want to and could just stick to a simple while loop

If you are using maven here's the dependency you can use.

<dependency>
    <groupId>org.jline</groupId>
    <artifactId>jline</artifactId>
</dependency>


问:
Alert box is not working in function while validating username and password using if condition in javascript
```<code>    function validate() {
        var x=document.getElementById("user").value;
        var y=document.getElementById("pass").value;
        if(x==null || x==" ") {
            alert("Enter username");
        }
        if(y==null || y==" ") {
            alert("Enter password");
        }
    }
</code>```

答:
if(x === undefined || x === null || x.trim() === '') alert('Please enter a username');
if(y === undefined || y === null || y.trim() === '') alert('Please enter a password');
```


问:
Silverlight Get Records Problem
I am usinq MySqlServer Domain Service and ADO.NET Entity Model for Silverlight Database works.

When I get the records from DataBase my grid get the columns name but there is no row no data. Sometimes my grid is invisible after I give ItemSource

this is my codes.

```<code>var q=DomainService.getItemQuery();
LoadOperation<TypeOfItem> c = Sk.Load<TypeOfItem>(q);
datagrid.ItemSource=c.Entities;
</code>```

What Can I do? i try get the 500

答: Have you checked that your LoadOperation is completing without errors?  I.E. is c.Entities null?</p>

Title: Silverlight Get Records Problem

Body:
I am usinq MySqlServer Domain Service and ADO.NET Entity Model for Silverlight Database works.

When I get the records from DataBase my grid get the columns name but there is no row no data. Sometimes my grid is invisible after I give ItemSource

this is my codes.

var q=DomainService.getItemQuery();
LoadOperation<TypeOfItem> c = Sk.Load<TypeOfItem>(q);
datagrid.ItemSource=c.Entities;

What Can I do? i try get the 500


问:
Group a list of objects by Unique key as a object using Java API
I am trying to create a key and value relationship and return in a json format between list of data returned by Database. I'm able to achieve the relationship  but not able to get the desired Json Format as a output

```<code>StudentProfResponse = profRepository.getstudentProfessorHirarchy();

studentprofResponse.stream().collect(Collectors.groupingBy(StudentProfResponse::getProfessorName));
</code>```

Db Results

ProfessorName ProfessorId StudentId StudentName

Vinay    P123      S567   Karthik

   Vinay  P123   S568   Jeevan

   Mayank P657   S569   Meena

   Vasu   P723   S570   Vijay

Json Format Im getting with the above code

```<code>[
{
    "vinay": [
        {
            "studentId": "S567",
            "StudentName": "Karthik",
            "professorName": "Vinay",
            "professorId": "P123"
        },
        {
            "studentId": "S568",
            "StudentName": "Jeevan",
            "professorName": "Vinay",
            "professorId": "P123"
        }
    ]
},
{
    "Mayank": [
        {
            "studentId": "S569",
            "StudentName": "Meena",
            "professorName": "Mayank",
            "professorId": "P657"
        }
    ]
},
{
    "vasu": [
        {
            "studentId": "S570",
            "StudentName": "Vijay",
            "professorName": "Vasu",
            "professorId": "P723"
        }
    ]
}
</code>```

]

Json format im Expecting

```<code>[
 {
    "professorName": "Vinay",
    "professorId" : "P123",
    "studentDetails": [
        {
            "studentId": "S567",
            "StudentName": "Karthik"
        },
        {
            "studentId": "S568",
            "StudentName": "Jeevan"
        }
    ]
},
{
    "professorName": "Mayank",
    "professorId" : "P657",
    "studentDetails": [
        {
            "studentId": "S569",
            "StudentName": "Meena"
        }
    ]
},
{
    "professorName": "Vasu",
    "professorId" : "P723",
    "studentDetails": [
        {
            "studentId": "S570",
            "StudentName": "Vijay"
        }
    ]
 }
]
</code>```

Is there a way, I can achieve above Json Format through Java 8 stream API by creating a bean class like and send a List of studprofrelationship details

```<code>public class StudentProfessorRelationship {

private Integer professorNo;

private String professorName;

private List<StudentDetails> studentDetails;

}
</code>```

答:
We can use Collectors.toMap with mergeFunction parameter of Collectors.toMap(keyMapper, valueMapper, mergeFunction):</p>

```<code>  studentprofResponse.stream()
    .map(resp-> new StudentProfessorRelationship(/*add arguments*/) )
    .collect(
             Collectors.toMap(
                              StudentProfessorRelationship::getProfessorName,
                              Function.identity(),
                              (relationship1, relationship2) -> {
                                      relationship1.getstudentDetails().addAll(
                                           relationship2.getstudentDetails());
                                       return realtionship1;} ))
      .values();
</code>```

Body:
I am trying to create a key and value relationship and return in a json format between list of data returned by Database. I'm able to achieve the relationship  but not able to get the desired Json Format as a output

StudentProfResponse = profRepository.getstudentProfessorHirarchy();

studentprofResponse.stream().collect(Collectors.groupingBy(StudentProfResponse::getProfessorName));

Db Results

ProfessorName ProfessorId StudentId StudentName

Vinay    P123      S567   Karthik

   Vinay  P123   S568   Jeevan

   Mayank P657   S569   Meena

   Vasu   P723   S570   Vijay

Json Format Im getting with the above code

[
{
    "vinay": [
        {
            "studentId": "S567",
            "StudentName": "Karthik",
            "professorName": "Vinay",
            "professorId": "P123"
        },
        {
            "studentId": "S568",
            "StudentName": "Jeevan",
            "professorName": "Vinay",
            "professorId": "P123"
        }
    ]
},
{
    "Mayank": [
        {
            "studentId": "S569",
            "StudentName": "Meena",
            "professorName": "Mayank",
            "professorId": "P657"
        }
    ]
},
{
    "vasu": [
        {
            "studentId": "S570",
            "StudentName": "Vijay",
            "professorName": "Vasu",
            "professorId": "P723"
        }
    ]
}

]

Json format im Expecting

[
 {
    "professorName": "Vinay",
    "professorId" : "P123",
    "studentDetails": [
        {
            "studentId": "S567",
            "StudentName": "Karthik"
        },
        {
            "studentId": "S568",
            "StudentName": "Jeevan"
        }
    ]
},
{
    "professorName": "Mayank",
    "professorId" : "P657",
    "studentDetails": [
        {
            "studentId": "S569",
            "StudentName": "Meena"
        }
    ]
},
{
    "professorName": "Vasu",
    "professorId" : "P723",
    "studentDetails": [
        {
            "studentId": "S570",
            "StudentName": "Vijay"
        }
    ]
 }
]

Is there a way, I can achieve above Json Format through Java 8 stream API by creating a bean class like and send a List of studprofrelationship details

public class StudentProfessorRelationship {

private Integer professorNo;

private String professorName;

private List<StudentDetails> studentDetails;

}

Body:
We can use Collectors.toMap with mergeFunction parameter of Collectors.toMap(keyMapper, valueMapper, mergeFunction):

  studentprofResponse.stream()
    .map(resp-> new StudentProfessorRelationship(/*add arguments*/) )
    .collect(
             Collectors.toMap(
                              StudentProfessorRelationship::getProfessorName,
                              Function.identity(),
                              (relationship1, relationship2) -> {
                                      relationship1.getstudentDetails().addAll(
                                           relationship2.getstudentDetails());
                                       return realtionship1;} ))
      .values();


问:
Difference between state data and destructuring in react
This is very basic of React but I really need to understand why it is behaving in this way.
Is there any difference between this part of code :
Example1:

```<code>increment = () => {
const { count } = this.state; // doing destructure ...
this.setState({ count: count + 1 }, () => {
console.log("Clicked times: ", count);
});
};

</code>```

and this part Example2:

```<code>increment = () => {
//const { count } = this.state;
this.setState({ count: this.state.count + 1 }, () => { //putting "this.state.count" directly
console.log("Clicked times: ", this.state.count);
});
};

</code>```

Because when I do the second way (Example2), then I get the correct output:
Its asynchronous way and show the same data both in browser and in console. Why the first example does not work in correct way, is it because I am saving the value in a new variable ( by doing de-structuring).
Here is my Whole code link: https://codesandbox.io/s/counting-in-react-j0uyc

Any help will be appreciated! Thanks

答:
In the distructure example you set the state as count+1 then console the count. but when you update the state it's update the state, not the local variable count, so you console the old count.

If after this.setState({count: count+1}) you console the this.state.count anything will look fine

Body:
This is very basic of React but I really need to understand why it is behaving in this way.
Is there any difference between this part of code :
Example1:

increment = () => {
const { count } = this.state; // doing destructure ...
this.setState({ count: count + 1 }, () => {
console.log("Clicked times: ", count);
});
};

and this part Example2:

increment = () => {
//const { count } = this.state;
this.setState({ count: this.state.count + 1 }, () => { //putting "this.state.count" directly
console.log("Clicked times: ", this.state.count);
});
};

Because when I do the second way (Example2), then I get the correct output:
Its asynchronous way and show the same data both in browser and in console. Why the first example does not work in correct way, is it because I am saving the value in a new variable ( by doing de-structuring).
Here is my Whole code link: https://codesandbox.io/s/counting-in-react-j0uyc

Any help will be appreciated! Thanks


问:
Is there a better way than using a generic WildCard as a method parameter?
I need my getNextId() method for three different maps:

```<code>private final Map<Integer, Track> tracks;
private final Map<Integer, Train> trains;

private final Map<Integer, Coach> coaches;
</code>```

So far, I had three different methods but that's obviously unnecessary. Is there a better way than using the generic wildcard ? if the method only needs to be working for the above maps?

```<code>public int getNextId(Map<Integer, ?> givenMap) {
            int id = 1;
        for (int key : givenMap.keySet()) {
            if (key > id) break;
            id = key + 1;
        }
        return id;
}
</code>```

The getNextId() method basically gets the smallest available ID >=1. If trainIDs 1, 2, 3, 4 exist and the user deletes train with ID 2, the next added train gets ID 2.

答:
Basically I would suggest to be as precise as possible. If you know your function works only for a fix set of classes, you shouldn´t make it possible to pass any class - which would apply to the ?-wildcard. Otherwise you´d get some weird runtime-errors, because I may simply provide a HashMap<Integer, MyOwnClass> without the compiler complaining. Furthermore you can´t do much on ?, which will evaluate to Object. So if you would need to evauate the maps values some day, you´d have a pretty big issue because you get just Object. Changing the methods signature may mor may not be possible at this time, if you have existing clients outside. So I´d strongly suggest not to use the ? unless you really mean "any arbitrary type of map".

You seem to have three types that all have some kind of an identifier. So best would be to extract an interface for them and use that within your implementation:

```<code>interface MyInterface { }
class Track : MyInterface { }
class Train : MyInterface { }
class Coach: MyInterface { }
</code>```

Now it´s easy to define your method:

```<code>public int getNextId(Map<Integer, ? extends MyInterface> givenMap) { ... }
</code>```

Apart from this I can´t see why you even use any map in the first place, when you´re just interested in the keys. Better just provide a List<Integer> or similar.

Body:
I need my getNextId() method for three different maps:

private final Map<Integer, Track> tracks;
private final Map<Integer, Train> trains;

private final Map<Integer, Coach> coaches;

So far, I had three different methods but that's obviously unnecessary. Is there a better way than using the generic wildcard ? if the method only needs to be working for the above maps?

public int getNextId(Map<Integer, ?> givenMap) {
            int id = 1;
        for (int key : givenMap.keySet()) {
            if (key > id) break;
            id = key + 1;
        }
        return id;
}

The getNextId() method basically gets the smallest available ID >=1. If trainIDs 1, 2, 3, 4 exist and the user deletes train with ID 2, the next added train gets ID 2.

Body:
Basically I would suggest to be as precise as possible. If you know your function works only for a fix set of classes, you shouldn´t make it possible to pass any class - which would apply to the ?-wildcard. Otherwise you´d get some weird runtime-errors, because I may simply provide a HashMap<Integer, MyOwnClass> without the compiler complaining. Furthermore you can´t do much on ?, which will evaluate to Object. So if you would need to evauate the maps values some day, you´d have a pretty big issue because you get just Object. Changing the methods signature may mor may not be possible at this time, if you have existing clients outside. So I´d strongly suggest not to use the ? unless you really mean "any arbitrary type of map".

You seem to have three types that all have some kind of an identifier. So best would be to extract an interface for them and use that within your implementation:

interface MyInterface { }
class Track : MyInterface { }
class Train : MyInterface { }
class Coach: MyInterface { }

Now it´s easy to define your method:

public int getNextId(Map<Integer, ? extends MyInterface> givenMap) { ... }

Apart from this I can´t see why you even use any map in the first place, when you´re just interested in the keys. Better just provide a List<Integer> or similar.


问:
Unable to add in the text colour of my menu navbar
This should be a fairly simple thing, however no matter where I add in color: black; the menu items do not show, you can only see them when I click and highlight over them. Please could someone point out which class needs to color tag to alter the text colour to black? I have tried placing it in .topnav with color: black; but did not change anything?

Also I can't get the active class to change when I'm on a different page, seems to only stay on the Home page?

```<code>.topnav {
  background-color:white;
  overflow: hidden;
}

/* Style the links inside the navigation bar */
.topnav a {
  float: left;
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Add an active class to highlight the current page */
.active {
  background-color: grey;
  color: white;
}

/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
  display: none;
}

/* Dropdown container - needed to position the dropdown content */
.dropdown {
  float: left;
  overflow: hidden;
}

/* Style the dropdown button to fit inside the topnav */
.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

/* Style the dropdown content (hidden by default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Style the links inside the dropdown */
.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a dark background on topnav links and the dropdown button on hover */
.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #555;
  color: white;
}

/* Add a grey background to dropdown links on hover */
.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

/* Show the dropdown menu when the user moves the mouse over the dropdown button */
.dropdown:hover .dropdown-content {
  display: block;
}
</code>```

THE MENU CODE:

```<code><!-- NAV BAR homepage-->
<nav>
  <!-- https://www.w3schools.com/howto/howto_js_topnav_responsive.asp -->
  <div class="topnav" id="myTopnav">
      <a href="index.php" class="active"><i class="fas fa-home">  Home</i></a>
      <a href="about.php"><i class="fas fa-info-circle">  About</i></a>
      <a href="contact.php"><i class="fas fa-envelope">  Contact</i></a>
      <?php
        // The below is a small 'if else' statement which depending on whether a user is logged in or not, the menu items will differ
        // If logged in, then show the logout and the dashboard item
        // If not logged in, then show the login and signup button
        if (!isset($_SESSION['studentID'])) {
          echo "<a name='login-submit' href='login.php'><i class='fas fa-sign-in-alt'>  Login</i></a>";
          echo "<a href='signup.php'><i class='fas fa-check-square'>  Sign Up</i></a>";
        } else if (isset($_SESSION['studentID'])) {
          echo "<a href ='dashboard.php'><i class='fas fa-tachometer-alt'>  Dashboard</i></a> ";
          echo "<a name='logout-submit' href='scripts/logout-script.php'><i class='fas fa-sign-out-alt'>  Logout</i></a>";
        }
      ?>
      <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="menu2Function()">☰</a>
  </div>
</nav>
</code>```

I have right clicked into the console to check the styles tab:

This is what I see on my screen without hovering over an item in the menu:

Then this is what I see when I hover over an item (About):

答:
in above code if you want to add background full navbar then added

.topnav{
      background-color:hotpink;
      overflow:hidden;
     }

image look like below

if you want to added background only item then added below style code into

```<code>.topnav a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    background: red;// background will be red all menu item
    }
</code>```

image like below

Body:
This should be a fairly simple thing, however no matter where I add in color: black; the menu items do not show, you can only see them when I click and highlight over them. Please could someone point out which class needs to color tag to alter the text colour to black? I have tried placing it in .topnav with color: black; but did not change anything?

Also I can't get the active class to change when I'm on a different page, seems to only stay on the Home page?

.topnav {
  background-color:white;
  overflow: hidden;
}

/* Style the links inside the navigation bar */
.topnav a {
  float: left;
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Add an active class to highlight the current page */
.active {
  background-color: grey;
  color: white;
}

/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
  display: none;
}

/* Dropdown container - needed to position the dropdown content */
.dropdown {
  float: left;
  overflow: hidden;
}

/* Style the dropdown button to fit inside the topnav */
.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

/* Style the dropdown content (hidden by default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Style the links inside the dropdown */
.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a dark background on topnav links and the dropdown button on hover */
.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #555;
  color: white;
}

/* Add a grey background to dropdown links on hover */
.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

/* Show the dropdown menu when the user moves the mouse over the dropdown button */
.dropdown:hover .dropdown-content {
  display: block;
}

THE MENU CODE:

        Home
        About
        Contact
      <?php
        // The below is a small 'if else' statement which depending on whether a user is logged in or not, the menu items will differ
        // If logged in, then show the logout and the dashboard item
        // If not logged in, then show the login and signup button
        if (!isset($_SESSION['studentID'])) {
          echo "  Login";
          echo "  Sign Up";
        } else if (isset($_SESSION['studentID'])) {
          echo "  Dashboard ";
          echo "  Logout";
        }
      ?>
      ☰

I have right clicked into the console to check the styles tab:

This is what I see on my screen without hovering over an item in the menu:

Then this is what I see when I hover over an item (About):

Body:
in above code if you want to add background full navbar then added

.topnav{
      background-color:hotpink;
      overflow:hidden;
     }

image look like below

if you want to added background only item then added below style code into

.topnav a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    background: red;// background will be red all menu item
    }

image like below


问:
NSTask + calling NSLog in the task results in double printing messages to the console
I have a app that calls an NSTask, (I have written the NSTask and App code) and the NSTask calls NSLog at places where I want a line written out to the console.

Problem is that I see the console message from the NSTask, then I see the same message output by the calling process, with a double header...

```<code>5/16/11 5:50:01 PM  theNSTask[7934] BLAH BLAH BLAH
[0x0-0x256256].com.someid[7505] 2011-05-16 17:50:01.708 theNSTask[7934:903] BLAH BLAH BLAH
</code>```

Super confusing just to read the desired output (BLAH BLAH BLAH). Is there a magic setting that fixes this problem?

Thanks,

--Tom

```<code>NSTask* task = [[NSTask alloc] init];
NSString* path = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"theNSTask"];
[task setLaunchPath:path];
NSMutableArray* arguments = [NSMutableArray array];
// get the dict as base64 string (start with binary plist):
NSString* base64Dict = [[self class] base64FromDictionary:message];
    [arguments addObject:base64Dict];
    [task setArguments:arguments];
[task launch];

[self.runningTasks addObject:task];
[task release];
</code>```

答:
My guess is that the task is logging the messages directly to the console and also to its standard output, which by default is the same stream as the parent process's standard output, which your app is sending to the console.

If that's true, then you should be able to fix it by setting the task's standard output to /dev/null like:

```<code>NSFileHandle *nullFileHandle = [NSFileHandle fileHandleWithNullDevice];
[task setStandardOutput:nullFileHandle];
[task setStandardError:nullFileHandle];
</code>```

Body:
I have a app that calls an NSTask, (I have written the NSTask and App code) and the NSTask calls NSLog at places where I want a line written out to the console.

Problem is that I see the console message from the NSTask, then I see the same message output by the calling process, with a double header...

5/16/11 5:50:01 PM  theNSTask[7934] BLAH BLAH BLAH
[0x0-0x256256].com.someid[7505] 2011-05-16 17:50:01.708 theNSTask[7934:903] BLAH BLAH BLAH

Super confusing just to read the desired output (BLAH BLAH BLAH). Is there a magic setting that fixes this problem?

Thanks,

--Tom

NSTask* task = [[NSTask alloc] init];
NSString* path = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"theNSTask"];
[task setLaunchPath:path];
NSMutableArray* arguments = [NSMutableArray array];
// get the dict as base64 string (start with binary plist):
NSString* base64Dict = [[self class] base64FromDictionary:message];
    [arguments addObject:base64Dict];
    [task setArguments:arguments];
[task launch];

[self.runningTasks addObject:task];
[task release];

Body:
My guess is that the task is logging the messages directly to the console and also to its standard output, which by default is the same stream as the parent process's standard output, which your app is sending to the console.

If that's true, then you should be able to fix it by setting the task's standard output to /dev/null like:

NSFileHandle *nullFileHandle = [NSFileHandle fileHandleWithNullDevice];
[task setStandardOutput:nullFileHandle];
[task setStandardError:nullFileHandle];


问:
Ternary operator (?:) in Bash
Is there a way to do something like this

```<code>int a = (b == 5) ? c : d;
</code>```

using Bash?

答:
A string-oriented alternative, that uses an array:

```<code>spec=(IGNORE REPLACE)
for p in {13..15}; do
  echo "$p: ${spec[p==14]}";
done
</code>```

which outputs:

```<code>13: IGNORE
14: REPLACE
15: IGNORE
</code>```

Title: Ternary operator (?:) in Bash

Body:
Is there a way to do something like this

int a = (b == 5) ? c : d;

using Bash?

Body:
A string-oriented alternative, that uses an array:

spec=(IGNORE REPLACE)
for p in {13..15}; do
  echo "$p: ${spec[p==14]}";
done

which outputs:

13: IGNORE
14: REPLACE
15: IGNORE


问:
"The requested URL /projects was not found on this server" when I am trying to run redmine(Ubuntu 16.04, Apache2, Passenger )
I installed passenger over apache in order to run redmine (ROR application)on Ubuntu 16.04.
I setuped everything as described in the documentation but I always get the "The requested URL /projects was not found on this server"
If I add a simple html page it loads fine.
The site configuration is teh following:

```<code><VirtualHost ip:80>
ServerName redmine.domain.com
ServerAlias www.redmine.domain.com
ServerAdmin webmaster@localhost
ServerAlias webmail.redmine.domain.com
ServerAlias admin.redmine.domain.com
DocumentRoot /home/user/public_html/redmine
PassengerRuby /home/user/.rvm/gems/ruby-2.4.2/wrappers/ruby
RailsEnv production
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory "/home/user/public_html/redmine">
      Options FollowSymLinks
      Require all granted
      Allow from all
      Options -MultiViews
</Directory>
</code>```

The error.log of apache shows the following:

```<code>[ N 2017-09-27 14:02:32.7396 7376/T1 age/Cor/CoreMain.cpp:1068 ]: Passenger core shutdown finished
[ N 2017-09-27 14:02:32.7504 7404/T1 age/Wat/WatchdogMain.cpp:1283 ]: Starting Passenger watchdog...
[ N 2017-09-27 14:02:32.7678 7408/T1 age/Cor/CoreMain.cpp:1083 ]: Starting Passenger core...
[ N 2017-09-27 14:02:32.7681 7408/T1 age/Cor/CoreMain.cpp:248 ]: Passenger core running in multi-application mode.
[ N 2017-09-27 14:02:32.7746 7408/T1 age/Cor/CoreMain.cpp:830 ]: Passenger core online, PID 7408
[ N 2017-09-27 14:02:32.7895 7417/T1 age/Ust/UstRouterMain.cpp:537 ]: Starting Passenger UstRouter...
[ N 2017-09-27 14:02:32.7905 7417/T1 age/Ust/UstRouterMain.cpp:350 ]: Passenger UstRouter online, PID 7417
[Wed Sep 27 14:02:32.832157 2017] [mpm_prefork:notice] [pid 7398] AH00163: Apache/2.4.18 (Ubuntu) mod_fcgid/2.3.9 Phusion_Passenger/5.1.8 OpenSSL/1.0.2g configured -- resuming normal operations
[Wed Sep 27 14:02:32.832208 2017] [core:notice] [pid 7398] AH00094: Command line: '/usr/sbin/apache2'
[ N 2017-09-27 14:02:34.9949 7408/T8 age/Cor/SecurityUpdateChecker.h:374 ]: Security update check: no update found (next check in 24 hours)
</code>```

Initially I was getting an error with autoindex which I disabled and now I do not get the error, but still no redmine page. Any Ideas or any other log you need?

Also the:

```<code>bundle exec passenger start
</code>```

Reports the following:

```<code>=============== Phusion Passenger Standalone web server started ===============
PID file: /home/user/public_html/redmine/tmp/pids/passenger.3000.pid
Log file: /home/user/public_html/redmine/log/passenger.3000.log
Environment: development
Accessible via: http://0.0.0.0:3000/
You can stop Phusion Passenger Standalone by pressing Ctrl-C.

===============================================================================

[ N 2017-09-27 14:43:00.4493 13372/T7 age/Cor/SecurityUpdateChecker.h:374 ]: Security update check: no update found (next check in 24 hours)
App 13412 stdout:
App 13428 stdout:
Started HEAD "/" for 127.0.0.1 at 2017-09-27 14:43:04 +0300
Processing by WelcomeController#index as HTML
   (1.1ms)  SELECT MAX(`settings`.`updated_on`) FROM `settings`
  Setting Load (0.6ms)  SELECT  `settings`.* FROM `settings` WHERE `settings`.`name` = 'rest_api_enabled'  ORDER BY `settings`.`id` DESC LIMIT 1
  AnonymousUser Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`type` IN ('AnonymousUser')  ORDER BY `users`.`id` ASC LIMIT 1
  Current user: anonymous
  Setting Load (0.6ms)  SELECT  `settings`.* FROM `settings` WHERE `settings`.`name` = 'login_required'  ORDER BY `settings`.`id` DESC LIMIT 1
Redirected to http://0.0.0.0/login?back_url=http%3A%2F%2F0.0.0.0%2F
Filter chain halted as :check_if_login_required rendered or redirected
Completed 302 Found in 180ms (ActiveRecord: 7.6ms)
</code>```

after that when I go to

```<code>links http://0.0.0.0/login?back_url=http%3A%2F%2F0.0.0.0%2F
</code>```

The page appear properly and I am able to login and work with it. Although from the redmine.domain.com I get the same error.

答:
/etc/apache2/sites-enabled/000-default.conf

from

DocumentRoot /var/www/html

to
DocumentRoot /var/www/

Body:
I installed passenger over apache in order to run redmine (ROR application)on Ubuntu 16.04.
I setuped everything as described in the documentation but I always get the "The requested URL /projects was not found on this server"
If I add a simple html page it loads fine.
The site configuration is teh following:

<VirtualHost ip:80>
ServerName redmine.domain.com
ServerAlias www.redmine.domain.com
ServerAdmin webmaster@localhost
ServerAlias webmail.redmine.domain.com
ServerAlias admin.redmine.domain.com
DocumentRoot /home/user/public_html/redmine
PassengerRuby /home/user/.rvm/gems/ruby-2.4.2/wrappers/ruby
RailsEnv production
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory "/home/user/public_html/redmine">
      Options FollowSymLinks
      Require all granted
      Allow from all
      Options -MultiViews
</Directory>

The error.log of apache shows the following:

[ N 2017-09-27 14:02:32.7396 7376/T1 age/Cor/CoreMain.cpp:1068 ]: Passenger core shutdown finished
[ N 2017-09-27 14:02:32.7504 7404/T1 age/Wat/WatchdogMain.cpp:1283 ]: Starting Passenger watchdog...
[ N 2017-09-27 14:02:32.7678 7408/T1 age/Cor/CoreMain.cpp:1083 ]: Starting Passenger core...
[ N 2017-09-27 14:02:32.7681 7408/T1 age/Cor/CoreMain.cpp:248 ]: Passenger core running in multi-application mode.
[ N 2017-09-27 14:02:32.7746 7408/T1 age/Cor/CoreMain.cpp:830 ]: Passenger core online, PID 7408
[ N 2017-09-27 14:02:32.7895 7417/T1 age/Ust/UstRouterMain.cpp:537 ]: Starting Passenger UstRouter...
[ N 2017-09-27 14:02:32.7905 7417/T1 age/Ust/UstRouterMain.cpp:350 ]: Passenger UstRouter online, PID 7417
[Wed Sep 27 14:02:32.832157 2017] [mpm_prefork:notice] [pid 7398] AH00163: Apache/2.4.18 (Ubuntu) mod_fcgid/2.3.9 Phusion_Passenger/5.1.8 OpenSSL/1.0.2g configured -- resuming normal operations
[Wed Sep 27 14:02:32.832208 2017] [core:notice] [pid 7398] AH00094: Command line: '/usr/sbin/apache2'
[ N 2017-09-27 14:02:34.9949 7408/T8 age/Cor/SecurityUpdateChecker.h:374 ]: Security update check: no update found (next check in 24 hours)

Initially I was getting an error with autoindex which I disabled and now I do not get the error, but still no redmine page. Any Ideas or any other log you need?

Also the:

bundle exec passenger start

Reports the following:

=============== Phusion Passenger Standalone web server started ===============
PID file: /home/user/public_html/redmine/tmp/pids/passenger.3000.pid
Log file: /home/user/public_html/redmine/log/passenger.3000.log
Environment: development
Accessible via: http://0.0.0.0:3000/
You can stop Phusion Passenger Standalone by pressing Ctrl-C.

===============================================================================

[ N 2017-09-27 14:43:00.4493 13372/T7 age/Cor/SecurityUpdateChecker.h:374 ]: Security update check: no update found (next check in 24 hours)
App 13412 stdout:
App 13428 stdout:
Started HEAD "/" for 127.0.0.1 at 2017-09-27 14:43:04 +0300
Processing by WelcomeController#index as HTML
   (1.1ms)  SELECT MAX(`settings`.`updated_on`) FROM `settings`
  Setting Load (0.6ms)  SELECT  `settings`.* FROM `settings` WHERE `settings`.`name` = 'rest_api_enabled'  ORDER BY `settings`.`id` DESC LIMIT 1
  AnonymousUser Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`type` IN ('AnonymousUser')  ORDER BY `users`.`id` ASC LIMIT 1
  Current user: anonymous
  Setting Load (0.6ms)  SELECT  `settings`.* FROM `settings` WHERE `settings`.`name` = 'login_required'  ORDER BY `settings`.`id` DESC LIMIT 1
Redirected to http://0.0.0.0/login?back_url=http%3A%2F%2F0.0.0.0%2F
Filter chain halted as :check_if_login_required rendered or redirected
Completed 302 Found in 180ms (ActiveRecord: 7.6ms)

after that when I go to

links http://0.0.0.0/login?back_url=http%3A%2F%2F0.0.0.0%2F

The page appear properly and I am able to login and work with it. Although from the redmine.domain.com I get the same error.


问:
Java: final string comparison does not work
I have created final strings for certain commands but when I try to check if the command given by the user matches, it does not work.

These are examples of my final strings:

```<code>public static final String END = "quit";
public static final String SHOW = "print";
</code>```

But if I were to use it e.g. like this:

```<code>String command = scanner.nextLine();
if (command == SHOW) {
   System.out.println("Print this line.");
}

</code>```

It sees that they do not match even if they do. I tried printing the finalized variables:

```<code>System.out.println(END);
</code>```

and it prints its value, but for some reason when I compare them to identical strings provided by the user, it does not recognize them.

I have tried to search similar examples and read about finalizing variables, but I think I am missing something important. I know that the problem is with the final variables and not elsewhere, because the program works if I compare these same strings with equal. E.g:

```<code>String command = scanner.nextLine();
if (command.equals("print") {
   System.out.println("Print this line.");
}
</code>```

I am assuming that there is something very simple that I am doing wrong, but I could not find any answer anywhere that I would understand. I am still a beginner and all the other examples regarding similar questions include some features that I don't understand, so they don't help me to see what I am doing wrong.

答:
```<code>String command = scanner.nextLine();
if (command.equals(SHOW) {
   System.out.println("Print this line.");
}
</code>```

Use it like this. (To answer your comment)

Body:
I have created final strings for certain commands but when I try to check if the command given by the user matches, it does not work.

These are examples of my final strings:

public static final String END = "quit";
public static final String SHOW = "print";

But if I were to use it e.g. like this:

String command = scanner.nextLine();
if (command == SHOW) {
   System.out.println("Print this line.");
}

It sees that they do not match even if they do. I tried printing the finalized variables:

System.out.println(END);

and it prints its value, but for some reason when I compare them to identical strings provided by the user, it does not recognize them.

I have tried to search similar examples and read about finalizing variables, but I think I am missing something important. I know that the problem is with the final variables and not elsewhere, because the program works if I compare these same strings with equal. E.g:

String command = scanner.nextLine();
if (command.equals("print") {
   System.out.println("Print this line.");
}

I am assuming that there is something very simple that I am doing wrong, but I could not find any answer anywhere that I would understand. I am still a beginner and all the other examples regarding similar questions include some features that I don't understand, so they don't help me to see what I am doing wrong.

Body:
String command = scanner.nextLine();
if (command.equals(SHOW) {
   System.out.println("Print this line.");
}

Use it like this. (To answer your comment)


问:
Best way to inherit from User table (SQLAlchemy & UserMixin)
I have a SQLALchemy table:

```<code>class User(db.Model, UserMixin):
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password_hash = db.Column(db.String(40), nullable=False)
</code>```

But I want users to be able login and register using either by creating a new account with username and password, or using a social media account (google/twitter/vk.com). My idea is to have a base User table that will have abstract methods like get_name() that will have to be defined in the derived tables for each social media.

Pseudocode for this:

Base user

```<code>class User(db.Model, UserMixin):
    user_id = db.Column(db.Integer, primary_key=True)

    # Overridden method from UserMixin
    def get_id(self):
        return self.user_id

    def get_name(self): raise NotImplementedError
</code>```

Google user

```<code>class GoogleUser(User):

    first_name = db.Columnn(db.String(40), nullable=False)
    last_name = db.Columnn(db.String(40), nullable=False)

    def get_name(self):
        return '{} {}'.format(self.first_name, self.last_name)

</code>```

E-mail user

```<code>class EmailUser(User):
    username = db.Column(db.String(100), nullable=False, unique=True)
    password_hash = db.Column(db.String(40), nullable=False)

    def get_name(self):
        return self.username

</code>```

The question is what is the best way to implement it with SQLAlchemy & UserMixin?
Thanks for any help in advance.

答:
What I usually do is create a User model with all the information that is needed by the application e.g.

```<code>class User(db.Model, UserMixin):
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password_hash = db.Column(db.String(40), nullable=True)
</code>```

Then for third party services authentication, I create a table which stores token and other relevant data regarding that service that the application requirese.g.

```<code>class GoogleUser(db.Model):

    first_name = db.Column(db.String(40), nullable=False)
    last_name = db.Column(db.String(40), nullable=False)
    google_token = db.Column(db.String(200), nullable=False)
</code>```

I connect this new table to the User model via foreign key:

```<code>google_user_id = db.Column(db.Integer, db.ForeignKey("google_user.id"))
</code>```

This way the user can easily connect their third party accounts and have an account on your application.

Facebook Login's documentation also recommends this

Hope it clears things up!

Body:
I have a SQLALchemy table:

class User(db.Model, UserMixin):
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password_hash = db.Column(db.String(40), nullable=False)

But I want users to be able login and register using either by creating a new account with username and password, or using a social media account (google/twitter/vk.com). My idea is to have a base User table that will have abstract methods like get_name() that will have to be defined in the derived tables for each social media.

Pseudocode for this:

Base user

class User(db.Model, UserMixin):
    user_id = db.Column(db.Integer, primary_key=True)

    # Overridden method from UserMixin
    def get_id(self):
        return self.user_id

    def get_name(self): raise NotImplementedError

Google user

class GoogleUser(User):

    first_name = db.Columnn(db.String(40), nullable=False)
    last_name = db.Columnn(db.String(40), nullable=False)

    def get_name(self):
        return '{} {}'.format(self.first_name, self.last_name)

E-mail user

class EmailUser(User):
    username = db.Column(db.String(100), nullable=False, unique=True)
    password_hash = db.Column(db.String(40), nullable=False)

    def get_name(self):
        return self.username

The question is what is the best way to implement it with SQLAlchemy & UserMixin?
Thanks for any help in advance.

Body:
What I usually do is create a User model with all the information that is needed by the application e.g.

class User(db.Model, UserMixin):
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password_hash = db.Column(db.String(40), nullable=True)

Then for third party services authentication, I create a table which stores token and other relevant data regarding that service that the application requirese.g.

class GoogleUser(db.Model):

    first_name = db.Column(db.String(40), nullable=False)
    last_name = db.Column(db.String(40), nullable=False)
    google_token = db.Column(db.String(200), nullable=False)

I connect this new table to the User model via foreign key:

google_user_id = db.Column(db.Integer, db.ForeignKey("google_user.id"))

This way the user can easily connect their third party accounts and have an account on your application.

Facebook Login's documentation also recommends this

Hope it clears things up!


问:
Which technologies/concepts do you suggest I learn before creating an iPhone game?
Sorry if this is a broad question, but other than Objective-C, Cocoa, and OpenGL ES, what technologies or concepts would you suggest I read up on before writing a game for the iPhone?  I'm a beginning game developer and need all the help I can get :)</p>

答:
Quite frankly, I have found that I never know what I need to know until I actually get my hands dirty.  That's why I suggested here that someone looking to jump into designing a 3-D iPhone game start with some simpler, targeted projects.  These targeted projects can teach you core concepts as you put them to practical use.  OpenGL seemed like this impossible-to-understand black box until I made myself perform some simple tasks with it.  In a few weeks, I had an application based on it.

In college, I would spend weeks trying to understand the theory behind an aspect of thermodynamics, but then I would see one practical application for it and the whole thing would fall into place.  Since then, I've focused on finding specific applications for concepts before spending too much time with the pure theory behind them.

OwnerDisplayName: DevFunGuy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Brad Larson


问:
git central repository and Team
I have been playing around with GIT on my local computer.

As I have gain a bit of knowledge using GIT like add, commit, merge, branch, checkout, status.

I still have more to learn but im confuse one thing.. how does git handle team?

For example:

Developer A computer

Developer B computer

Developer C computer

Central repository (Server)

All Developers working on the same project.

From what I understood (correct me if im wrong).. A ,B and C developers push their branch (master?) to central repository via SSH remote.

But on the central repository, how do I get information or which files (or branch?) that has been pushed from the developers... What would it look like on the central repository?

On the central repository, how would handle merges developers work?

Thanks.

答: Take look at the Pro Git book chapter 5 - it should answer all your questions about Git workflow.</p>

Title: git central repository and Team


问:
remotely determine using ssh IF a machine needs to be rebooted
There are plenty of examples of HOW to reboot a linux machine via SSH. However, in my case I want to check IF a linux machine needs to be rebooted via SSH. I have an agent that checks a machine for various metrics and reports that back to a central alarm console. I want to add the ability to check if a machine requires a reboot since some of them have security updates automatically installing.

I don't want to have to enable something on each machine as I prefer to run one script from one location preferably with a single command to check remotely.

EDIT: To clarify, I was looking for a file on a machine that would indicate whether a machine requires a reboot. I then wanted to check for the existence of that file (or something else) remotely using SSH where I am already doing other checks on a group of machines on a nightly basis. I didn't necessarily want to trigger a reboot if it was determined a reboot is required.

The answer I was looking for is below that's referencing /var/run/reboot-required which lead me to to this link.

答:
There are plenty of examples of HOW to reboot a linux machine via SSH.

Since you're logged into that machine through SSH then the way to reboot is the same. restart -r now would restart that machine immediately.

I want to check IF a linux machine needs to be rebooted via SSH.

In that case you could check if your conditions are met in a bash script like,

```<code>if [ yourCondition ]; then
    restart -r now
fi
</code>```

Body:
There are plenty of examples of HOW to reboot a linux machine via SSH.

Since you're logged into that machine through SSH then the way to reboot is the same. restart -r now would restart that machine immediately.

I want to check IF a linux machine needs to be rebooted via SSH.

In that case you could check if your conditions are met in a bash script like,

if [ yourCondition ]; then
    restart -r now
fi


答:
This is how I wwas able to apply Yoben's solution to every tab in the xlsx file, append them together and write the full table to a .csv:</p>

```<code>sheets_dict = pd.read_excel(r'file.xlsx', sheet_name=None)

full_table = pd.DataFrame()
for name, sheet in sheets_dict.items():
    sheet['sheet'] = name
    sheet = sheet.melt(['City','State'])
    sheet = sheet.join(sheet.variable.str.split(',' , expand=True))
    full_table = full_table.append(sheet)

full_table.reset_index(inplace=True, drop=True)

full_table.to_csv('Full Table.csv')
</code>```

Title: Pandas - Pivot and Rearrange Table With Multiple Labels in Same Header

Body:
I have an xlsx file with tabs for multiple years of data. Each tab contains a table with many columns and the table is structured like this:

+-----------+-------+-------------------------+----------------------+
|   City    | State | Number of Drivers, 2019 | Number of Cars, 2019 |
+-----------+-------+-------------------------+----------------------+
| LA        | CA    |                     123 |                 10.0 |
| San Diego | CA    |                     456 |                 2345 |
+-----------+-------+-------------------------+----------------------+

I would like to rearrange the table to look like this, and do it for each tab in the xlsx:

+-----------+-------+------+-------------------+---------------+
|   City    | State | Year |   Measure Name    | Measure Value |
+-----------+-------+------+-------------------+---------------+
| LA        | CA    | 2019 | Number of Drivers |           123 |
| San Diego | CA    | 2019 | Number of Drivers |           456 |
| LA        | CA    | 2019 | Number of Cars    |            10 |
| San Diego | CA    | 2019 | Number of Cars    |          2345 |
+-----------+-------+------+-------------------+---------------+

There are a lot of moving pieces to this and has been a little tricky to get the final formatting correct.

Body:
This is how I wwas able to apply Yoben's solution to every tab in the xlsx file, append them together and write the full table to a .csv:

sheets_dict = pd.read_excel(r'file.xlsx', sheet_name=None)

full_table = pd.DataFrame()
for name, sheet in sheets_dict.items():
    sheet['sheet'] = name
    sheet = sheet.melt(['City','State'])
    sheet = sheet.join(sheet.variable.str.split(',' , expand=True))
    full_table = full_table.append(sheet)

full_table.reset_index(inplace=True, drop=True)

full_table.to_csv('Full Table.csv')


问:
Laravel LeftJoin Multiple queries with similer name
I need to show role name(roles table) in admin list(admins table). I work with leftJoin query:

```<code>   $data = Admin::select('admins.*', 'roles.name')
        ->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'admins.id')
        ->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
        ->get();
</code>```

In Action print_r($data) I see This output:

```<code>(
[id] => 1
[name] => administrator
[email] => m@m.com
[password] => $2y$10$7/HMHGIPIJ6FiNBLy.BynurEhcsrbWkbc4wFREN9qjAFGNqSdaFTS
[remember_token] =>
[created_at] => 2020-02-11 10:46:45
[updated_at] => 2020-02-11 10:46:45
[sex] =>
[dob] =>
[mobile] =>
[phone] =>
[address] =>
[street] =>
[city] =>
[district] =>
[state] =>
[country] =>
[photo] =>
[web] =>
[status] => New
[upload_folder] =>
[deleted_at] =>
)
</code>```

This Work But I can't See admin name in list! In Output roles name replace with admin name.([name] => administrator).

How do can i fix this problem and show all value from admins table + name of roles table?!

答:
You can alias your roles.name as below

Change

```<code>$data = Admin::select('admins.*', 'roles.name')
</code>```

to

```<code>$data = Admin::select('admins.*', 'roles.name as RoleName')
</code>```

Body:
I need to show role name(roles table) in admin list(admins table). I work with leftJoin query:

   $data = Admin::select('admins.*', 'roles.name')
        ->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'admins.id')
        ->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
        ->get();

In Action print_r($data) I see This output:

(
[id] => 1
[name] => administrator
[email] => m@m.com
[password] => $2y$10$7/HMHGIPIJ6FiNBLy.BynurEhcsrbWkbc4wFREN9qjAFGNqSdaFTS
[remember_token] =>
[created_at] => 2020-02-11 10:46:45
[updated_at] => 2020-02-11 10:46:45
[sex] =>
[dob] =>
[mobile] =>
[phone] =>
[address] =>
[street] =>
[city] =>
[district] =>
[state] =>
[country] =>
[photo] =>
[web] =>
[status] => New
[upload_folder] =>
[deleted_at] =>
)

This Work But I can't See admin name in list! In Output roles name replace with admin name.([name] => administrator).

How do can i fix this problem and show all value from admins table + name of roles table?!

Body:
You can alias your roles.name as below

Change

$data = Admin::select('admins.*', 'roles.name')

to

$data = Admin::select('admins.*', 'roles.name as RoleName')


问:
Shiro FormAuthenticationFilter basics question
I can find plenty of examples that show how to configure a URL to use the authc filter, but I cannot find any examples of a simple login page that would be appropriate.  I am using Spring integration to Shiro, but I don't think that has anything to do with my problem.

From reading the documentation, I set up my filter factory like this:

```<code><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="loginUrl" value="/login.jsp" />
        <property name="successUrl" value="/Reports.jsp" />
        <property name="securityManager" ref="securityManager" />
        <property name="filterChainDefinitionMap">
                <map>
                        <entry key="/ws/**" value="authc" />
                        <entry key="/Reports.jsp" value="authc" />
                        <entry key="/**" value="anon" />
                </map>
        </property>
</bean>
</code>```

I'll spare you the entire xml file.  I can tell that it's picking up the right filter, because when I do this:

```<code>> curl -v localhost:8080/factorlab-web/Reports.jsp
</code>```

I get this response:

```<code>< HTTP/1.1 302 Found
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: JSESSIONID=19gdgnmukynb3;Path=/factorlab-web
< Location: http://localhost:8080/factorlab-web/login.jsp;jsessionid=19gdgnmukynb3
< Content-Length: 0
< Server: Jetty(6.1.21)
<
</code>```

So far, so good, right? However, if I submit the username and password, I should get the content of Reports.jsp, right?  I don't.  If I do this:
* curl -v -d "username=demo&password=demo&rememberMe=false" http://localhost:8080/factorlab-web/Reports.jsp

I get the same response as before:

```<code>< HTTP/1.1 302 Found
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: JSESSIONID=qnidg37bqo9f;Path=/factorlab-web
< Location: http://localhost:8080/factorlab-web/login.jsp;jsessionid=qnidg37bqo9f
< Content-Length: 0
< Server: Jetty(6.1.21)
<
</code>```

Clearly I'm confused either about configuration or about how it's supposed to work.  First, can anyone tell me just what I should expect from the second curl command, or why I don't see what I'm expecting?

Second, is there a small sample with a login.jsp (or similar) where I could see what happens when a user:
* Goes explicitly to the login page
* Is automatically directed to the login page (e.g. logging in takes you back to the original attempted page).
* Submits bad username and password from the login page.

答:
Here was my confusion: Don't submit your credentials to anything other than loginUrl.  So, in my case, the form post in my login.jsp should not name a different endpoint.  In the example above, rather than

```<code>curl -v -d "username=demo&password=demo&rememberMe=false" http://localhost:8080/factorlab-web/Reports.jsp
</code>```

I should have tested

```<code>curl -v -d "username=demo&password=demo&rememberMe=false" http://localhost:8080/factorlab-web/login.jsp
</code>```

which will return:

```<code>< HTTP/1.1 302 Found
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: JSESSIONID=1bug6rem2iecb;Path=/factorlab
< Set-Cookie: rememberMe=deleteMe; Path=/factorlab; Expires=Mon, 16-May-2011 00:32:27 GMT
< Location: http://localhost:8080/factorlab/Reports.jsp;jsessionid=1bug6rem2iecb
< Content-Length: 0
< Server: Jetty(6.1.21)
<
</code>```

Body:
I can find plenty of examples that show how to configure a URL to use the authc filter, but I cannot find any examples of a simple login page that would be appropriate.  I am using Spring integration to Shiro, but I don't think that has anything to do with my problem.

From reading the documentation, I set up my filter factory like this:

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="loginUrl" value="/login.jsp" />
        <property name="successUrl" value="/Reports.jsp" />
        <property name="securityManager" ref="securityManager" />
        <property name="filterChainDefinitionMap">
                <map>
                        <entry key="/ws/**" value="authc" />
                        <entry key="/Reports.jsp" value="authc" />
                        <entry key="/**" value="anon" />
                </map>
        </property>
</bean>

I'll spare you the entire xml file.  I can tell that it's picking up the right filter, because when I do this:

> curl -v localhost:8080/factorlab-web/Reports.jsp

I get this response:

< HTTP/1.1 302 Found
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: JSESSIONID=19gdgnmukynb3;Path=/factorlab-web
< Location: http://localhost:8080/factorlab-web/login.jsp;jsessionid=19gdgnmukynb3
< Content-Length: 0
< Server: Jetty(6.1.21)
<

So far, so good, right? However, if I submit the username and password, I should get the content of Reports.jsp, right?  I don't.  If I do this:
* curl -v -d "username=demo&password=demo&rememberMe=false" http://localhost:8080/factorlab-web/Reports.jsp

I get the same response as before:

< HTTP/1.1 302 Found
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: JSESSIONID=qnidg37bqo9f;Path=/factorlab-web
< Location: http://localhost:8080/factorlab-web/login.jsp;jsessionid=qnidg37bqo9f
< Content-Length: 0
< Server: Jetty(6.1.21)
<

Clearly I'm confused either about configuration or about how it's supposed to work.  First, can anyone tell me just what I should expect from the second curl command, or why I don't see what I'm expecting?

Second, is there a small sample with a login.jsp (or similar) where I could see what happens when a user:
* Goes explicitly to the login page
* Is automatically directed to the login page (e.g. logging in takes you back to the original attempted page).
* Submits bad username and password from the login page.

Body:
Here was my confusion: Don't submit your credentials to anything other than loginUrl.  So, in my case, the form post in my login.jsp should not name a different endpoint.  In the example above, rather than

curl -v -d "username=demo&password=demo&rememberMe=false" http://localhost:8080/factorlab-web/Reports.jsp

I should have tested

curl -v -d "username=demo&password=demo&rememberMe=false" http://localhost:8080/factorlab-web/login.jsp

which will return:

< HTTP/1.1 302 Found
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: JSESSIONID=1bug6rem2iecb;Path=/factorlab
< Set-Cookie: rememberMe=deleteMe; Path=/factorlab; Expires=Mon, 16-May-2011 00:32:27 GMT
< Location: http://localhost:8080/factorlab/Reports.jsp;jsessionid=1bug6rem2iecb
< Content-Length: 0
< Server: Jetty(6.1.21)
<


问:
Ternary Operator in java with multiple statements
I want to write multiple statements in Ternary Operator..But dont know how to write.
I want like this,

```<code>public static void main(String[] args) {

    String replaceString,newString;
    Scanner user_input=new Scanner(System.in);
    String input=user_input.next();
    boolean choice=true;
    if(choice==true){
        System.out.println("Enter string to replace");
        replaceString=user_input.next();
        System.out.println("Enter new string");
        newString=user_input.next();
        input.replace(replaceString, newString);
        }
}
</code>```

I want to write the above code in java using ternary operator.Please help

答:
Not entirely sure what you want to do here, or why you want to do it. Also, I will focus on your specific question, and not on your use of Scanner.

Is there something about your sample code's if statement that you don't like?

Why do you want to use a ternary operator?

Bottom line: I think a ternary operator is a bad fit for what you may be trying to do.

The Java ternary operator is a one-line way of writing a simplified if...else... assignment. In your sample code, you have an if but no else - and no obvious assignment - unless you mean to assign the result of this line...

input.replace(replaceString, newString);

...to a String variable. I may be completely wrong about your intention.

The values of a ternary operator (after the ? question-mark and separated by the : colon) can be assigned by methods, as long as the methods return the expected type.

The following uses a ternary operator:

```<code>//
// BAD use of the ternary operator - NOT RECOMMENDED:
//
public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    String input = userInput.next();
    boolean choice = true;
    String replaced = (choice == true) ? whenTrue(userInput, input) : null;
}

private static String whenTrue(Scanner userInput, String input) {
    System.out.println("Enter string to replace");
    String replaceString = userInput.next();
    System.out.println("Enter new string");
    String newString = userInput.next();
    return input.replace(replaceString, newString);
}

</code>```

You would be better off using if, in my opinion.

Body:
I want to write multiple statements in Ternary Operator..But dont know how to write.
I want like this,

public static void main(String[] args) {

    String replaceString,newString;
    Scanner user_input=new Scanner(System.in);
    String input=user_input.next();
    boolean choice=true;
    if(choice==true){
        System.out.println("Enter string to replace");
        replaceString=user_input.next();
        System.out.println("Enter new string");
        newString=user_input.next();
        input.replace(replaceString, newString);
        }
}

I want to write the above code in java using ternary operator.Please help

Body:
Not entirely sure what you want to do here, or why you want to do it. Also, I will focus on your specific question, and not on your use of Scanner.

Is there something about your sample code's if statement that you don't like?

Why do you want to use a ternary operator?

Bottom line: I think a ternary operator is a bad fit for what you may be trying to do.

The Java ternary operator is a one-line way of writing a simplified if...else... assignment. In your sample code, you have an if but no else - and no obvious assignment - unless you mean to assign the result of this line...

input.replace(replaceString, newString);

...to a String variable. I may be completely wrong about your intention.

The values of a ternary operator (after the ? question-mark and separated by the : colon) can be assigned by methods, as long as the methods return the expected type.

The following uses a ternary operator:

//
// BAD use of the ternary operator - NOT RECOMMENDED:
//
public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    String input = userInput.next();
    boolean choice = true;
    String replaced = (choice == true) ? whenTrue(userInput, input) : null;
}

private static String whenTrue(Scanner userInput, String input) {
    System.out.println("Enter string to replace");
    String replaceString = userInput.next();
    System.out.println("Enter new string");
    String newString = userInput.next();
    return input.replace(replaceString, newString);
}

You would be better off using if, in my opinion.


问:
Flutter: FlutterFirebaseInstanceIDService.java uses or overrides a deprecated API
Integrating Firebase messaging service in flutter app and using latest firebase_messaging:^3.0.0 gradle in the flutter but while installing app showing error and I have already reinstall the app many times.

```<code>FlutterFirebaseInstanceIDService.java:21: error: cannot find symbol
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
FlutterFirebaseInstanceIDService.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
</code>```

I have added these line in build.gradle in the android section, still showing the same error. I have taken ref. from here.

```<code>gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xlint:deprecation"
        }
    }
</code>```

How to resolve this error -Xlint:deprecation for flutter.

答:
in your android/app/build.gradle file set the minSdkVersion 21

or

add this implementation "androidx.multidex:multidex:2.0.0" in your dependencies at android/app/build.gradle file

Body:
Integrating Firebase messaging service in flutter app and using latest firebase_messaging:^3.0.0 gradle in the flutter but while installing app showing error and I have already reinstall the app many times.

FlutterFirebaseInstanceIDService.java:21: error: cannot find symbol
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
FlutterFirebaseInstanceIDService.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

I have added these line in build.gradle in the android section, still showing the same error. I have taken ref. from here.

gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xlint:deprecation"
        }
    }

How to resolve this error -Xlint:deprecation for flutter.


问:
"Symbols Tool failed" error while exporting iPhone application with APP Store Profile
After successful Archive, while exporting the Archive to "Save for App Store Deployment", I got the following error:
"Symbol Tool Failed".

During the Export sequence, I have observed, "Binary and Entitlements" section, has two entries.
1) The app store targetAppName (5 Entitlements). with valid Provisioning Profiles.
2) One of the build files FTALDeviceDetailsViewController.o (o Entitlement) with Provisioning Profiles (none)

I bet the second entry here is what is causing the error. Here is the error log:

Any one know how to remove the second entry?

I found another interesting information, regarding this issue:

Unser Archive folder
ActiveLife\ 11-12-14\,\ 3.56\ AM.xcarchive/Products/Applications/ActiveLife.app/

I found following 3 files those are generated in response to second Entitlement file:

```<code>FTALDeviceDetailsViewController.d
FTALDeviceDetailsViewController.dia
FTALDeviceDetailsViewController.o
</code>```

I have manually deleted these 3 files, and now I am able to generate .ipa file.

Now still mystery to me is; why are these files generated and how to fix the root of the problem?

答: Unchecking "Upload your app's symbols to receive symbolicated reports from Apple" option fixes the "Symbol tools failed" error when you Archive the app in Organiser window of Xcode.

Body:
After successful Archive, while exporting the Archive to "Save for App Store Deployment", I got the following error:
"Symbol Tool Failed".

During the Export sequence, I have observed, "Binary and Entitlements" section, has two entries.
1) The app store targetAppName (5 Entitlements). with valid Provisioning Profiles.
2) One of the build files FTALDeviceDetailsViewController.o (o Entitlement) with Provisioning Profiles (none)

I bet the second entry here is what is causing the error. Here is the error log:

Any one know how to remove the second entry?

I found another interesting information, regarding this issue:

Unser Archive folder
ActiveLife\ 11-12-14\,\ 3.56\ AM.xcarchive/Products/Applications/ActiveLife.app/

I found following 3 files those are generated in response to second Entitlement file:

FTALDeviceDetailsViewController.d
FTALDeviceDetailsViewController.dia
FTALDeviceDetailsViewController.o

I have manually deleted these 3 files, and now I am able to generate .ipa file.

Now still mystery to me is; why are these files generated and how to fix the root of the problem?