问:
PHP echo MYSQL Value to URL
I'm attempting to carry the value of a cell to the end of my URL so that I delete the targeted row from a MYSQL table respectively. However, the value in $row['waybill_ID'] does not carry as expected. What can I do to remedy this? I understand that this is slightly drawn out, but I am doing this a part of a 'are you sure' prompt.

```<code><html>
<body>

<div id="myNav" class="overlay">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×
</a>
<div class="overlay-content">
<h2 style="color: white">Are you sure you want to delete this record?</h2>
<h2 style="color: white">This record will no longer exist after
deletion</h2>
<a id="deletePrompt" href="#" target="blank">Delete Record</a>
</div>
</div>

<div class="midA">
    <div class='wrapper'>
        <button class="accordion">Unit(s) and Driver(s)</button>
        <div class="panel">
            <div class='buffer'>
        <?php

        //Unitboard Display
        $issue_ID = $_GET['idx'];
        $mysqli = new mysqli('localhost', 'root', '', 'disolDemo');
        $query = $mysqli->query("SELECT * FROM unitboard WHERE issue_ID = '$issue_ID'") or die($msqli->error);
                    echo"
        <table border= 1px solid white>
        <tr>
            <th>Action</th>
            <th>Waybill_ID</th>
            <th>Driver</th>
            <th>Unit Type</th>
            <th>Move Type</th>
            <th>Route ID</th>
            <th>Tractor Number</th>
            <th>Trailer Number</th>
            <th>Waybill Status</th>
        </tr>
        <tr>";?><?php
        while($row = mysqli_fetch_assoc($query)){?>
        <td>
            <a href="#" onclick="window.open( 'editUnitBoard.php?idx=<?php echo $row['waybill_ID'] ?>', 'name', 'location=no,scrollbars=yes,status=no,toolbar=no,resizable=no' )">edit</a>
            <a href="#" onclick="openNav()">delete</a>
        </td>
         <?php echo"
            <td>{$row['waybill_ID']}</td>
            <td>{$row['driver']}</td>
            <td>{$row['unitType']}</td>
            <td>{$row['moveType']}</td>
            <td>{$row['location_ID']}</td>
            <td>{$row['tractorNum']}</td>
            <td>{$row['trailerNum']}</td>
            <td>{$row['waybillStatus']}</td>
        </tr>";
        }
        echo'<table></table>';

        ?>

            <button style="margin-top: 15px; float: right" class='button' type="button" a href="#" onclick="window.open( 'formNewUnit.php?idx=<?php echo $_GET['idx'] ?>', 'name', 'location=no,scrollbars=yes,status=no,toolbar=no,resizable=no' )">Create New Unit</button>

            <a href="viewRun.php?idx=<?php echo $_GET['idx'] ?>" target="_blank">view</a>

            <div style="clear: both;"></div>
            </div>
        </div>
    </div>
</div>

<script>
function openNav() {
document.getElementById("myNav").style.width = "100%";
document.getElementById("deletePrompt").href="editUnitBoard.php?idx=<?php
echo $row['waybill_ID']; ?>";
return false;
}

function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
</script>

</body>
</html>
</code>```

The result is   editUnitBoard.php?idx=   but    I need something link editUnitBoard.php?id=1234    for example

答:
Hope this helps, select the column, enter the ID and use echo $value[0]['column name'];

Its not SQL Injection proof, I think.

```<code>        $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        $query = mysqli_query($this->db_connection,"SELECT value FROM settings WHERE id='1'");
        $value = mysqli_fetch_all($query,MYSQLI_ASSOC);
</code>```

Title: PHP echo MYSQL Value to URL

Body:
I'm attempting to carry the value of a cell to the end of my URL so that I delete the targeted row from a MYSQL table respectively. However, the value in $row['waybill_ID'] does not carry as expected. What can I do to remedy this? I understand that this is slightly drawn out, but I am doing this a part of a 'are you sure' prompt.

×

Are you sure you want to delete this record?

This record will no longer exist after
deletion

Delete Record

        <button class="accordion">Unit(s) and Driver(s)</button>

        <?php

        //Unitboard Display
        $issue_ID = $_GET['idx'];
        $mysqli = new mysqli('localhost', 'root', '', 'disolDemo');
        $query = $mysqli->query("SELECT * FROM unitboard WHERE issue_ID = '$issue_ID'") or die($msqli->error);
                    echo"

            Action
            Waybill_ID
            Driver
            Unit Type
            Move Type
            Route ID
            Tractor Number
            Trailer Number
            Waybill Status

";?><?php
        while($row = mysqli_fetch_assoc($query)){?>

            <a href="#" onclick="window.open( 'editUnitBoard.php?idx=<?php echo $row['waybill_ID'] ?>', 'name', 'location=no,scrollbars=yes,status=no,toolbar=no,resizable=no' )">edit
            delete

         <?php echo"
            {$row['waybill_ID']}
            {$row['driver']}
            {$row['unitType']}
            {$row['moveType']}
            {$row['location_ID']}
            {$row['tractorNum']}
            {$row['trailerNum']}
            {$row['waybillStatus']}

";
        }
        echo'

';

        ?>

            <button style="margin-top: 15px; float: right" class='button' type="button" a href="#" onclick="window.open( 'formNewUnit.php?idx=<?php echo $_GET['idx'] ?>', 'name', 'location=no,scrollbars=yes,status=no,toolbar=no,resizable=no' )">Create New Unit</button>

            <a href="viewRun.php?idx=<?php echo $_GET['idx'] ?>" target="_blank">view

The result is   editUnitBoard.php?idx=   but    I need something link editUnitBoard.php?id=1234    for example

Body:
Hope this helps, select the column, enter the ID and use echo $value[0]['column name'];

Its not SQL Injection proof, I think.

        $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        $query = mysqli_query($this->db_connection,"SELECT value FROM settings WHERE id='1'");
        $value = mysqli_fetch_all($query,MYSQLI_ASSOC);


来源: stackexchange

问:
How to push json keys and json values into two arrays
I have one json file with following structure:

```<code>{
    "won":3,
    "lost":0,
    "void":0,
    "active":1
}
</code>```

I've been trying to figure out how to make two arrays in javascript that will contain following information:

```<code>var labels = ["won", "lost", "void", "active"];
var data = ["3","0", "0","1"];
</code>```

But I can't my head around how to do it.

答:
You can use:

```<code>var labels = Object.keys(input);
var data = Object.values(input);
</code>```

However you should check the browsers compatibility:

Object.keys
Object.values

ContentLicense: CC BY-SA 3.0

Body:
I have one json file with following structure:

{
    "won":3,
    "lost":0,
    "void":0,
    "active":1
}

I've been trying to figure out how to make two arrays in javascript that will contain following information:

var labels = ["won", "lost", "void", "active"];
var data = ["3","0", "0","1"];

But I can't my head around how to do it.

Body:
You can use:

var labels = Object.keys(input);
var data = Object.values(input);

However you should check the browsers compatibility:

Object.keys
Object.values


问:
Recyclerview shows wrong data
output shows only last item of list
i.e,
16:15-16:30
16:15-16:30
where as it should show
16:00-16:15
16:15-16:30

json output

```<code> {
    "slots": [{
        "1": {
            "slot": "16:00-16:15",
            "value": "1",
            "ar_index": "1"
        },
        "2": {
            "slot": "16:15-16:30",
            "value": "2",
            "ar_index": "2"
        }
    }]
 }
</code>```

Here is the postexecute code that im using to fetch json output and setting it in recyclerview using adapter
Im fetching these two slots and displaying in recyclerview but im geting only the last time of the list. not able to understand the issue with the code

```<code>@Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataBook> data=new ArrayList<>();

            pdLoading.dismiss();
            try {
                    JSONObject jsonObject = new JSONObject(result);
                    System.out.println("jsonObject_1 = "+jsonObject);

                    if(jsonObject != null){
                        JSONArray jsonArray = jsonObject.getJSONArray("slots");
                        System.out.println("jsonArray_2 = "+jsonArray);

                        if(jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                System.out.println("jsonArray.length() = "+jsonArray.length());
                                System.out.println("i_value = "+i);

                                JSONObject elem = jsonArray.getJSONObject(i);
                                System.out.println("elem = " + elem);

                                for (int j = 1; j <= elem.length(); j++) {
                                    System.out.println("elem.length() = "+elem.length());
                                    System.out.println("j_value = "+j);

                                    JSONObject elem1 = elem.getJSONObject(String.valueOf(j));
                                    System.out.println("elem1 = " + elem1);
                                    DataBook fishData = new DataBook();

                                    if (elem1 != null) {
                                        fishData.fishName = elem1.getString("slot");
                                        System.out.println("fishData.fishName = " + fishData.fishName);
                                    }
                                    data.add(fishData);
                                }
                            }
                        }
                    }
// Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(R.id.rc_slotsList);
                mAdapter = new AdapterFish(BookActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(BookActivity.this));

            } catch (JSONException e) {
                Toast.makeText(BookActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }
        }
</code>```

This is my Adapter class were i am setting the result

```<code>public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataBook> data= Collections.emptyList();
    DataBook current;
    int currentPos=0;

    // create constructor to innitilize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataBook> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when viewholder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.book_container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        current = data.get(position);

        myHolder.textFishName.setText(current.fishName);
        System.out.println("holder_current.fishName"+current.fishName);

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyHolder extends RecyclerView.ViewHolder{

        TextView textFishName;
        ImageView ivFish;
        TextView textSize;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textFishName= (TextView) itemView.findViewById(R.id.textFishName);
        }

    }

}
</code>```

答:
```<code>public AdapterFish(Context context, List<DataBook> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
      system.out.println(""+data.size());
//check how much data that you have got

    }
@Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and
        assign values from list
        MyHolder myHolder= (MyHolder) holder;
        current = data.get(position-1);

        myHolder.textFishName.setText(current.fishName);
        System.out.println("holder_current.fishName"+current.fishName);

    }
</code>```

Title: Recyclerview shows wrong data

Body:
output shows only last item of list
i.e,
16:15-16:30
16:15-16:30
where as it should show
16:00-16:15
16:15-16:30

json output

 {
    "slots": [{
        "1": {
            "slot": "16:00-16:15",
            "value": "1",
            "ar_index": "1"
        },
        "2": {
            "slot": "16:15-16:30",
            "value": "2",
            "ar_index": "2"
        }
    }]
 }

Here is the postexecute code that im using to fetch json output and setting it in recyclerview using adapter
Im fetching these two slots and displaying in recyclerview but im geting only the last time of the list. not able to understand the issue with the code

@Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataBook> data=new ArrayList<>();

            pdLoading.dismiss();
            try {
                    JSONObject jsonObject = new JSONObject(result);
                    System.out.println("jsonObject_1 = "+jsonObject);

                    if(jsonObject != null){
                        JSONArray jsonArray = jsonObject.getJSONArray("slots");
                        System.out.println("jsonArray_2 = "+jsonArray);

                        if(jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                System.out.println("jsonArray.length() = "+jsonArray.length());
                                System.out.println("i_value = "+i);

                                JSONObject elem = jsonArray.getJSONObject(i);
                                System.out.println("elem = " + elem);

                                for (int j = 1; j <= elem.length(); j++) {
                                    System.out.println("elem.length() = "+elem.length());
                                    System.out.println("j_value = "+j);

                                    JSONObject elem1 = elem.getJSONObject(String.valueOf(j));
                                    System.out.println("elem1 = " + elem1);
                                    DataBook fishData = new DataBook();

                                    if (elem1 != null) {
                                        fishData.fishName = elem1.getString("slot");
                                        System.out.println("fishData.fishName = " + fishData.fishName);
                                    }
                                    data.add(fishData);
                                }
                            }
                        }
                    }
// Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(R.id.rc_slotsList);
                mAdapter = new AdapterFish(BookActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(BookActivity.this));

            } catch (JSONException e) {
                Toast.makeText(BookActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }
        }

This is my Adapter class were i am setting the result

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataBook> data= Collections.emptyList();
    DataBook current;
    int currentPos=0;

    // create constructor to innitilize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataBook> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when viewholder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.book_container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        current = data.get(position);

        myHolder.textFishName.setText(current.fishName);
        System.out.println("holder_current.fishName"+current.fishName);

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyHolder extends RecyclerView.ViewHolder{

        TextView textFishName;
        ImageView ivFish;
        TextView textSize;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textFishName= (TextView) itemView.findViewById(R.id.textFishName);
        }

    }

}


问:
Silverlight Datagrid: Changing cell styles, based on values
I have some data. I want to go through that data and change cells (for example - Background color), if that data meets a certain condition. Somehow, I've not been able to figure it out how to do this seemingly easy thing in Silverlight.</p>

答:
I've generally written custom ValueConverters for each data type being bound that return Visibility, Colour, etc.

This gives a single point where the customisation rules are defined and I've found works very well.

Robin's second link describes writing a custom ValueConverter.

OwnerDisplayName: Mindaugas Mozuras

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mindaugas Mozuras

OwnerDisplayName: Rammesses


问:
Adding textview below each group of items in listview
First of all,I am sorry if my question is meaningless or wrong.

I need to add textview as the footer view to listview ,and that
  footer view should be repeated for particular number of items.

For example,

If I am having 50 items in a list, whenever I am displaying it in listview , the textview should be displayed below the each group of 10 items (That is the textview should separate 10 items).

Can anyone help me please. I don't even know "using footer view to achieve this is right or not". Thanks!

答:
First @override below function in your adapter

```<code> @Override
    public int getItemViewType(int position) {
        if (position == 0) return 1;
        else return 2;
    }
 }
</code>```

After that check returning positions in @onBindViewHolder and manage your data according to that.
Hope this will help you.

Body:
First @override below function in your adapter

 @Override
    public int getItemViewType(int position) {
        if (position == 0) return 1;
        else return 2;
    }
 }

After that check returning positions in @onBindViewHolder and manage your data according to that.
Hope this will help you.


问:
Need to open blob/PDF in IE window
I have the code below in my typescript to call a web api method and retrieve a binary byte array (blob) that is a PDF.  My user requirement is to open PDF in a new window.

```<code>$scope.selectRow = (itemImageNumber: string, printProcessId: string, printXmlId: string) => {
        itemService.GetOutgoingDocument($scope.item.ItemId, itemImageNumber, printProcessId, printXmlId).success((response) => {
            var file = new Blob([response], { type: 'application/pdf' });
            var fileUrl = URL.createObjectURL(file);
            //$scope.outDocContent = $sce.trustAsResourceUrl(fileUrl);
            var win = window.open($sce.trustAsResourceUrl(fileUrl));
            win.focus();
        }).error(() => {
            var message =
                "The document you selected can’t be displayed at this time. Please call Customer Service at xxx-xxx-xxxx for assistance.";
            $rootScope.$broadcast("app-message", {
                type : "danger",
                message : message
            });
        });
    }
</code>```

This code works fine in Chrome.  The document opens as expected.  IE however asks "Do you want to allow this website to open an app on your computer?" and when allowed, tell me "No apps are installed to open this kind of link (blob)".

Any ideas on how to open this in a new tab or save the blob as a file as a last resort?

答:
The reason why it works in Chrome and other normal browsers: they have pdf previewer installed inside of them.

The lease why it does not work in IE: since in architecture if IE there should be some PDF reading program installed on operating system; for instance, if you have Adobe Acrobat installed, you will open it without problems.

I can recommend you to use: pdf.js/.

Title: Need to open blob/PDF in IE window

Body:
I have the code below in my typescript to call a web api method and retrieve a binary byte array (blob) that is a PDF.  My user requirement is to open PDF in a new window.

$scope.selectRow = (itemImageNumber: string, printProcessId: string, printXmlId: string) => {
        itemService.GetOutgoingDocument($scope.item.ItemId, itemImageNumber, printProcessId, printXmlId).success((response) => {
            var file = new Blob([response], { type: 'application/pdf' });
            var fileUrl = URL.createObjectURL(file);
            //$scope.outDocContent = $sce.trustAsResourceUrl(fileUrl);
            var win = window.open($sce.trustAsResourceUrl(fileUrl));
            win.focus();
        }).error(() => {
            var message =
                "The document you selected can’t be displayed at this time. Please call Customer Service at xxx-xxx-xxxx for assistance.";
            $rootScope.$broadcast("app-message", {
                type : "danger",
                message : message
            });
        });
    }

This code works fine in Chrome.  The document opens as expected.  IE however asks "Do you want to allow this website to open an app on your computer?" and when allowed, tell me "No apps are installed to open this kind of link (blob)".

Any ideas on how to open this in a new tab or save the blob as a file as a last resort?


答:
You can do this too

var mydata = {
    "won":3,
    "lost":0,
    "void":0,
    "active":1
};

var first = [],
    second = [];

for (var property in mydata) {

   if ( ! mydata.hasOwnProperty(property)) {
      continue;
   }

   first.push(property);
   second.push(mydata[property]);

}

console.log(first);
console.log(second);```

Title: How to push json keys and json values into two arrays


问:
How to enable/disable Autocomplete component of Angular Material based on Angular2?
I'm not able to enable/disable the autocomplete textfield component dynamically or otherwise.

I want the component to be disabled by default. And later on some user activity, like on click of a button this should enable the component.

I tried the following code but didnt work:

```<code>export class MyComponent {
  // this DIDN'T WORK
  opts:object={value: "", disabled: true};
  ctrl= new FormControl(this.opts);

  ngDoCheck(){
    // this DIDN'T WORK
    // this could be ngOnChange, ngOnInit or button click event
    if(this.IsTextBoxEnabled){
      this.ctrl.enable();
    }else{
      this.ctrl.disable();
    }
  }
}
</code>```

How to do this in Angular Material Autocomplete component?

UPDATE:

Similar issue on SO was also left unanswered. To which I responded with my answer.

答:
I got this working by doing this. </p>

```<code><input [attr.disabled]="IsTextBoxDisabled?'true':null">
</code>```

<p>Apparently I found this here.  </p>

Body:
I'm not able to enable/disable the autocomplete textfield component dynamically or otherwise.

I want the component to be disabled by default. And later on some user activity, like on click of a button this should enable the component.

I tried the following code but didnt work:

export class MyComponent {
  // this DIDN'T WORK
  opts:object={value: "", disabled: true};
  ctrl= new FormControl(this.opts);

  ngDoCheck(){
    // this DIDN'T WORK
    // this could be ngOnChange, ngOnInit or button click event
    if(this.IsTextBoxEnabled){
      this.ctrl.enable();
    }else{
      this.ctrl.disable();
    }
  }
}

How to do this in Angular Material Autocomplete component?

UPDATE:

Similar issue on SO was also left unanswered. To which I responded with my answer.

Body:
I got this working by doing this.

<input [attr.disabled]="IsTextBoxDisabled?'true':null">

Apparently I found this here.


问:
How can I make a star rating in a canvas?
I've got a html page generated with xslt which lists a few made-up restaurants, and I've been trying to add a star-rating to them. I've managed to get it working as a separate piece of code, in browser and in the w3schools code editor, but I can't get it to display in the main page.

There have been similar questions asked before, and I've tried the suggestions in the answers to those (moving the script to an external .js file, putting some unused html tags in the page so the script refers to permanent html instead of dynamically generated) but they haven't worked.

A few code snippets to show what I'm trying to do (a lot of code omitted to keep it concise):

xml:

```<code><restaurants>
...
<restaurant>
    <name></name>
    <rating></rating>
</restaurant>
...
</restaurants>
</code>```

xsl stylesheet:

```<code><body>
    <h1>Restaurants List</h1>
    <xsl:for-each select="restaurants/restaurant">
        <canvas id="rating" width="181px" height="28px">
            <xsl:value-of select="rating"/>
        </canvas>
            Rating: <xsl:value-of select="rating"/>/5
            <hr/>
    </xsl:for-each>

    <img src="images/star.png" id="star" width="29px">
</body>
</code>```

javaScript (between
```

It also worked in JSFiddle, but only if it was all pasted into the html field; if it was separated into html and javaScript it stopped working (I could be misusing the fiddle, I'm not sure):
https://jsfiddle.net/pqzqbejz/2/
vs.
https://jsfiddle.net/pqzqbejz/3/

Side note: as mentioned, the code works in the w3schools' editor, including the xml/xslt editor, however when implemented the stars only appear next to the first restaurant in the list. Assuming the main issue is fixed, any further ideas on how to get it to show up for all of them? I've tried a, xsl:for-each loop, and putting the function call in the onload in each canvas hoping it would be called each time a canvas was created, but I suspect the problem is the function uses element IDs, and I can't have multiple canvases that share an id. Either way, this is less important to me than the main issue, but any and all help is appreciated.

答:
If you give all your canvas elements a class name, you can then use document.getElementsByClassName to get them all, and then you can iterate over them to draw them one at a time

```<code>function draw()
{
  var cs = document.getElementsByClassName("myCanvas");
  for (var i = 0; i < cs.length; i++)
  {
    drawCanvas(cs[i]);
   }
}

function drawCanvas(c)
{
  var ctx = c.getContext("2d");
  var img = document.getElementById("star")
  var pat = ctx.createPattern(img, 'repeat-x');
  var r = c.innerHTML * 29
  ctx.rect(0, 0, r, 28);
  ctx.fillStyle = pat;
  ctx.fill();
}
</code>```

Then, your XSLT would look like this

```<code><body onload="draw()">
    <h1>Restaurants List</h1>
    <xsl:for-each select="restaurants/restaurant">
        <canvas id="rating{position()}" width="181px" height="28px" class="myCanvas">
            <xsl:value-of select="rating"/>
        </canvas>
            Rating: <xsl:value-of select="rating"/>/5
            <hr/>
    </xsl:for-each>

    <img src="https://i.imgur.com/POxaCQd.png" id="star" width="29px" style="display:none" />
</body>
</code>```

See an example of the transformation at http://xsltransform.net/gVhD8S4

Or, if you want, see the final result at jsfiddle at https://jsfiddle.net/pqzqbejz/5/

Body:
I've got a html page generated with xslt which lists a few made-up restaurants, and I've been trying to add a star-rating to them. I've managed to get it working as a separate piece of code, in browser and in the w3schools code editor, but I can't get it to display in the main page.

There have been similar questions asked before, and I've tried the suggestions in the answers to those (moving the script to an external .js file, putting some unused html tags in the page so the script refers to permanent html instead of dynamically generated) but they haven't worked.

A few code snippets to show what I'm trying to do (a lot of code omitted to keep it concise):

xml:

<restaurants>
...
<restaurant>
    <name></name>
    <rating></rating>
</restaurant>
...
</restaurants>

xsl stylesheet:

Restaurants List

    <xsl:for-each select="restaurants/restaurant">
        <canvas id="rating" width="181px" height="28px">
            <xsl:value-of select="rating"/>
        </canvas>
            Rating: <xsl:value-of select="rating"/>/5

    </xsl:for-each>

javaScript (between

It also worked in JSFiddle, but only if it was all pasted into the html field; if it was separated into html and javaScript it stopped working (I could be misusing the fiddle, I'm not sure):
https://jsfiddle.net/pqzqbejz/2/
vs.
https://jsfiddle.net/pqzqbejz/3/

Side note: as mentioned, the code works in the w3schools' editor, including the xml/xslt editor, however when implemented the stars only appear next to the first restaurant in the list. Assuming the main issue is fixed, any further ideas on how to get it to show up for all of them? I've tried a, xsl:for-each loop, and putting the function call in the onload in each canvas hoping it would be called each time a canvas was created, but I suspect the problem is the function uses element IDs, and I can't have multiple canvases that share an id. Either way, this is less important to me than the main issue, but any and all help is appreciated.

Body:
If you give all your canvas elements a class name, you can then use document.getElementsByClassName to get them all, and then you can iterate over them to draw them one at a time

function draw()
{
  var cs = document.getElementsByClassName("myCanvas");
  for (var i = 0; i < cs.length; i++)
  {
    drawCanvas(cs[i]);
   }
}

function drawCanvas(c)
{
  var ctx = c.getContext("2d");
  var img = document.getElementById("star")
  var pat = ctx.createPattern(img, 'repeat-x');
  var r = c.innerHTML * 29
  ctx.rect(0, 0, r, 28);
  ctx.fillStyle = pat;
  ctx.fill();
}

Then, your XSLT would look like this

<body onload="draw()">
    <h1>Restaurants List</h1>
    <xsl:for-each select="restaurants/restaurant">
        <canvas id="rating{position()}" width="181px" height="28px" class="myCanvas">
            <xsl:value-of select="rating"/>
        </canvas>
            Rating: <xsl:value-of select="rating"/>/5
            <hr/>
    </xsl:for-each>

    <img src="https://i.imgur.com/POxaCQd.png" id="star" width="29px" style="display:none" />
</body>

See an example of the transformation at http://xsltransform.net/gVhD8S4

Or, if you want, see the final result at jsfiddle at https://jsfiddle.net/pqzqbejz/5/


问:
jQuery animate() showing error of $(...).animate is not a function
```<code><!DOCTYPE html>
<html>
<head>
  <title>Alive Time</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="style.css">
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
  <script src="code.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
</head>
  <body>
    <i class="fa fa-cog" style="font-size:100px"></i>
    <i class="fa fa-arrow-right" style="font-size:100px"></i>

  </body>

</html>
----------------------------------------------------------------------------
.fa-cog{
    margin: 10% 50%;
    color: red;
    /*-moz-transition: all 0.5s linear;
    -webkit-transition: all 0.5s linear;
    transition: all 0.5s linear;*/
}

.down {
       -moz-transform:rotate(180deg);
    -webkit-transform:rotate(180deg);
    transform:rotate(180deg);
}
--------------------------------------------------------------------------------------------------------------
$(document).ready(function(){

   $(".fa-cog").on('mouseenter',function(){
 $(this).animate({rotate:180},{
  step:function(now,fx){

    /*$(this).css({' -moz-transform':'rotate('+now+'deg)',
    '-webkit-transform':'rotate('+now+'deg)',
    'transform':'rotate('+now+'deg)'});*/

    $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
  },duration:'slow'},'linear');
});
});
</code>```

Guys I am trying to use specifically animate() method of jquery to rotate a cog. I know I can make a class use some transition,transform and then add or remove that class. But I want to use animate() up here. Couple of docs on stackoverflow said that we don’t actually have to use a real CSS property, like text-index or border-spacing, but instead you can specify a fake CSS property, like rotation or my-awesome-property or else. It might be a good idea to use something that does not risk becoming an actual CSS property in the future. I tried every thing couldnt find the mistake in my code. Ignore the code which I have commented out.

答:
Problem is in this line:

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
</code>```

You can't use the slim version of the jQuery, in your case, as this version is without animations. Just replace it with this:

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</code>```

Body:
<!DOCTYPE html>

  <title>Alive Time</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="style.css">

----------------------------------------------------------------------------
.fa-cog{
    margin: 10% 50%;
    color: red;
    /*-moz-transition: all 0.5s linear;
    -webkit-transition: all 0.5s linear;
    transition: all 0.5s linear;*/
}

.down {
       -moz-transform:rotate(180deg);
    -webkit-transform:rotate(180deg);
    transform:rotate(180deg);
}
--------------------------------------------------------------------------------------------------------------
$(document).ready(function(){

   $(".fa-cog").on('mouseenter',function(){
 $(this).animate({rotate:180},{
  step:function(now,fx){

    /*$(this).css({' -moz-transform':'rotate('+now+'deg)',
    '-webkit-transform':'rotate('+now+'deg)',
    'transform':'rotate('+now+'deg)'});*/

    $(this).css('-webkit-transform','rotate('+now+'deg)');
      $(this).css('-moz-transform','rotate('+now+'deg)');
      $(this).css('transform','rotate('+now+'deg)');
  },duration:'slow'},'linear');
});
});

Guys I am trying to use specifically animate() method of jquery to rotate a cog. I know I can make a class use some transition,transform and then add or remove that class. But I want to use animate() up here. Couple of docs on stackoverflow said that we don’t actually have to use a real CSS property, like text-index or border-spacing, but instead you can specify a fake CSS property, like rotation or my-awesome-property or else. It might be a good idea to use something that does not risk becoming an actual CSS property in the future. I tried every thing couldnt find the mistake in my code. Ignore the code which I have commented out.

Body:
Problem is in this line:

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

You can't use the slim version of the jQuery, in your case, as this version is without animations. Just replace it with this:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>


答:
Try this code

var item_list = {
    "won":3,
    "lost":0,
    "void":0,
    "active":1
};

var labels = [];
var data = [];
for(var item in item_list){
 // console.log(item);
  labels.push(item);
  data.push(item_list[item]);
}

console.log(labels);
console.log(data);```


问:
Combining PHP__autoload with Mollie_API_Autoloader class
Although I know it's not appropriate to ask for ready-to-use code, I do in this case, since I'm failing to find the solution.

Trying to use native PHP __autoload function along with the Mollie_API_Autoloader class:

```<code>class Mollie_API_Autoloader
{
/**
 * @param string $class_name
 */
public static function autoload ($class_name)
{
    if (strpos($class_name, "Mollie_") === 0)
    {
        $file_name = str_replace("_", "/", $class_name);
        $file_name = realpath(dirname(__FILE__) .
"/../../{$file_name}.php");

        if ($file_name !== false)
        {
            require $file_name;
        }
    }
}

/**
 * @return bool
 */
public static function register ()
{
    return spl_autoload_register(array(__CLASS__, "autoload"));
}

/**
 * @return bool
 */
public static function unregister ()
{
    return spl_autoload_unregister(array(__CLASS__, "autoload"));
}
}

Mollie_API_Autoloader::register();
</code>```

The Mollie autoloader class affects the proper functioning of the native PHP __autoload class. Can't seem to combine these. How'd I do this?

答:
__autoload() is deprecated, it was replaced by spl_autoloader_register() many years ago (on PHP 5.1.2).

They cannot work together. __autoload() is limited and all it does, spl_autoloader_register() does better.

Since the class you posted already uses spl_autoload_register(), all you have to do is to call

```<code>Mollie_API_Autoloader::register()
</code>```

somewhere in your boostrap code.

If your existing code uses __autoload() you can easily change it to use spl_autoload_register(). Just rename the __autoload function to something else (let's say old_autoloader) and add spl_autoload_register('old_autoloader'); after its definition.

Check Example #1 on the documentation of spl_autoload_register() for an example.

Body:
Although I know it's not appropriate to ask for ready-to-use code, I do in this case, since I'm failing to find the solution.

Trying to use native PHP __autoload function along with the Mollie_API_Autoloader class:

class Mollie_API_Autoloader
{
/**
 * @param string $class_name
 */
public static function autoload ($class_name)
{
    if (strpos($class_name, "Mollie_") === 0)
    {
        $file_name = str_replace("_", "/", $class_name);
        $file_name = realpath(dirname(__FILE__) .
"/../../{$file_name}.php");

        if ($file_name !== false)
        {
            require $file_name;
        }
    }
}

/**
 * @return bool
 */
public static function register ()
{
    return spl_autoload_register(array(__CLASS__, "autoload"));
}

/**
 * @return bool
 */
public static function unregister ()
{
    return spl_autoload_unregister(array(__CLASS__, "autoload"));
}
}

Mollie_API_Autoloader::register();

The Mollie autoloader class affects the proper functioning of the native PHP __autoload class. Can't seem to combine these. How'd I do this?

Body:
__autoload() is deprecated, it was replaced by spl_autoloader_register() many years ago (on PHP 5.1.2).

They cannot work together. __autoload() is limited and all it does, spl_autoloader_register() does better.

Since the class you posted already uses spl_autoload_register(), all you have to do is to call

Mollie_API_Autoloader::register()

somewhere in your boostrap code.

If your existing code uses __autoload() you can easily change it to use spl_autoload_register(). Just rename the __autoload function to something else (let's say old_autoloader) and add spl_autoload_register('old_autoloader'); after its definition.

Check Example #1 on the documentation of spl_autoload_register() for an example.


问:
App won't start for button-onclick code
I make a simple app which has 7 activities , 2 high quality background images [I created drawable-xxhdpi folder and paste all background images there all background images there including button images]

Also I created assets folder folder as I want to show HTML file on button click

Problem - when I am running the app the app is automatically crashing. the app won't  start. after removing the button-onclick code I try again and the app is working ,but cannot go to another activity.

I think the problem is happening for button onclick-code .I cannot go to go to other activity on button click

Here is  activity main.xml file photo and also the mainactivity.java file photo

Java file photo - https://i.stack.imgur.com/WKmUr.jpg

Xml file photo - https://i.stack.imgur.com/vZiEu.jpg

Also, here is a detailed video regarding this problem check it out

Link - https://drive.google.com/file/d/1KLhK9gQ_ejILN-gwPZ42G_BpfgZKQSKk/view

答:
Have you tried to start another activity using action name of another activity in your mainfest file.

```<code>Intent i = new Intent("Action name defined for second activity in android mainfest under application");
</code>```

Title: App won't start for button-onclick code

Body:
Have you tried to start another activity using action name of another activity in your mainfest file.

Intent i = new Intent("Action name defined for second activity in android mainfest under application");


问:
Steps to extract values from "USER INTERFACE" custom window textbox into my code, WHILE CREATING A SET UP PROJECT?
HI, I have created a setUp project for my windows application.
My Solution has 2 Projects(1st is the Windows application and 2nd project is the setUp project that I added)I want to add custom welcome screens during installtion, so I did the following actions.

1) Created a setUp project and added it to solution having a windows application.

2) Added the primary output of the only windows application (within the solution) to the setUp project.

3) Right click on SetUp project -> VIEW -> USER INTERFACES;  then added a textboxA.

4) Right click on SetUp project -> CUSTOM ACTIONS; This has 4 options Install, UnInstall,Commit,RollBack.

5) Added a new class to the Windows Application project, inherited "Installer" class to this new class. Overridded "Install" method of this class.

6)Right Click on INSTALL option -> ADD CUSTOM ACTION; and the primary output of the windows application was already added, so I didnt add anything.

HERE THE WINDOWS APPLICATION PROJECT HAS BOTH APPLICATION CODE AND ALSO THE OVERRIDDED Install METHOD.
bUT WHEN i TRY TO INSTALL THIS ITS SHOWING SOME ERROR CODE 2869.

Kindly help me with the procedure to extract values from custom textBox into my overridden Install method.

答:
Frankly speaking I have no idea if it is possible to add anything custom to VS setup project.

I had a similar issue and soon lost my patience and migrated to WiX. It integrates with VS very well (you can add WiX XML schema to have your code coloured and Intelisense enabled). With Wix you can do far more custom things than in VS Setup.

Moreover WiX has a great community, loads of examples and last but not least, you can adjust user interface as the VS Setup projects look REALLY ugly.


问:
Redirect direct image urls to image post or attachment page?
New :
I have a wallpaper website and I recently checked the server log of the files accessed and I saw that I am getting lots of traffic on the image files rather than the page of the website.

So I want to do is redirect example.com/sample-image.jpg to example.com/sample-image.html

I am using WordPress CMS and I tried one .htaccess code but it redirects all the images to the homepage of website :(

OLD:

When a user attempts to load an image directly into the browser (for example from Google Images), the browser normally opens just the bare image.

I'm trying to address the following situation:

1) User is browsing Google Images and finds an image. 2) Google Images offers the user to open the website where the image was found or just open the original image. 3) The user chooses the latter, therefore the ball is now on the webserver where the image is hosted. 4) htaccess detects a human operated browser trying to access directly to an image in /uploads/ folder. 5) htaccess redirects the user to single-attachment.php or post in which image include or attached.

答: Images/media it is post type. Try get_permalink($id_of_attachment); If you have url of image you can get id too. Example by get_post_thumbnail_id();


问:
Fetch data from Json
```<code>{"726":
{"id":"726","show":"1","level":"529","author":"1035","title":"a:3:
{s:3:\"geo\";s:24:\"Product name1\";s:3:\"eng\";s:24:\"Product
name2\";s:3:\"rus\";s:24:\"Product name3\";}"
</code>```

I need to get title where language is "geo".
So result should be: "Product name1"

I user code (81 is id):

```<code>$json_url = "http://some/sync.php?
products=1&hash=566gfjfhgkd4343";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE, 512, JSON_UNESCAPED_UNICODE);

$mytest2 = $data['81']['title'];
</code>```

答:
i can't help to much cause your json is not valid, this is example to get value from json

```<code>$json = json_decode($response, true);
foreach($json['name'] as $key => $value)
{
  if(!empty($value['name']))
  {
   $name= $value['name'];
   $name= addslashes($name);
   $name= trim(preg_replace('/\s\s+/', ' ', $name));
  }
  else
  {
    $name= '';
  }
   echo 'name= '.$name.'</br>';
}
</code>```

Before you ask, please post your question clearly, so people can help you better.

Title: Fetch data from Json

Body:
{"726":
{"id":"726","show":"1","level":"529","author":"1035","title":"a:3:
{s:3:\"geo\";s:24:\"Product name1\";s:3:\"eng\";s:24:\"Product
name2\";s:3:\"rus\";s:24:\"Product name3\";}"

I need to get title where language is "geo".
So result should be: "Product name1"

I user code (81 is id):

$json_url = "http://some/sync.php?
products=1&hash=566gfjfhgkd4343";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE, 512, JSON_UNESCAPED_UNICODE);

$mytest2 = $data['81']['title'];

Body:
i can't help to much cause your json is not valid, this is example to get value from json

$json = json_decode($response, true);
foreach($json['name'] as $key => $value)
{
  if(!empty($value['name']))
  {
   $name= $value['name'];
   $name= addslashes($name);
   $name= trim(preg_replace('/\s\s+/', ' ', $name));
  }
  else
  {
    $name= '';
  }
   echo 'name= '.$name.'</br>';
}

Before you ask, please post your question clearly, so people can help you better.


问:
MS Word, Colour change linked to dropdown menu
I have a Word template with options within the header, one of which is the type of document it relates to. I have cytotoxic and monoclonal options to be selected from a drop down menu.

I need to have some identifier colours displayed on the document, Yellow for cytotoxic and Blue for monoclonal. To help with quick recognition for better usability.

Is there a way to alter a shape or text box colour depending on which option is selected?

edit
The template is a work in progress so not 100% sure where the colour will be added, would just like it automated for uniformity as it will be applied to many documents. And worked on by different people.

I'm after an excel conditional formatting type effect where if the drop down shows cytotoxic colour gets applied. It could be a shape, textbox, cell or font, I could work with whichever is possible to be linked.

Thanks for any help!

答:
Please paste the code below in the ThisDocument code sheet of your template and save it as macro enabled, in DOTM or DOCM format.

Add an ActiveX combobox to your template. By default it has the name "ComboBox1". You will find that the code refers to it by this name.

Add a rectangular shape to your template. I made this more like a bar, about 5mm high and across the entire page width. By default, Word will call it "Rectangle 1". Note that the code refers to it by this name.

```<code>Option Explicit

Private Sub Document_Open()
    ' 16 Nov 2017

    Dim iShp As InlineShape
    Dim Shp As Shape
    Dim ShapesCount As Integer

    For Each iShp In ActiveDocument.InlineShapes
        With iShp
            If .Type = wdInlineShapeOLEControlObject Then
                If StrComp(.OLEFormat.Object.Name, "ComboBox1", vbTextCompare) _
                           = 0 Then ShapesCount = ShapesCount + 1
            End If
        End With
    Next iShp

    For Each Shp In ActiveDocument.Shapes
        With Shp
            If .Type = msoAutoShape Then
                If StrComp(.Name, "Rectangle 1", vbTextCompare) _
                           = 0 Then ShapesCount = ShapesCount + 1
            End If
        End With
    Next Shp

   If ShapesCount < 2 Then
        MsgBox "One of the required shapes is missing.", _
               vbInformation, "Corrupted document"
        Exit Sub
    Else
        With ActiveDocument
            With .ComboBox1
                .List = Array("Cycotoxic", "Monoclonic")
                If .ListIndex < 0 Then .ListIndex = 0
            End With
        End With
    End If
End Sub

Private Sub ComboBox1_Change()
    ' 16 Nov 2017
    Shapes("Rectangle 1").Fill.ForeColor = Array(vbYellow, 15773696)(ComboBox1.ListIndex)
End Sub
</code>```

When you open the document the Document_Open event procedure will run (for testing, you can also run it manually). It checks if the two shapes are present - one an Inlineshape, the other a normal shape - and gives an error message if one of them is missing. It will also add the two choices to the Combobox. You will find the names in the code (in case I misspelled them).

Now, when you change the selection the colour of the bar will toggle between yellow and blue.

Statistics: 32 lines of supporting code so that one lone line can do all the work.

The following code will have the rectangle in the header. Unfortunately, it isn't possible to have an ActiveX control in the header, but you might format the ComboBox to have no frame and let the dropdown arrow only appear when you hover the mouse over it so that the selected word appears as part of the document's text, perhaps even its title.

```<code>Option Explicit

Private Sub Document_Open()
    ' 17 Nov 2017

    Dim iShp As InlineShape

    For Each iShp In ActiveDocument.InlineShapes
        With iShp
            If .Type = wdInlineShapeOLEControlObject Then
                If StrComp(.OLEFormat.Object.Name, "ComboBox1", vbTextCompare) = 0 Then
                    With .OLEFormat.Object
                        .List = Array("Cycotoxic", "Monoclonic")
                        If .ListIndex < 0 Then .ListIndex = 0
                    End With
                End If
            End If
        End With
    Next iShp
End Sub

Private Sub ComboBox1_Change()
    ' 17 Nov 2017

    Dim Sect As Object, Story As Object
    Dim Shp As Shape

    With ActiveDocument
        For Each Sect In .Sections
            For Each Story In Sect.Headers
                For Each Shp In Story.Shapes
                    With Shp
                        If .Type = msoAutoShape Then
                            If StrComp(.Name, "Rectangle 1", vbTextCompare) = 0 Then
                                Shap.Fill.ForeColor = Array(vbYellow, 15773696)(ComboBox1.ListIndex)
                            End If
                        End If
                    End With
                Next Shp
            Next Story
        Next Sect
    End With
End Sub
</code>```

Note that this version doesn't inspect the document for the presence of either ComboBox or Rectangle. Instead, if the ComboBox is found its dropdown list is set. If it isn't found nothing will happen. And if there is no ComboBox  to call its change event the colour in the rectangle won't change, especially if it doesn't exist.

Body:
Please paste the code below in the ThisDocument code sheet of your template and save it as macro enabled, in DOTM or DOCM format.

Add an ActiveX combobox to your template. By default it has the name "ComboBox1". You will find that the code refers to it by this name.

Add a rectangular shape to your template. I made this more like a bar, about 5mm high and across the entire page width. By default, Word will call it "Rectangle 1". Note that the code refers to it by this name.

Option Explicit

Private Sub Document_Open()
    ' 16 Nov 2017

    Dim iShp As InlineShape
    Dim Shp As Shape
    Dim ShapesCount As Integer

    For Each iShp In ActiveDocument.InlineShapes
        With iShp
            If .Type = wdInlineShapeOLEControlObject Then
                If StrComp(.OLEFormat.Object.Name, "ComboBox1", vbTextCompare) _
                           = 0 Then ShapesCount = ShapesCount + 1
            End If
        End With
    Next iShp

    For Each Shp In ActiveDocument.Shapes
        With Shp
            If .Type = msoAutoShape Then
                If StrComp(.Name, "Rectangle 1", vbTextCompare) _
                           = 0 Then ShapesCount = ShapesCount + 1
            End If
        End With
    Next Shp

   If ShapesCount < 2 Then
        MsgBox "One of the required shapes is missing.", _
               vbInformation, "Corrupted document"
        Exit Sub
    Else
        With ActiveDocument
            With .ComboBox1
                .List = Array("Cycotoxic", "Monoclonic")
                If .ListIndex < 0 Then .ListIndex = 0
            End With
        End With
    End If
End Sub

Private Sub ComboBox1_Change()
    ' 16 Nov 2017
    Shapes("Rectangle 1").Fill.ForeColor = Array(vbYellow, 15773696)(ComboBox1.ListIndex)
End Sub

When you open the document the Document_Open event procedure will run (for testing, you can also run it manually). It checks if the two shapes are present - one an Inlineshape, the other a normal shape - and gives an error message if one of them is missing. It will also add the two choices to the Combobox. You will find the names in the code (in case I misspelled them).

Now, when you change the selection the colour of the bar will toggle between yellow and blue.

Statistics: 32 lines of supporting code so that one lone line can do all the work.

The following code will have the rectangle in the header. Unfortunately, it isn't possible to have an ActiveX control in the header, but you might format the ComboBox to have no frame and let the dropdown arrow only appear when you hover the mouse over it so that the selected word appears as part of the document's text, perhaps even its title.

Option Explicit

Private Sub Document_Open()
    ' 17 Nov 2017

    Dim iShp As InlineShape

    For Each iShp In ActiveDocument.InlineShapes
        With iShp
            If .Type = wdInlineShapeOLEControlObject Then
                If StrComp(.OLEFormat.Object.Name, "ComboBox1", vbTextCompare) = 0 Then
                    With .OLEFormat.Object
                        .List = Array("Cycotoxic", "Monoclonic")
                        If .ListIndex < 0 Then .ListIndex = 0
                    End With
                End If
            End If
        End With
    Next iShp
End Sub

Private Sub ComboBox1_Change()
    ' 17 Nov 2017

    Dim Sect As Object, Story As Object
    Dim Shp As Shape

    With ActiveDocument
        For Each Sect In .Sections
            For Each Story In Sect.Headers
                For Each Shp In Story.Shapes
                    With Shp
                        If .Type = msoAutoShape Then
                            If StrComp(.Name, "Rectangle 1", vbTextCompare) = 0 Then
                                Shap.Fill.ForeColor = Array(vbYellow, 15773696)(ComboBox1.ListIndex)
                            End If
                        End If
                    End With
                Next Shp
            Next Story
        Next Sect
    End With
End Sub

Note that this version doesn't inspect the document for the presence of either ComboBox or Rectangle. Instead, if the ComboBox is found its dropdown list is set. If it isn't found nothing will happen. And if there is no ComboBox  to call its change event the colour in the rectangle won't change, especially if it doesn't exist.


问:
OpenGL ARGB vs RGB and Texture Compression
I have a rendering context with a color depth of 32-bits. I will be using some alpha blending, but not much; so using 24-bit images for most of the textures I need will greatly reduce the memory requirements. My question is, can I use 24-bit RGB textures with a 32-bit rendering context and expect the same performance as a 32-bit ARGB texture? I understand that the internal format is probably neither to begin with, but the target format of the RC is 32-bit ARGB.

Also, I am planning on using some form of texture compression. The platform will be Windows, exclusively. Which would provide the best compression and widest-compatibility? I am also hoping to use 24-bit compressed textures since I won't be using the alpha bits; but the rendering context will remain 32-bits.

答:
There is no problem at all using any texture format as input textures when rendering to a 32bit render context. The texture formats are either supported by the platform or not, that's about it, if it's supported you can use it without consideration of the format of the render context.

To compress your 24 bits textures, you could take a look at DXT1 texture compression that is supported on all OpenGL implementations on Windows PC. Note that depending on your content, and the compression quality you want to obtain, there are 'tricks' allowing to improve image quality using DXT compressions, alternative color spaces, and shader code for decoding, here is an example.


问:
Eclipse - Scenebuilder not starting with right clicking and "Open with scenebuilder"
I have a JavaFX project with several .fxml files. I used to open those files by right-clicking on them and selecting "Open with SceneBuilder". Probably after some operating system maintenance, SceneBuilder does not start anymore. No error message appears, just nothing happens. I' working under XUbuntu 16.04, same behavior on Eclipse Neon and Eclipse Oxygen, the latter with fresh install.
SceneBuilder path is correctly set under Window -> Preferences -> JavaFX -> SceneBuilder executable.
I tried reinstalling e(fx)clipse, nothing.
Tried to reset SceneBuilder by removing ~/.scenebuilder and ~/.java/.userPrefs/com/oracle/javafx/scenebuilder/.
This happens with SceneBuilder 8.4.1 and 8.3.0 . I'm using the executable jar version of SceneBuilder (scenebuilder-8.4.1-all.jar).
Of course, launching SceneBuilder alone and opening fxml files from the filesystem works.
Does anybody have an idea on how to restore the functionality or at least a way to understand whats happening? Many thanks</p>

答:
Installing the packaged version of SceneBuilder solved the problem.
Downloaded scenebuilder-8.4.1.deb, installed with "sudo apt-get install ./scenebuilder-8.4.1.deb". Then configured Eclipse pointing "Window->Preferences->JavaFX->SceneBuilder executable" to "/opt/SceneBuilder/SceneBuilder".
This also solves the problems related to window maximization/minimization not working properly with SceneBuilder executable jar file.</p>


问:
php compare variable does not work
I have a litte php code which reads out a file which contains y or n or b.
I have echoed the file output and it displays perfectly y. Now if I compare the variable with y it does not accept it and proceeds with else.

```<code>$result = mysqli_query($db, "SELECT ID FROM review WHERE reviewer_ID='$reviewer_ID' AND products_ID='$products_ID'");
            if ($result->num_rows > 0){
            // this person has already reviewed it
            echo "you have already reviewed it<br />";
            echo "<p><a href=\"../page.php?productid=". $F_products_ID ."\">Zurück</a></p>";
    }else{

    // $out= y if its valid and $out= n if its a invalid review
    $out = shell_exec ("/home/script.sh $reviewlink");
    // time for the script to run. needs aprx. 1-2 seconds.
    sleep(2);
    // variables for PHP
    $valid = file_get_contents('/home/script/valid');
    $digits = file_get_contents('/home/script/digits');
    // PHP sends it to the DB if true

        if ($out == 'b' or $valid == 'b'){
        echo "<p>We have an issue right now!</a></p>";
        header('location:issue.php?productid=$F_products_ID');
        } else {
        echo "Review Status from file: $valid <br>";
        echo "Review Status from script: $out <br>";
        echo "Digits in Review: $digits <br><br>";
        if (($out == 'y' or $valid == 'y') and $digits >= $mindigits){
        //do stuff
</code>```

So echoing out and valid displays y and the digits correctly, but comparing them with y (or with mindigits) seems not to work.
PHP thinks y =/y and i dont get it...

答:
Try adding [0] to the variables:

```<code>if ($out[0] == 'y' or $valid[0] == 'y'){ ... }
</code>```

So only the first character is used for the comparing process.

Title: php compare variable does not work

Body:
I have a litte php code which reads out a file which contains y or n or b.
I have echoed the file output and it displays perfectly y. Now if I compare the variable with y it does not accept it and proceeds with else.

$result = mysqli_query($db, "SELECT ID FROM review WHERE reviewer_ID='$reviewer_ID' AND products_ID='$products_ID'");
            if ($result->num_rows > 0){
            // this person has already reviewed it
            echo "you have already reviewed it
";
            echo "
Zurück
";
    }else{

    // $out= y if its valid and $out= n if its a invalid review
    $out = shell_exec ("/home/script.sh $reviewlink");
    // time for the script to run. needs aprx. 1-2 seconds.
    sleep(2);
    // variables for PHP
    $valid = file_get_contents('/home/script/valid');
    $digits = file_get_contents('/home/script/digits');
    // PHP sends it to the DB if true

        if ($out == 'b' or $valid == 'b'){
        echo "
We have an issue right now!
";
        header('location:issue.php?productid=$F_products_ID');
        } else {
        echo "Review Status from file: $valid
";
        echo "Review Status from script: $out
";
        echo "Digits in Review: $digits

";
        if (($out == 'y' or $valid == 'y') and $digits >= $mindigits){
        //do stuff

So echoing out and valid displays y and the digits correctly, but comparing them with y (or with mindigits) seems not to work.
PHP thinks y =/y and i dont get it...

Body:
Try adding [0] to the variables:

if ($out[0] == 'y' or $valid[0] == 'y'){ ... }

So only the first character is used for the comparing process.


问:
Adding enum on model shows error on initializing different class object
I have added enum on RvDate model as:

```<code>class RvDate < ApplicationRecord
 enum status: { Available: 0, Not_Available: 1 }

 # Associations
 belongs_to :rv

 # Validations
 validates_presence_of :start_date
end
</code>```

But when I run Rv.create on rails console, it shows me the following error:

I have not used enum on Rv model and I do not need one. Is there anything I have missed here?

Rv model looks like this:

```<code>class Rv < ApplicationRecord
 has_many :rv_dates, dependent: :destroy
end
</code>```

Schema for rv_dates

```<code>create_table "rv_dates", force: :cascade do |t|
 t.integer  "rv_id"
 t.date     "start_date"
 t.date     "end_date"
 t.boolean  "availability"
 t.float    "price"
 t.text     "notes"
 t.datetime "created_at",   null: false
 t.datetime "updated_at",   null: false
 t.integer  "status"
 t.index ["rv_id"], name: "index_rv_dates_on_rv_id", using: :btree
end
</code>```

答:
Ruby doesn’t have a built-in enum type

Create a constant:

```<code>STATUSES = { available: 0, not_available: 1 }
</code>```

Access:

RvDate::STATUSES[:available]

RvDate::STATUSES[:not_available]

Body:
I have added enum on RvDate model as:

class RvDate < ApplicationRecord
 enum status: { Available: 0, Not_Available: 1 }

 # Associations
 belongs_to :rv

 # Validations
 validates_presence_of :start_date
end

But when I run Rv.create on rails console, it shows me the following error:

I have not used enum on Rv model and I do not need one. Is there anything I have missed here?

Rv model looks like this:

class Rv < ApplicationRecord
 has_many :rv_dates, dependent: :destroy
end

Schema for rv_dates

create_table "rv_dates", force: :cascade do |t|
 t.integer  "rv_id"
 t.date     "start_date"
 t.date     "end_date"
 t.boolean  "availability"
 t.float    "price"
 t.text     "notes"
 t.datetime "created_at",   null: false
 t.datetime "updated_at",   null: false
 t.integer  "status"
 t.index ["rv_id"], name: "index_rv_dates_on_rv_id", using: :btree
end

Body:
Ruby doesn’t have a built-in enum type

Create a constant:

STATUSES = { available: 0, not_available: 1 }

Access:

RvDate::STATUSES[:available]

RvDate::STATUSES[:not_available]


问:
How to store the out put of find command to a array in csh scripting
I want to store each output of find command at each index of a array .

I am using

set arr = find $path -name "*.txt"

  echo $arr

actual output:

  file1.txt file.txt file3.txt

expected output:

file1.txt

file2.txt

file3.txt

答:
Use parenthesis () to assign an array and use backtick to execute the find command :

```<code>set arr = (`find $path -name "*.txt"`)
</code>```

and to see the array elements

```<code>echo ${arr[*]}
</code>```

Body:
Use parenthesis () to assign an array and use backtick to execute the find command :

set arr = (`find $path -name "*.txt"`)

and to see the array elements

echo ${arr[*]}


问:
Conventions for naming class operations?
What conventions do you use for naming class operations? </p>

答:
Naming conventions are a controversial topic, because it's an arbitrary distinction.

The two answers above are good ones. My addition is this:

Your goal is readability. Your code tells a story, albeit a sometimes kind of boring one. Make sure the story is clear.

For extra fun see these links:

http://www.joelonsoftware.com/articles/Wrong.html

http://en.wikipedia.org/wiki/Naming_convention_%28programming%29


问:
Firebase ITEM_NAME not visible in Analytics dashboard
I am trying to see which parts of my app are most used, for this I have added a logEvent like this:

```<code>Bundle bundle= new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "action");
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "screen_a");
FirebaseAnalytics.getInstance(context).logEvent(FirebaseAnalytics.Event,VIEW_ITEM, bundle);
</code>```

The events get logged and I can see in my Dashboard under Events section a view_item entry with the Count, however, when I enter it, I can see the counts, meaning values, but I can't see any values like "screen_a" or "screen_b"...

Since these are not custom events, shouldn't the values be available in the dashboard?

答:
I got the same question as you. By asking email to firebase team, they replied the exact method to watch the log of item_name. Below are the example, I logged an ITEM_NAME "action_getProVersion" with ECOMMERCE_PURCHASE event:

log event in your codes: (You have done this)

Bundle bundle = new Bundle();

//bundle.putString(FirebaseAnalytics.Param.ITEM_ID, itemId);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "action_getProVersion");
//bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.ECOMMERCE_PURCHASE, bundle);

On the firebase event screen, press on the right side,for event "Edit parameter reporting", then add "item_name" and save. (it looks you haven't done this)

After a while, let it log from users event. You will see the events logged with parameter "ITEM_NAME" as the attached screenshot

Body:
I am trying to see which parts of my app are most used, for this I have added a logEvent like this:

Bundle bundle= new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "action");
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "screen_a");
FirebaseAnalytics.getInstance(context).logEvent(FirebaseAnalytics.Event,VIEW_ITEM, bundle);

The events get logged and I can see in my Dashboard under Events section a view_item entry with the Count, however, when I enter it, I can see the counts, meaning values, but I can't see any values like "screen_a" or "screen_b"...

Since these are not custom events, shouldn't the values be available in the dashboard?

ContentLicense: CC BY-SA 4.0


问:
Running into 'Error in eval(predvars, data, env) : object 'Age' not found' while using predict function in logistic regression
```<code>#Logistic Regression
glm.fit <- glm(recent_cannabis_use~.,data = drug_use_train, family = binomial)
summary(glm.fit)

predict(glm.fit, with(drug_use_train, data.frame(Gender = "Male")), type = "response")
</code>```

Trying to find the predicted probability for recent_canabis_use for a male.

答:
You should use predict(glm.fit, newdata = data.frame(Gender = "Male")). Using with in this case is not warranted, since you are not accessing any of the variables in drug_use_train.

Note that this assumes your formula is, upon expansion, recent_cannabis_use ~ Gender. If you have other variable and you want to explore only the effect of Gender, you will need to set (pre-calculate or make up) all other variables to some fixed value (remember how coefficients are interpreted - change in y with one unit change of x, provided everything else stays the same). See for example this post.

Body:
#Logistic Regression
glm.fit <- glm(recent_cannabis_use~.,data = drug_use_train, family = binomial)
summary(glm.fit)

predict(glm.fit, with(drug_use_train, data.frame(Gender = "Male")), type = "response")

Trying to find the predicted probability for recent_canabis_use for a male.


问:
TYPO3 Custom Element colorpicker
I'm new to TYPO3 (first project) and I have some understanding issues of the creation of a custom element with a colorpicker. In this project I already have created a few elements but I only use predetermined fields for the backend input. For the element I need next I need the user to choose a color. I haven't found a fitting existing element. My setup that doesn't work is in the TCA/Overrides/tt_content.php file and looks like this.

```<code>$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Color';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
    'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
        header;Title,
        subheader;Background,
        header_link;Target,
        item_0;Color,
        bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
        ');
</code>```

The item_0 was a try to create a colorpicker but it doesn't seem to work. Do I need something different in a different file? The first few lines I added to define my field. Is there a better way to do this?

All other files in my custom extension work (since all other custom elements work fine). The only difference is, as said, the need of a way to choose a color in the new one.

Just for a clearer look here the other files

setup.txt:

```<code>lib.contentElement {
  templateRootPaths {
    100 = EXT:wostyle/Resources/Private/Template
  }
}
tt_content {
    wo_mitem < lib.contentElement
    wo_mitem {
        templateName = MItem
    }
}
</code>```

tt_content.php

```<code>\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPlugin(
   array(
      'WO_Item (ItemBox, Text only)',
      'wo_mitem',
      'content-image'
   ),
   'CType',
   'wostyle'
);

$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Farbe';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
            'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
            header;Bezeichnung,
            subheader;Chemische Bezeichnung,
            header_link;Zielseite,
            item_0;Farbe,
            bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
            ');
</code>```

typo.ts

```<code>mod.wizards.newContentElement.wizardItems.wo_extra {
   header = WO Elemente
   after = common
  elements {
    wo_mitem {
         iconIdentifier = content-image
         title = WO_Item (ItemBox, Text only)
         description = Ein Produktfeld mit Text
         tt_content_defValues {
            CType = wo_mitem
         }
      }
   }
   show := addToList(wo_mitem)
}
</code>```

MItem.html

```<code><div class="item-text">
    <f:link.typolink parameter="{data.header_link}">
        <div class="item-front">
            <f:if condition="{data.subheader}!=''">
            <f:then>
            <div class="item-bg">
                <f:format.html>{data.subheader}</f:format.html>
            </div>
            </f:then>
            </f:if>
            <div class="item-title">
                <f:format.html>{data.header}</f:format.html>
            </div>
        </div>
        <div class="item-back">
            <f:format.html>{data.bodytext}</f:format.html>
        </div>
    </f:link.typolink>
</div>
<f:debug>{data}</f:debug>
</code>```

EDIT: I use typo3 8.7.8

答:
I did not check your whole code but I have a working color-picker on a field ...
you're close but an error that pops up right away is that your item should be placed under ['columns'] ...

```<code>$GLOBALS['TCA']['tt_content']['columns']['item_0']=array();
</code>```

next you are missing the refference to the wizard !! (you should adopt the annotation with square brackets which shows much more the structure)

this should be stored in Configuration/TCA/Overrides/tt_content.php: (when you override existing fields, otherwise you have a dedicated code for the element)

```<code><?php

/***************
 * Modify the tt_content TCA
 */
$tca = [
    'columns' => [
        'item_0' => [
            'label' => 'Color',
            'config' => [
                'type' => 'input',
                'size' => 10,
                'eval' => 'trim',
                'default' => '#ffffff',
                'wizards' => [
                    'colorChoice' => [
                        'type' => 'colorbox',
                        'title' => 'LLL:EXT:lang/locallang_wizards:colorpicker_title',
                        'module' => [
                            'name' => 'wizard_colorpicker'
                        ],
                        'dim' => '20x20',
                        'JSopenParams' => 'height=600,width=380,status=0,menubar=0,scrollbars=1',
                    ],
                ],
            ],
        ],
    ],
];
$GLOBALS['TCA']['tt_content'] = array_replace_recursive($GLOBALS['TCA']['tt_content'], $tca);
</code>```

Title: TYPO3 Custom Element colorpicker

Body:
I'm new to TYPO3 (first project) and I have some understanding issues of the creation of a custom element with a colorpicker. In this project I already have created a few elements but I only use predetermined fields for the backend input. For the element I need next I need the user to choose a color. I haven't found a fitting existing element. My setup that doesn't work is in the TCA/Overrides/tt_content.php file and looks like this.

$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Color';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
    'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
        header;Title,
        subheader;Background,
        header_link;Target,
        item_0;Color,
        bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
        ');

The item_0 was a try to create a colorpicker but it doesn't seem to work. Do I need something different in a different file? The first few lines I added to define my field. Is there a better way to do this?

All other files in my custom extension work (since all other custom elements work fine). The only difference is, as said, the need of a way to choose a color in the new one.

Just for a clearer look here the other files

setup.txt:

lib.contentElement {
  templateRootPaths {
    100 = EXT:wostyle/Resources/Private/Template
  }
}
tt_content {
    wo_mitem < lib.contentElement
    wo_mitem {
        templateName = MItem
    }
}

tt_content.php

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPlugin(
   array(
      'WO_Item (ItemBox, Text only)',
      'wo_mitem',
      'content-image'
   ),
   'CType',
   'wostyle'
);

$GLOBALS['TCA']['tt_content']['item_0']=array();
$GLOBALS['TCA']['tt_content']['item_0']['label']='Farbe';
$GLOBALS['TCA']['tt_content']['item_0']['config']=array();
$GLOBALS['TCA']['tt_content']['item_0']['config']['type']='input';
$GLOBALS['TCA']['tt_content']['item_0']['config']['renderType']='colorpicker';
$GLOBALS['TCA']['tt_content']['item_0']['config']['size']=10;

$GLOBALS['TCA']['tt_content']['types']['wo_mitem'] = array(
            'showitem' => '--palette--;LLL:EXT:cms/locallang_ttc.xlf:palette.general;general,
            header;Bezeichnung,
            subheader;Chemische Bezeichnung,
            header_link;Zielseite,
            item_0;Farbe,
            bodytext;Text;;richtext:rte_transform[flag=rte_enabled|mode=ts_css]
            ');

typo.ts

mod.wizards.newContentElement.wizardItems.wo_extra {
   header = WO Elemente
   after = common
  elements {
    wo_mitem {
         iconIdentifier = content-image
         title = WO_Item (ItemBox, Text only)
         description = Ein Produktfeld mit Text
         tt_content_defValues {
            CType = wo_mitem
         }
      }
   }
   show := addToList(wo_mitem)
}

MItem.html

    <f:link.typolink parameter="{data.header_link}">

            <f:if condition="{data.subheader}!=''">
            <f:then>

                <f:format.html>{data.subheader}</f:format.html>

            </f:then>
            </f:if>

                <f:format.html>{data.header}</f:format.html>

            <f:format.html>{data.bodytext}</f:format.html>

    </f:link.typolink>

<f:debug>{data}</f:debug>

EDIT: I use typo3 8.7.8

Body:
I did not check your whole code but I have a working color-picker on a field ...
you're close but an error that pops up right away is that your item should be placed under ['columns'] ...

$GLOBALS['TCA']['tt_content']['columns']['item_0']=array();

next you are missing the refference to the wizard !! (you should adopt the annotation with square brackets which shows much more the structure)

this should be stored in Configuration/TCA/Overrides/tt_content.php: (when you override existing fields, otherwise you have a dedicated code for the element)

<?php

/***************
 * Modify the tt_content TCA
 */
$tca = [
    'columns' => [
        'item_0' => [
            'label' => 'Color',
            'config' => [
                'type' => 'input',
                'size' => 10,
                'eval' => 'trim',
                'default' => '#ffffff',
                'wizards' => [
                    'colorChoice' => [
                        'type' => 'colorbox',
                        'title' => 'LLL:EXT:lang/locallang_wizards:colorpicker_title',
                        'module' => [
                            'name' => 'wizard_colorpicker'
                        ],
                        'dim' => '20x20',
                        'JSopenParams' => 'height=600,width=380,status=0,menubar=0,scrollbars=1',
                    ],
                ],
            ],
        ],
    ],
];
$GLOBALS['TCA']['tt_content'] = array_replace_recursive($GLOBALS['TCA']['tt_content'], $tca);


问:
Array Doesn't Push Elements Node.js
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

```<code>    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }
</code>```

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.

答:
@Lepanto is right.
<input type="submit"> will refresh the page and you will lose your state. try this:

<button onclick="addToList" >submit</button>

Title: Array Doesn't Push Elements Node.js

Body:
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.


问:
Making a Calendar with Ionic2
https://thielcole.github.io/ionic2/2017/02/03/Ionic2-Calendar.html
I followed this link and tried exactly what he said but ran into a lot of errors.
I want to make calendar with different color events. I tried https://devdactic.com/ionic-calendar-app/ this and works well but what I want is dot events on calendar with event in different color as first link</p>

答:
Can you change

in calendar.ts

```<code> .no-events-label {
      ..
      color: darkgrey; // change what you want
    }

 .calendar-event-inner {
      ..
      background-color: #3a87ad; // change what you want
      color: white; // change what you want

    }
</code>```

Title: Making a Calendar with Ionic2

Body:
Can you change

in calendar.ts

 .no-events-label {
      ..
      color: darkgrey; // change what you want
    }

 .calendar-event-inner {
      ..
      background-color: #3a87ad; // change what you want
      color: white; // change what you want

    }


问:
How would I check if user input is over the Int limit using public static main void (String args[])
This is what I've put so far:

```<code>public class CheckNum {

    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++) {
            if (Integer.parseInt(args[i]) > Integer.MAX_VALUE) {
                System.out.println("Input value is too big");
            }

        }
    }

}
</code>```

However when I do put in a digit in linux thats over the Integer Max Value like this:

java CheckNum 1234567890

I get a NumberFormats error at parseInt, which I'm guessing is from the inability to convert the too large number into an Integer even before comparing with the max value of Integer. Is there another way to check if the number entered is too large for an integer using just the inputs on String args[]?

答:
Simply catch the exception you get

```<code>public static void main (String args[]) {
    for (int i = 0; i < args.length; i++) {
        try{
            Integer.parseInt(args[i]);
        catch(NumberFormatException e){
            //e.printStackTrace();
            System.out.format("Input %d is incorrect : %s%n", i, args[i]);
        }

    }
}
</code>```

It will print the input index that are incorrect.

Body:
This is what I've put so far:

public class CheckNum {

    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++) {
            if (Integer.parseInt(args[i]) > Integer.MAX_VALUE) {
                System.out.println("Input value is too big");
            }

        }
    }

}

However when I do put in a digit in linux thats over the Integer Max Value like this:

java CheckNum 1234567890

I get a NumberFormats error at parseInt, which I'm guessing is from the inability to convert the too large number into an Integer even before comparing with the max value of Integer. Is there another way to check if the number entered is too large for an integer using just the inputs on String args[]?

Body:
Simply catch the exception you get

public static void main (String args[]) {
    for (int i = 0; i < args.length; i++) {
        try{
            Integer.parseInt(args[i]);
        catch(NumberFormatException e){
            //e.printStackTrace();
            System.out.format("Input %d is incorrect : %s%n", i, args[i]);
        }

    }
}

It will print the input index that are incorrect.


问:
iPhone: Splash screen in app - Good or Bad?
I'm going to submit a Lifestyle app to the App Store. I'm confused whether to add a Splash Screen to the App or not ?

Please advise me whether it's a good or bad idea as far as usability and App Store's submission guidelines are concerned.

答:
Yes, you can add a splash screen to your app.

Depending on what you do with your splash screen as far as extravagant animations go, I would go subtle, with minimal animations.


问:
Laravel form returning errors only for some fields in log file
I've got an application form. This form has a few fields, such as "name", "email", "country", etc.

Laravel is ONLY redirecting back returning an error for the email field. Such as The email field is required.. For everything else, it just refreshes the page, and in my laravel.log file, I get the following error:

[2017-11-16 08:52:30] production.ERROR:
  Illuminate\Validation\ValidationException: The given data failed to
  pass validation. in
  C:\xampp\htdocs\series\commend-me\CommendMe\vendor\laravel\framework\src\Illuminate\Foundation\Validation\ValidatesRequests.php:89

Here is my route:

```<code>Route::post('/postapply', [
    'uses' => '\CommendMe\Http\Controllers\ApplyController@postApply',
    'as' => 'post.apply',
    'middleware' => ['auth'],
]);
</code>```

and my controller:

```<code>public function postApply(Request $request) {

    $this->validate($request, [
        'name' => 'required|alpha_num|max:40|min:2',
        'country' => 'required|alpha_num|max:100|min:2',
        'body' => 'required|string|max:2000',
        'mature' => 'required',
        'email' => 'required|email|max:255',
    ]);

    dd("test");
</code>```

dd does not return "test" in this instance. Furthermore, the validation will ONLY redirect back an error for the email field, and if the email field is renamed to something else in the controller, it'll go back to just sending the error to the log file.

Why is this happening?

EDIT:

Adding markup as requested:

```<code><form role="form" method="post" action="{{ route ('post.apply') }}">
    <div class="submitArtSection">
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div class="border-bot">
            <input class="submitArtTitle" type="text" name="name" maxlength="39"  placeholder="Name">
        </div>
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div class="border-bot">
            <input class="submitArtTitle" type="text" maxlength="255" name="email"  placeholder="Email">
        </div>
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div class="border-bot">
            <input class="submitArtTitle" type="text" maxlength="255" name="country"  placeholder="Country">
        </div>
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div>
            <textarea name="body" style="height: 175px;" maxlength="1980" placeholder="Tell us about yourself..."></textarea>
        </div>
    </div>

    <div class="submitArtSection submitArtCheckers">
    <div class="submitRequired">Required</div>
        <div>
            <span class="submitArtCaption submitArtRestrictionsHeader">
                Age
            </span>
            <span>
                <label>
                  <input type="radio" name="mature" value="0">
                    Under 18
                  <span class="checkmark"></span>
                </label>

                <label>
                 <input type="radio" name="mature" value="1">
                    18+
                  <span class="checkmark"></span>
                </label>
            </span>
        </div>
    </div>

    <div class="text-center">
        <button id="saveImage" class="pointer">Submit</button>
    </div>
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</code>```

dd($request->all()); at the start of the method returns of the following

```<code>array:5 [▼
  "name" => ""
  "email" => ""
  "country" => ""
  "body" => ""
  "_token" => "HKJ51CMvteYOD0OG79SQiRjpeTup9NNWvTfw1IWB"
]
</code>```

答:
Try changing the type of the input to email instead of text. You probably entered a text value when you made the submit, Laravel already has a validation for the email type

```<code><div class="border-bot">
            <input class="submitArtTitle" type="text" maxlength="255" name="email"  placeholder="Email">
        </div>
</code>```

TO

```<code><div class="border-bot">
            <input class="submitArtTitle" type="email" maxlength="255" name="email"  placeholder="Email">
        </div>
</code>```

Body:
I've got an application form. This form has a few fields, such as "name", "email", "country", etc.

Laravel is ONLY redirecting back returning an error for the email field. Such as The email field is required.. For everything else, it just refreshes the page, and in my laravel.log file, I get the following error:

[2017-11-16 08:52:30] production.ERROR:
  Illuminate\Validation\ValidationException: The given data failed to
  pass validation. in
  C:\xampp\htdocs\series\commend-me\CommendMe\vendor\laravel\framework\src\Illuminate\Foundation\Validation\ValidatesRequests.php:89

Here is my route:

Route::post('/postapply', [
    'uses' => '\CommendMe\Http\Controllers\ApplyController@postApply',
    'as' => 'post.apply',
    'middleware' => ['auth'],
]);

and my controller:

public function postApply(Request $request) {

    $this->validate($request, [
        'name' => 'required|alpha_num|max:40|min:2',
        'country' => 'required|alpha_num|max:100|min:2',
        'body' => 'required|string|max:2000',
        'mature' => 'required',
        'email' => 'required|email|max:255',
    ]);

    dd("test");

dd does not return "test" in this instance. Furthermore, the validation will ONLY redirect back an error for the email field, and if the email field is renamed to something else in the controller, it'll go back to just sending the error to the log file.

Why is this happening?

EDIT:

Adding markup as requested:

<form role="form" method="post" action="{{ route ('post.apply') }}">

Required

            <input class="submitArtTitle" type="text" name="name" maxlength="39"  placeholder="Name">

Required

            <input class="submitArtTitle" type="text" maxlength="255" name="email"  placeholder="Email">

Required

            <input class="submitArtTitle" type="text" maxlength="255" name="country"  placeholder="Country">

Required

            <textarea name="body" style="height: 175px;" maxlength="1980" placeholder="Tell us about yourself..."></textarea>

Required

                Age

                  <input type="radio" name="mature" value="0">
                    Under 18

                 <input type="radio" name="mature" value="1">
                    18+

        <button id="saveImage" class="pointer">Submit</button>

    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

dd($request->all()); at the start of the method returns of the following

array:5 [▼
  "name" => ""
  "email" => ""
  "country" => ""
  "body" => ""
  "_token" => "HKJ51CMvteYOD0OG79SQiRjpeTup9NNWvTfw1IWB"
]

Body:
Try changing the type of the input to email instead of text. You probably entered a text value when you made the submit, Laravel already has a validation for the email type

<div class="border-bot">
            <input class="submitArtTitle" type="text" maxlength="255" name="email"  placeholder="Email">
        </div>

TO

<div class="border-bot">
            <input class="submitArtTitle" type="email" maxlength="255" name="email"  placeholder="Email">
        </div>


问:
How to show popupWindow as drop down onClick of a Recyclerview row element?
I have tried using a code that is working fine except when I click on the last or end rows of the recyclerview, the popupWindow opens offscreen. Is there any way to show the popupWindow upSide of the view for end rows of the recyclerview.
Here is the code I am using:

```<code>public void showPopup(View v, int _pos) {

    LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View popupView = layoutInflater.inflate(R.layout.popup_row_appointment_option, null);

    popupWindow = new PopupWindow(
            popupView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    popupWindow.setBackgroundDrawable(new BitmapDrawable());
    popupWindow.setFocusable(true);
    popupWindow.setOutsideTouchable(true);
    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            //TODO do sth here on dismiss
        }
    });

    popupWindow.showAsDropDown(v, v.getScrollX(), v.getScrollY());

    tv_view_profile = (TextView) popupView.findViewById(R.id.tv_view_profile);
    tv_view_profile.setOnClickListener(this);
}
</code>```

答:
I would suggest you to go for PopupMenu which accepts AnchorView -> with the use of that we can get the exact position where we want to show popup -> you can pass AnchroView as View (The three dot imageview)

Here is the great example of it :

https://www.javatpoint.com/android-popup-menu-example

And also please use Appcompat version to get Material touch in menu.

Ok with custom layout you can go with your regular flow with minor changes --

```<code>popup.showAtLocation(anchorView, Gravity.BOTTOM, 0,
                anchorView.getBottom() - 60);
</code>```

this is just an example for bottom gravity. You can set gravity and margin according to your code.

anchorView =  the view where you want to show this popup. Try this and let me know if you have any query.

Body:
I have tried using a code that is working fine except when I click on the last or end rows of the recyclerview, the popupWindow opens offscreen. Is there any way to show the popupWindow upSide of the view for end rows of the recyclerview.
Here is the code I am using:

public void showPopup(View v, int _pos) {

    LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View popupView = layoutInflater.inflate(R.layout.popup_row_appointment_option, null);

    popupWindow = new PopupWindow(
            popupView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    popupWindow.setBackgroundDrawable(new BitmapDrawable());
    popupWindow.setFocusable(true);
    popupWindow.setOutsideTouchable(true);
    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            //TODO do sth here on dismiss
        }
    });

    popupWindow.showAsDropDown(v, v.getScrollX(), v.getScrollY());

    tv_view_profile = (TextView) popupView.findViewById(R.id.tv_view_profile);
    tv_view_profile.setOnClickListener(this);
}

Body:
I would suggest you to go for PopupMenu which accepts AnchorView -> with the use of that we can get the exact position where we want to show popup -> you can pass AnchroView as View (The three dot imageview)

Here is the great example of it :

https://www.javatpoint.com/android-popup-menu-example

And also please use Appcompat version to get Material touch in menu.

Ok with custom layout you can go with your regular flow with minor changes --

popup.showAtLocation(anchorView, Gravity.BOTTOM, 0,
                anchorView.getBottom() - 60);

this is just an example for bottom gravity. You can set gravity and margin according to your code.

anchorView =  the view where you want to show this popup. Try this and let me know if you have any query.