问:
curve_fit can not do a linear fit
I have a pretty simple data which the curve_fit can not give me a linear fit to it.
Here is the code:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#################
def linear(x,a,b):
    return a*x+b
#################
N=[200,250,300,400,500,600,700]
sp=[17,18,20,23,26,28,31]
tp=[19,21.5,23.5,27,30,33,36]
#################
error=[0]*len(N)
for i in range(len(N)):
      error[i]=abs(sp[i]-tp[i])/(1.0*sp[i])*100
a,b=curve_fit(linear,N,error)
print a
plt.figure()
plt.plot(N,error,'r-o',label=r'${\rm relative\ error}$')
plt.plot(N,linear(N,*a))
plt.grid()
plt.savefig('error.pdf')
plt.show()
</code>```

and what I get is none sense:
  none sense result!
What is going on

答:
Your call to linear is maybe not the best as N is a list and a is about zero. it should work if you call plt.plot( N, linear( np.array( N ),*a ) ) instead.
Moreover I highly recommend to rename the variables as curve_fit returns an array of best values and the covariance matrix. Hence bestFit, pcov = curve_fit( linear, N, error ) and then plt.plot( N, linear( np.array( N ), *bestFit ) ) is probably better and avoids confusion. a, b = ( curve_fit( linear, N, error) )[0] might work though but then you'd have to pass plt.plot( N, linear( np.array( N ), a, b ) )

Eventually, I'd do it like this:

```<code>import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#################
def linear( x, a, b):
    return a * x + b
#################
N =  np.array([ 200, 250, 300, 400, 500, 600, 700 ], np.float )
sp = np.array([ 17, 18, 20, 23, 26, 28, 31 ], np.float )
tp = np.array([ 19, 21.5, 23.5, 27, 30, 33, 36 ], np.float )
#################
error = np.fromiter( ( abs( s - t ) / s * 100 for s, t in zip( sp, tp ) ), np.float)
bestFit, pcov = curve_fit( linear, N, error )
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.plot( N, error, 'r-o', label=r'${\rm relative\ error}$' )
ax.plot( N,  linear( N, *bestFit ) )
ax.grid()
plt.show()
</code>```

So, works as it should.

Title: curve_fit can not do a linear fit

Body:
I have a pretty simple data which the curve_fit can not give me a linear fit to it.
Here is the code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#################
def linear(x,a,b):
    return a*x+b
#################
N=[200,250,300,400,500,600,700]
sp=[17,18,20,23,26,28,31]
tp=[19,21.5,23.5,27,30,33,36]
#################
error=[0]*len(N)
for i in range(len(N)):
      error[i]=abs(sp[i]-tp[i])/(1.0*sp[i])*100
a,b=curve_fit(linear,N,error)
print a
plt.figure()
plt.plot(N,error,'r-o',label=r'${\rm relative\ error}$')
plt.plot(N,linear(N,*a))
plt.grid()
plt.savefig('error.pdf')
plt.show()

and what I get is none sense:
  none sense result!
What is going on

Body:
Your call to linear is maybe not the best as N is a list and a is about zero. it should work if you call plt.plot( N, linear( np.array( N ),*a ) ) instead.
Moreover I highly recommend to rename the variables as curve_fit returns an array of best values and the covariance matrix. Hence bestFit, pcov = curve_fit( linear, N, error ) and then plt.plot( N, linear( np.array( N ), *bestFit ) ) is probably better and avoids confusion. a, b = ( curve_fit( linear, N, error) )[0] might work though but then you'd have to pass plt.plot( N, linear( np.array( N ), a, b ) )

Eventually, I'd do it like this:

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#################
def linear( x, a, b):
    return a * x + b
#################
N =  np.array([ 200, 250, 300, 400, 500, 600, 700 ], np.float )
sp = np.array([ 17, 18, 20, 23, 26, 28, 31 ], np.float )
tp = np.array([ 19, 21.5, 23.5, 27, 30, 33, 36 ], np.float )
#################
error = np.fromiter( ( abs( s - t ) / s * 100 for s, t in zip( sp, tp ) ), np.float)
bestFit, pcov = curve_fit( linear, N, error )
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.plot( N, error, 'r-o', label=r'${\rm relative\ error}$' )
ax.plot( N,  linear( N, *bestFit ) )
ax.grid()
plt.show()

So, works as it should.


来源: stackexchange

问:
How to display Woocommerce Category image?
I use this code in PHP:

```<code>$idcat = 147;
$thumbnail_id = get_woocommerce_term_meta( $idcat, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '<img src="'.$image.'" alt="" width="762" height="365" />';
</code>```

Where 147 is the current ID manually set, but i need to current id in other categories

Any suggest?

答:
To prevent full size category images slowing page down, you can use smaller images with wp_get_attachment_image_src():

```<code><?php
$thumbnail_id = get_term_meta( $term_id, 'thumbnail_id', true );

// get the medium-sized image url
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );

// Output in img tag
echo '<img src="' . $image[0] . '" alt="" />';

// Or as a background for a div
echo '<div class="image" style="background-image: url("' . $image[0] .'")"></div>';

?>
</code>```

EDIT: Fixed variable name and missing quote

ContentLicense: CC BY-SA 3.0

Body:
I use this code in PHP:

$idcat = 147;
$thumbnail_id = get_woocommerce_term_meta( $idcat, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '';

Where 147 is the current ID manually set, but i need to current id in other categories

Any suggest?

Body:
To prevent full size category images slowing page down, you can use smaller images with wp_get_attachment_image_src():

<?php
$thumbnail_id = get_term_meta( $term_id, 'thumbnail_id', true );

// get the medium-sized image url
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );

// Output in img tag
echo '<img src="' . $image[0] . '" alt="" />';

// Or as a background for a div
echo '<div class="image" style="background-image: url("' . $image[0] .'")"></div>';

?>

EDIT: Fixed variable name and missing quote

ContentLicense: CC BY-SA 4.0


问:
Text-based game code not working?
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Here is my code:

```<code><!DOCTYPE html>
<html>
<head>
<title>game</title>
<style>
</style>
</head>
<body>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
/*var input;
var room;

function submitFunction() {
    alert("hello")
}
*/
</script>
<script type="text/javascript">
    var input;
    var room;
    room = "Main Enterence"

    $(document).ready(function () {
        $("#mainForm").submit(function() {
            input = document.getElementById("textInput").value;

            if (input == "east") {
                if (room == "Main Enterence") {
                    room = "Bedroom"
                    enterBedroom();
                }

            }
            if (input == "west") {

            }
            if (input == "north") {

            }
            if (input == "south") {

            }

        })
    })

function enterBedroom() {
    $( "#consoleOutput" ).append( "<p>Test</p>" );

}
</script>

<div id="consoleOutput">
    <p id="welcomeText"></p>
</div>

<form onsubmit="submitFunction()" id="mainForm">
    <input type="text" id="textInput">
    <input type="submit" name="sumbit">
</form>

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

Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

答:
It clears because you are using submit which will cause the page to reload/refresh. Change that to click

your html button:

```<code><input type="button" name="sumbit" id="submit" value="submit">
</code>```

your js:

```<code>$(document).ready(function () {
    $("#submit").click(function() {
 .
 .
 .
</code>```

Title: Text-based game code not working?

Body:
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Here is my code:

<!DOCTYPE html>

<title>game</title>

<form onsubmit="submitFunction()" id="mainForm">
    <input type="text" id="textInput">
    <input type="submit" name="sumbit">
</form>

Hi,
I am trying to make a text-based HTML game. My .append method from jQuery is not working. When I .append() a paragraph tag to a  it displays for a split second and goes away. Please help

Body:
It clears because you are using submit which will cause the page to reload/refresh. Change that to click

your html button:

<input type="button" name="sumbit" id="submit" value="submit">

your js:

$(document).ready(function () {
    $("#submit").click(function() {
 .
 .
 .


问:
Need to put the output of below selenium code to a Json file

need to parse the output data and dump it into a json file. Any help will be appreciated.

```<code>executable_path = "/usr/local/share/chromedriver"
chrome_options = Options()
os.environ["webdriver.chrome.driver"] = executable_path
driver = webdriver.Chrome(executable_path=executable_path,
chrome_options=chrome_options)
driver.get("http://environment.netronline.com/api/viewers//env-
app.php?addr=gilbert")
time.sleep(5)
listOfElements = driver.find_elements_by_xpath("//div[@id='pinBox']//div[@class='pin']")
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_elements_by_xpath("//*[@id='tooltip']")
    print targetTooltip.text
    print "**********************"
</code>```

output is :
Emergency Response Notification System (ERNS)
Left click the pin for more info.

Incident: CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.
Incident Date: 7/3/2012 6:20
Incident location: MP: 926.96
Year Reported: 2012
City: GILBERT
State: AZ
County: MARICOPA

US RCRA Generators (CESQG, SQG, LQG)
Left click the pin for more info.

Info URL: http://ofmpub.epa.gov/enviro/fii_query_detail.disp_program_facility?p_registry_id=110045500757
EPA Identifier: 110045500757
Primary Name: CVS PHARMACY #3268
Address: 765 S LINDSAY RD
City: GILBERT
County: MARICOPA
State: AZ
Zipcode: 85296-3063
Programs: AZURITE, BR, RCRAINFO
Program Interests: HAZARDOUS WASTE BIENNIAL REPORTER, LQG, STATE MASTER
Updated On: 27-JAN-2015 13:51:45
Recorded On: 10-MAY-2012 16:46:54

Required json format is :
[
      {
         "source":"Emergency Response Notification System (ERNS)",
     "Incident":"CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.",
         "Incident Date":"7/3/2012 6:20",
         "Incident location":"MP: 926.96",
         "Year Reported":"2012",
         "City":"GILBERT",
         "State":"AZ",
         "County":"MARICOPA"
      }
]

答:
I have ran the code in python 3.5 so changed urllib2 to urllib3.
Next change is passing chrome driver path in method webdriver.chrome().
You can download chrome diver from "https://sites.google.com/a/chromium.org/chromedriver/".</p>

```<code>from selenium import webdriver
import os
import urllib3
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome('C:\\Users\\raj.damani\\Downloads\\chromedriver.exe')
driver.get("http://environment.netronline.com/api/viewers//env-app.php?addr=gilbert#")
time.sleep(8)
listOfElements = driver.find_elements_by_xpath('//div[@id="pinBox"]//div[@class="pin"]')
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_element_by_xpath('//*[@id="tooltip"]')
    print(targetTooltip.text)
    print("**********************")
</code>```

Body:
need to parse the output data and dump it into a json file. Any help will be appreciated.

executable_path = "/usr/local/share/chromedriver"
chrome_options = Options()
os.environ["webdriver.chrome.driver"] = executable_path
driver = webdriver.Chrome(executable_path=executable_path,
chrome_options=chrome_options)
driver.get("http://environment.netronline.com/api/viewers//env-
app.php?addr=gilbert")
time.sleep(5)
listOfElements = driver.find_elements_by_xpath("//div[@id='pinBox']//div[@class='pin']")
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_elements_by_xpath("//*[@id='tooltip']")
    print targetTooltip.text
    print "**********************"

output is :
Emergency Response Notification System (ERNS)
Left click the pin for more info.

Incident: CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.
Incident Date: 7/3/2012 6:20
Incident location: MP: 926.96
Year Reported: 2012
City: GILBERT
State: AZ
County: MARICOPA

US RCRA Generators (CESQG, SQG, LQG)
Left click the pin for more info.

Info URL: http://ofmpub.epa.gov/enviro/fii_query_detail.disp_program_facility?p_registry_id=110045500757
EPA Identifier: 110045500757
Primary Name: CVS PHARMACY #3268
Address: 765 S LINDSAY RD
City: GILBERT
County: MARICOPA
State: AZ
Zipcode: 85296-3063
Programs: AZURITE, BR, RCRAINFO
Program Interests: HAZARDOUS WASTE BIENNIAL REPORTER, LQG, STATE MASTER
Updated On: 27-JAN-2015 13:51:45
Recorded On: 10-MAY-2012 16:46:54

Required json format is :
[
      {
         "source":"Emergency Response Notification System (ERNS)",
     "Incident":"CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.",
         "Incident Date":"7/3/2012 6:20",
         "Incident location":"MP: 926.96",
         "Year Reported":"2012",
         "City":"GILBERT",
         "State":"AZ",
         "County":"MARICOPA"
      }
]

Body:
I have ran the code in python 3.5 so changed urllib2 to urllib3.
Next change is passing chrome driver path in method webdriver.chrome().
You can download chrome diver from "https://sites.google.com/a/chromium.org/chromedriver/".

from selenium import webdriver
import os
import urllib3
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome('C:\\Users\\raj.damani\\Downloads\\chromedriver.exe')
driver.get("http://environment.netronline.com/api/viewers//env-app.php?addr=gilbert#")
time.sleep(8)
listOfElements = driver.find_elements_by_xpath('//div[@id="pinBox"]//div[@class="pin"]')
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_element_by_xpath('//*[@id="tooltip"]')
    print(targetTooltip.text)
    print("**********************")


问:
Mongodb: calculated connectToField inside graphlookup
I have mongo tree structure that looks like this:

```<code>{"parent": null, "path": "#a", "name": "a"}
{"parent": "a", "path": "#a#b", "name": "b"}
{"parent": "a", "path": "#a#c", "name": "c"}
{"parent": "b", "path": "#a#b#1", "name": "1"}
{"parent": "b", "path": "#a#b#2", "name": "2"}
{"parent": "c", "path": "#a#c#1", "name": "1"}
{"parent": "1", "path": "#a#c#1#x", "name": "x"}
</code>```

which can be represented as follows:

```<code>#a
|_#a#b
|    |_#a#b#1
|    |_#a#b#2
|_#a#c
    |_#a#c#1
          |_#a#c#1#x
</code>```

My goal is to build a request that will get only the leaves under a specified node.

Had I stored the parent path inside the field parent instead of the parent identifier I would have been able to do it using the following request:

```<code>db.tree.aggregate([
        {$match:{"parent": {$regex:"^#a#c"}}},
        {$graphLookup:{
                       from:"tree",
                       startWith:"$path",
                       connectFromField:"path",
                       connectToField:"parent",
                       as:"dep"}},
        {$match:{dep:[]}},
        {$project:{"_id":0, path:1}}
])
</code>```

as already answered in my previous question here:
Mongodb: get only leaves of tree

The problem is I did not.

So I have to somehow transform the 'connectToField' in my request so that it represents the path of my parent instead of the id of my parent.
Does anybody have an idea on how to do this?

答:
connectToField is a name, not an expression. You can't do anything with it.

You really need to re-consider the schema. It is flawed in many ways starting from non-unique names used in parent references. Since you rely on the path string instead (which is a questionable decision by itself), you need a path to reference the parent.

The answer below does it runtime, and is hardly advisable for operational queries due to performance inefficiency and some assumptions of how the path is built. It can be used as a one-off request though.

Basically you need to create a view with calculated parent path:

```<code>db.createView("rootless_tree", "tree", [
    { $match: { parent: { $ne: null } } },
    { $addFields: {
        parent_path: { $let: {
            vars: { parents: { $split: [ "$path", "#" ] } },
            in: { $reduce: {
                input: { $slice: [ "$$parents", 1, { $subtract: [ { $size: "$$parents" }, 2 ] } ] },
                initialValue: "",
                in: { $concat: [ "$$value", "#", "$$this" ] }
            } }
        } }
    } }
]);
</code>```

So then you can do your lookup as advised in your previous question:

```<code>db.tree.aggregate([
    { $graphLookup: {
        from: "rootless_tree",
        startWith: "$path",
        connectFromField: "path",
        connectToField: "parent_path",
        as:"dep"
    } },
    { $match: { dep: [] } },
])
</code>```

Body:
I have mongo tree structure that looks like this:

{"parent": null, "path": "#a", "name": "a"}
{"parent": "a", "path": "#a#b", "name": "b"}
{"parent": "a", "path": "#a#c", "name": "c"}
{"parent": "b", "path": "#a#b#1", "name": "1"}
{"parent": "b", "path": "#a#b#2", "name": "2"}
{"parent": "c", "path": "#a#c#1", "name": "1"}
{"parent": "1", "path": "#a#c#1#x", "name": "x"}

which can be represented as follows:

#a
|_#a#b
|    |_#a#b#1
|    |_#a#b#2
|_#a#c
    |_#a#c#1
          |_#a#c#1#x

My goal is to build a request that will get only the leaves under a specified node.

Had I stored the parent path inside the field parent instead of the parent identifier I would have been able to do it using the following request:

db.tree.aggregate([
        {$match:{"parent": {$regex:"^#a#c"}}},
        {$graphLookup:{
                       from:"tree",
                       startWith:"$path",
                       connectFromField:"path",
                       connectToField:"parent",
                       as:"dep"}},
        {$match:{dep:[]}},
        {$project:{"_id":0, path:1}}
])

as already answered in my previous question here:
Mongodb: get only leaves of tree

The problem is I did not.

So I have to somehow transform the 'connectToField' in my request so that it represents the path of my parent instead of the id of my parent.
Does anybody have an idea on how to do this?

Body:
connectToField is a name, not an expression. You can't do anything with it.

You really need to re-consider the schema. It is flawed in many ways starting from non-unique names used in parent references. Since you rely on the path string instead (which is a questionable decision by itself), you need a path to reference the parent.

The answer below does it runtime, and is hardly advisable for operational queries due to performance inefficiency and some assumptions of how the path is built. It can be used as a one-off request though.

Basically you need to create a view with calculated parent path:

db.createView("rootless_tree", "tree", [
    { $match: { parent: { $ne: null } } },
    { $addFields: {
        parent_path: { $let: {
            vars: { parents: { $split: [ "$path", "#" ] } },
            in: { $reduce: {
                input: { $slice: [ "$$parents", 1, { $subtract: [ { $size: "$$parents" }, 2 ] } ] },
                initialValue: "",
                in: { $concat: [ "$$value", "#", "$$this" ] }
            } }
        } }
    } }
]);

So then you can do your lookup as advised in your previous question:

db.tree.aggregate([
    { $graphLookup: {
        from: "rootless_tree",
        startWith: "$path",
        connectFromField: "path",
        connectToField: "parent_path",
        as:"dep"
    } },
    { $match: { dep: [] } },
])


问:
PHP Call to a member function on a non-object
Okay, I have given up on figuring this out. I am creating a simple hook system, files are placed into a folder called hooks/.

Here is an example hook

```<code><?php
//Testhook
function exampleHook() {
    echo 'Example hook as been run';
}
//Register hook (start is the hook type (where to be called), exampleHook is the function //name and TRUE if it is enabled or not.

$hooks->RegisterHook('start','exampleHook','TRUE');
?>
</code>```

This system will load all the functions into the page, they wont be executed just yet though.

Now in the actual page heres what the code looks like:

```<code><?php
    include ("hooks.class.php");
    $hooks = new hooks('hooks/');
?>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Hooks</title>
</head>

<body>
    <p>Start hooks should run below</p>
    <?php $hooks->callHooks('start'); ?>
    <p>Start hooks should now finish</p>
</body>
</html>
</code>```

The callHooks function will execute any functions with the type 'start' in it. My problem is that in the testHook.php it cannot find the class $hooks, I've put the exampleHook into the same page and registered the function and it works perfectly but for some reason it cannot find the class $hooks even though the page is included.

Here is the hooks class file:

```<code><?php

class hooks {

    //Variable Initialisation
    private $hookDir;
    private $allHooks;
    public $debug = FALSE;
    private $debugDetails = array();

    //Function runs when the class is called, sets the location and calls the function retrieveHooks() to include all the files
    function __construct($hookDir = "library/addHooks/hooks/") {
        $this->hookDir = $hookDir;
        $this->allHooks = array();
        $this->retrieveHooks();
    }

    public function retrieveHooks() {
        //Get all files located in hooks directory
        $hookFiles = scandir($this->hookDir);
        //Loop through the files and remove any that arnt a file
        foreach($hookFiles as $hookFile) {
            if (strlen($hookFile) > 2) {
                //Include the file into the page
                include_once($this->hookDir . $hookFile);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = $this->hookDir . $hookFile . '<br />'; }
                // END DEBUG SECTION OF CODE //
            }
        }

    }

    //Function is called by hook files to register themselves into the class file
    public function registerHook($hookType,$functionName,$hookEnabled = TRUE) {
        if ($hookEnabled == TRUE) {
            $singleHook = array('type' => $hookType, 'function' => $functionName);
            $this->allHooks[] = $singleHook;
            // START DEBUG SECTION OF CODE //
            if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
            // END DEBUG SECTION OF CODE //
        }
    }

    //Execute the hooks based on the hook type, the programmer can add as many hooks as he wants
    public function callHooks($hookType) {
        //For each hook in the array
        foreach($this->allHooks as $singleHook) {
            //If hook is found for that type eg. start, end, middle
            if ($singleHook['type'] == $hookType) {
                //Call the function that is now included within the web page
                call_user_func($singleHook['function']);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
                // END DEBUG SECTION OF CODE //
            }
        }
    }

    //Return the array of debug details
    public function fetchDebugDetails() {
        return $debugDetails;
    }

    //Test the class by outputting a simple message
    public function testClass() {
        $className = 'hooks';
        echo 'Class is working: ' . $className;
    }

}

?>
</code>```

Finally the error message:

```<code>Notice: Undefined variable: hooks in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9

Fatal error: Call to a member function RegisterHook() on a non-object in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9
</code>```

Thanks, for any clarification just ask :) This has been really bugging me.

答:
@keepwalking is right, the problem is where the hook files are being included.
You include the file inside the "retrieveHooks()" method in the "hooks" class, and that is where the code in the hook starts to execute. It doesn't have access to the "$hook" variable because it's in the wrong scope, but it does have access to the "$this" variable, which can be called to add the hook.</p>

ContentLicense: CC BY-SA 2.5

Body:
Okay, I have given up on figuring this out. I am creating a simple hook system, files are placed into a folder called hooks/.

Here is an example hook

<?php
//Testhook
function exampleHook() {
    echo 'Example hook as been run';
}
//Register hook (start is the hook type (where to be called), exampleHook is the function //name and TRUE if it is enabled or not.

$hooks->RegisterHook('start','exampleHook','TRUE');
?>

This system will load all the functions into the page, they wont be executed just yet though.

Now in the actual page heres what the code looks like:

<?php
    include ("hooks.class.php");
    $hooks = new hooks('hooks/');
?>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Hooks</title>

Start hooks should run below

    <?php $hooks->callHooks('start'); ?>

Start hooks should now finish

The callHooks function will execute any functions with the type 'start' in it. My problem is that in the testHook.php it cannot find the class $hooks, I've put the exampleHook into the same page and registered the function and it works perfectly but for some reason it cannot find the class $hooks even though the page is included.

Here is the hooks class file:

<?php

class hooks {

    //Variable Initialisation
    private $hookDir;
    private $allHooks;
    public $debug = FALSE;
    private $debugDetails = array();

    //Function runs when the class is called, sets the location and calls the function retrieveHooks() to include all the files
    function __construct($hookDir = "library/addHooks/hooks/") {
        $this->hookDir = $hookDir;
        $this->allHooks = array();
        $this->retrieveHooks();
    }

    public function retrieveHooks() {
        //Get all files located in hooks directory
        $hookFiles = scandir($this->hookDir);
        //Loop through the files and remove any that arnt a file
        foreach($hookFiles as $hookFile) {
            if (strlen($hookFile) > 2) {
                //Include the file into the page
                include_once($this->hookDir . $hookFile);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = $this->hookDir . $hookFile . '
'; }
                // END DEBUG SECTION OF CODE //
            }
        }

    }

    //Function is called by hook files to register themselves into the class file
    public function registerHook($hookType,$functionName,$hookEnabled = TRUE) {
        if ($hookEnabled == TRUE) {
            $singleHook = array('type' => $hookType, 'function' => $functionName);
            $this->allHooks[] = $singleHook;
            // START DEBUG SECTION OF CODE //
            if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
            // END DEBUG SECTION OF CODE //
        }
    }

    //Execute the hooks based on the hook type, the programmer can add as many hooks as he wants
    public function callHooks($hookType) {
        //For each hook in the array
        foreach($this->allHooks as $singleHook) {
            //If hook is found for that type eg. start, end, middle
            if ($singleHook['type'] == $hookType) {
                //Call the function that is now included within the web page
                call_user_func($singleHook['function']);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
                // END DEBUG SECTION OF CODE //
            }
        }
    }

    //Return the array of debug details
    public function fetchDebugDetails() {
        return $debugDetails;
    }

    //Test the class by outputting a simple message
    public function testClass() {
        $className = 'hooks';
        echo 'Class is working: ' . $className;
    }

}

?>

Finally the error message:

Notice: Undefined variable: hooks in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9

Fatal error: Call to a member function RegisterHook() on a non-object in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9

Thanks, for any clarification just ask :) This has been really bugging me.


问:
Render JSON data using React
I have this JSON data I am trying to render as a list.

```<code>[{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]
</code>```

I am trying to display the data such that I pass a title of the data and the id's as parameters from Parent class to Child class and the latter prints the data as list.

```<code>export default class Parent extends Component {
  render() {
    return (
        <div>
        <Child
          title={"Group 1"}
          options={this.props.data.name}
        />
        </div>
    );
  }
}
</code>```

Here's my Child class:

```<code>export default class Child extends Component {
  render() {
    var data=this.props;
    var title=this.props.title;
    var name=this.props.name;
    return (
      <ul>
        <h4>{title}</h4>
        <div>{this.props.map(item=>
          <li>{name}</li>
        )}
        </div>
      </ul>
    );
  }
}
</code>```

What I don't understand is how to use map in the Child class to display data. I know that I shouldn't write this.props.map(item=>. I am new to React and would appreciate some help fixing this.

答:
Well, first you have to use JSON.parse() on your json, so it becomes a javascript object, you also have to make sure you are passing the props to your Child right. Then, you can map like this:

this.props.data.map((item,i) =>
{item.name}
)

Title: Render JSON data using React

Body:
I have this JSON data I am trying to render as a list.

[{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]

I am trying to display the data such that I pass a title of the data and the id's as parameters from Parent class to Child class and the latter prints the data as list.

export default class Parent extends Component {
  render() {
    return (

        <Child
          title={"Group 1"}
          options={this.props.data.name}
        />

    );
  }
}

Here's my Child class:

export default class Child extends Component {
  render() {
    var data=this.props;
    var title=this.props.title;
    var name=this.props.name;
    return (

{title}

{this.props.map(item=>

{name}

        )}

    );
  }
}

What I don't understand is how to use map in the Child class to display data. I know that I shouldn't write this.props.map(item=>. I am new to React and would appreciate some help fixing this.

Body:
Well, first you have to use JSON.parse() on your json, so it becomes a javascript object, you also have to make sure you are passing the props to your Child right. Then, you can map like this:

this.props.data.map((item,i) => <li key={i}>{item.name}</li>)


问:
li Control from code behind asp.net
i can't access to a li control in my master page,
i need to set it visible = false when user isn't "admin", with runat = "server" i can't access from code, why?  how can i solve this problem?
aspx

```<code><li runat="server" id="tabadmin"><a runat="server" href="~/DatiInterni.aspx" >Amministrazione sito</a></li>
</code>```

aspx.cs

```<code>if (Context.User.Identity.Name != "admin")
{
    HtmlGenericControl li = (HtmlGenericControl) FindControl("tabadmin");
    li.Attributes.Add("Visible", "false");

}
</code>```

login view

```<code><asp:LoginView runat="server" ViewStateMode="Disabled">
    <AnonymousTemplate>
        <ul class="nav navbar-nav navbar-right">
        <li><a runat="server" href="~/Account/Login" title="Login">Accedi</a></li>
          <li><a runat="server" href="~/Account/Register" title="Register">Registrati</a></li>
        </ul>
    </AnonymousTemplate>
     <%--Lato destro della navbar se l'utente si è autenticato--%>
    <LoggedInTemplate>
        <ul class="nav navbar-nav navbar-right"  runat="server">
         <li><a runat="server" href="~/Account/Manage" title="Manage your account">Ciao, <%: Context.User.Identity.GetUserName()  %> </a></li>
        <li class="dropdown">
      <a class="dropdown-toggle" data-toggle="dropdown" href="#">Menu
      <span class="caret"></span></a>
      <ul class="dropdown-menu" runat="server" id="menu">
        <li><a href="/Apparati.aspx">Dati clienti</a></li>
        <li><a href="/DatiInterni.aspx">Dati interni</a></li>
     <li runat="server" id="tabadmin"><a runat="server" href="~/DatiInterni.aspx" >Amministrazione sito</a></li>
     <li>
        <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Disconnetti" LogoutPageUrl="/Account/Login.aspx" OnLoggingOut="Unnamed_LoggingOut" />
    </li>
      </ul>
    </li>
        </ul>
    </LoggedInTemplate>
</asp:LoginView>
</code>```

答:
Solved with this code </p>

```<code>            <asp:LoginView runat="server" ViewStateMode="Disabled" ID="LogSection">

                <AnonymousTemplate>
                    <ul class="nav navbar-nav navbar-right">
                    <li><a runat="server" href="~/Account/Login" title="Login">Accedi</a></li>
                      <li><a runat="server" href="~/Account/Register" title="Register">Registrati</a></li>
                    </ul>
                </AnonymousTemplate>
                 <%--Lato destro della navbar se l'utente si è autenticato--%>
                <LoggedInTemplate>
                    <ul class="nav navbar-nav navbar-right"  runat="server">
                     <li><a runat="server" href="~/Account/Manage" title="Manage your account">Ciao, <%: Context.User.Identity.GetUserName()  %> </a></li>
                    <li class="dropdown" id="menu" runat="server">
                  <a class="dropdown-toggle" data-toggle="dropdown" href="#">Menu
                  <span class="caret"></span></a>
                  <ul class="dropdown-menu" runat="server" id="list" >
                    <li><a href="/Apparati.aspx">Dati clienti</a></li>
                    <li><a href="/DatiInterni.aspx">Dati interni</a></li>
                 <li runat="server" id="tabadmin" visible="true"><a runat="server" href="~/Admin/Administration.aspx" >Amministrazione sito</a></li>
                                                    <li>
                            <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Disconnetti" LogoutPageUrl="/Account/Login.aspx" OnLoggingOut="Unnamed_LoggingOut" />
                        </li>
                  </ul>
                </li>
                    </ul>
                </LoggedInTemplate>
            </asp:LoginView>
</code>```

<p>code behind </p>

```<code>    if (Context.User.Identity.Name != "admin" && Context.User.Identity.Name != "")
    {
        HtmlGenericControl menu = (HtmlGenericControl)LogSection.FindControl("menu");
        HtmlGenericControl list = (HtmlGenericControl)menu.FindControl("list");
        HtmlGenericControl li = (HtmlGenericControl)list.FindControl("tabadmin");
        li.Visible = false;
    }
</code>```

Title: li Control from code behind asp.net

Body:
i can't access to a li control in my master page,
i need to set it visible = false when user isn't "admin", with runat = "server" i can't access from code, why?  how can i solve this problem?
aspx

Amministrazione sito

aspx.cs

if (Context.User.Identity.Name != "admin")
{
    HtmlGenericControl li = (HtmlGenericControl) FindControl("tabadmin");
    li.Attributes.Add("Visible", "false");

}

login view

<asp:LoginView runat="server" ViewStateMode="Disabled">
    <AnonymousTemplate>

Accedi

Registrati

    </AnonymousTemplate>
     <%--Lato destro della navbar se l'utente si è autenticato--%>
    <LoggedInTemplate>

Ciao, <%: Context.User.Identity.GetUserName()  %>

      Menu

Dati clienti

Dati interni

Amministrazione sito

        <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Disconnetti" LogoutPageUrl="/Account/Login.aspx" OnLoggingOut="Unnamed_LoggingOut" />

    </LoggedInTemplate>
</asp:LoginView>

Body:
Solved with this code

            <asp:LoginView runat="server" ViewStateMode="Disabled" ID="LogSection">

                <AnonymousTemplate>
                    <ul class="nav navbar-nav navbar-right">
                    <li><a runat="server" href="~/Account/Login" title="Login">Accedi</a></li>
                      <li><a runat="server" href="~/Account/Register" title="Register">Registrati</a></li>
                    </ul>
                </AnonymousTemplate>
                 <%--Lato destro della navbar se l'utente si è autenticato--%>
                <LoggedInTemplate>
                    <ul class="nav navbar-nav navbar-right"  runat="server">
                     <li><a runat="server" href="~/Account/Manage" title="Manage your account">Ciao, <%: Context.User.Identity.GetUserName()  %> </a></li>
                    <li class="dropdown" id="menu" runat="server">
                  <a class="dropdown-toggle" data-toggle="dropdown" href="#">Menu
                  <span class="caret"></span></a>
                  <ul class="dropdown-menu" runat="server" id="list" >
                    <li><a href="/Apparati.aspx">Dati clienti</a></li>
                    <li><a href="/DatiInterni.aspx">Dati interni</a></li>
                 <li runat="server" id="tabadmin" visible="true"><a runat="server" href="~/Admin/Administration.aspx" >Amministrazione sito</a></li>
                                                    <li>
                            <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Disconnetti" LogoutPageUrl="/Account/Login.aspx" OnLoggingOut="Unnamed_LoggingOut" />
                        </li>
                  </ul>
                </li>
                    </ul>
                </LoggedInTemplate>
            </asp:LoginView>

code behind

    if (Context.User.Identity.Name != "admin" && Context.User.Identity.Name != "")
    {
        HtmlGenericControl menu = (HtmlGenericControl)LogSection.FindControl("menu");
        HtmlGenericControl list = (HtmlGenericControl)menu.FindControl("list");
        HtmlGenericControl li = (HtmlGenericControl)list.FindControl("tabadmin");
        li.Visible = false;
    }


问:
My auto suggestion is not working properly?
```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Auto Suggest</title>
 <script type="text/javascript" src="{{ MEDIA_URL }}scripts/jquery-1.2.1.pack.js"></script>
 <script type="text/javascript">
    function lookup(inputString) {
        if(inputString.length == 0) {
            $('#suggestions').hide();
        } else {
            $.post("/search/", {q: ""+inputString+""}, function(data){
                if(data.length >0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').html(data);
                }
            });
        }
    }
    function fill(thisValue) {
        $('#inputString').val(thisValue);
        setTimeout("$('#suggestions').hide();", 200);
    }
 </script>
<style type="text/css">
    body {
        font-family: Helvetica;
        font-size: 11px;
        color: #000;
    }
    h3 {
        margin: 0px;
        padding: 0px;
    }
    .suggestionsBox {
        position: relative;
        left: 30px;
        margin: 10px 0px 0px 0px;
        width: 200px;
        background-color: #212427;
        -moz-border-radius: 7px;
        -webkit-border-radius: 7px;
        border: 2px solid #000;
        color: #fff;
    }
    .suggestionList {
        margin: 0px;
        padding: 0px;
    }
    .suggestionList li {
        margin: 0px 0px 3px 0px;
        padding: 3px;
        cursor: pointer;
    }

    .suggestionList li:hover {
        background-color: #659CD8;
    }
</style>
</head>
 <body>
    <div>
        <form>
            <div>
                <br />
                <input type="text" size="30" value="" autocomplete="off" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
            </div>
            <div class="suggestionsBox" id="suggestions" style="display: none;">
                    <img src="{{ MEDIA_URL }}images/upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
                <div class="suggestionList" id="autoSuggestionsList">
                    {% for value in result %}
                    <li onclick="fill({{ value }});">{{ value }}</li>
                        {% endfor %}
                </div>
            </div>
        </form>
    </div>

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

I tried an example from http://www.jeffadams.co.uk/2009/08/31/auto-suggest-with-php-jquery/ But it is not working for me. Where i am doing wrong? Can any one suggest?

答: This isn't a direct answer to your question, but have you tried using the 'official' jquery autocomplete? http://jqueryui.com/demos/autocomplete/</p>

Body:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Auto Suggest</title>

        <form>

                <input type="text" size="30" value="" autocomplete="off" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />

                    {% for value in result %}

{{ value }}

                        {% endfor %}

        </form>

I tried an example from http://www.jeffadams.co.uk/2009/08/31/auto-suggest-with-php-jquery/ But it is not working for me. Where i am doing wrong? Can any one suggest?


问:
Python tkinter save new results in text file
I would like to ask a question about loading a certain txt file in python with tkinter, or any other method that I could use. Here is the "test" program that I made.enter image description here

Every button calculates a certain percentage of the entered number.
After I enter a number and calculate the percentage of that number, say I enter 100 and 80% of that is 80. The result is displayed, and after that I would like to save that result in a text file, using "Add new max" button.
After the result is saved when I open the program it should display "Current max: 80". So basically save the calculated result and display it every time I open the program.

Say that the "current saved result" is 80 and I calculate a new one which is greater than current result(80) and it is thus replaced.

In the image that I attached:

```<code>      test1 = x
</code>```

and if the new value that I enter is greater than x, that x should be replaced by new value. (ignore test2, test3)

What should I use in order to do that?

Thank you guys in advance!

答:
This isn't too difficult.

To write a file:

```<code>f = open( 'name_of_a_file', 'w' ) #(w = write)
f.write(some_data_or_something)
f.close()
</code>```

To read a file:

```<code>try:
    fh = open('name_of_a_file', "r")
    some_data = fh.read()
    fh.close()

except IOError:
    print("could not load the file.")
</code>```

**Complete code - saves a file, then pulls it back in and prints it:

```<code>some_data_or_something = 'hello'
f = open( 'name_of_a_file', 'w' ) #(w = write)
f.write(some_data_or_something)
f.close()

try:
    fh = open('name_of_a_file', "r") #(r = read)
    some_data = fh.read()
    fh.close()
    print(some_data)

except IOError:
    print("could not load the file.")
</code>```

Body:
I would like to ask a question about loading a certain txt file in python with tkinter, or any other method that I could use. Here is the "test" program that I made.enter image description here

Every button calculates a certain percentage of the entered number.
After I enter a number and calculate the percentage of that number, say I enter 100 and 80% of that is 80. The result is displayed, and after that I would like to save that result in a text file, using "Add new max" button.
After the result is saved when I open the program it should display "Current max: 80". So basically save the calculated result and display it every time I open the program.

Say that the "current saved result" is 80 and I calculate a new one which is greater than current result(80) and it is thus replaced.

In the image that I attached:

      test1 = x

and if the new value that I enter is greater than x, that x should be replaced by new value. (ignore test2, test3)

What should I use in order to do that?

Thank you guys in advance!

Body:
This isn't too difficult.

To write a file:

f = open( 'name_of_a_file', 'w' ) #(w = write)
f.write(some_data_or_something)
f.close()

To read a file:

try:
    fh = open('name_of_a_file', "r")
    some_data = fh.read()
    fh.close()

except IOError:
    print("could not load the file.")

**Complete code - saves a file, then pulls it back in and prints it:

some_data_or_something = 'hello'
f = open( 'name_of_a_file', 'w' ) #(w = write)
f.write(some_data_or_something)
f.close()

try:
    fh = open('name_of_a_file', "r") #(r = read)
    some_data = fh.read()
    fh.close()
    print(some_data)

except IOError:
    print("could not load the file.")


问:
Remove duplicates by multiple conditions
I have data where an individual (Name) appears multiple times in a eggphase category. I would like for there only to be one sample per individual but I don't just want to keep the first one the R finds. I would like to keep the one where the group appears most in all other categories. Hopefully my example helps make this clear.

```<code>library(tidyverse)
myDF <- read.table(text="Tissue Food Eggphase Name Group
  wb fl after Kia a
  wb fl after Kia c
  wb wf before Kia b
  wb fl before Lucy c
  wb fl after Lucy b
  wb fl after Lucy c
  wb fl yolkdep Jess c
  wb fl yolkdep Betty a
  wb fl yolkdep Betty b", header = TRUE)
</code>```

I would like to just keep the rows where Name appears once grouped by Tissue, Food and Eggphase BUT I want to select the row where Group appears in most if not all different eggphases (with the same Tissue and Food combinations).

```<code>   #results I want
  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     c
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     c
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b
</code>```

I tried

```<code>one_bird <- myDF %>%
  distinct(Tissue, Food, Eggphase, Name, .keep_all = TRUE)
</code>```

but it only keeps the first entry

```<code>  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     a
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     b
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b
</code>```

Any ideas in how to tell it select the row where Groupappears in most (if not all) of the eggphases within a Tissue Food combination?
In my example the group that appears the most within the Tissue and Food combination of wb and fl is c and b but Kia doesn't appear in Group b and so c is a better option. Like this example, my data has duplicates which are from groups which are not the most common Group, how do I make it choose next most common just for that row?

I hope I have made enough sense.

答:
Hey thanx for your guys help!! A combination of what you suggested seems to have worked:</p>

```<code># Create a var that indicates a duplicate or a record with a duplicate
myDF$duplicate <- duplicated(myDF[,c('Name','Eggphase','Tissue','Food')])
#this won't tell you that the first entry og the combination is double
# so need to make them check against the previous row
myDF$duplicate <- ifelse(duplicated(myDF[,c('Name','Eggphase','Tissue','Food')],fromLast=T),yes=T, no=myDF$duplicate)

# Count eggphases by group
eggphaseCount <- with(myDF,aggregate(x=list(Group_phaseCt=Eggphase),by=list(Group=Group),FUN=function(x) length(unique(x))))
# Merge to DF
myDF <- merge(myDF,eggphaseCount,by='Group',all=T)

# Get the max # of egphases by name
scale <- with(myDF,aggregate(x=list(PhaseMax=Group_phaseCt),by=list(Name=Name),FUN=max))
# Add to DF
myDF <- merge(myDF,scale,by='Name',all=T)

# Take the ratio
myDF$bestRatio <- with(myDF,Group_phaseCt/PhaseMax)

# make new df without duplicates
myDF2 <- myDF %>%
#arrange in a way that the first duplicate is from the group with the most eggphases
#and the name appears in the most egg phases
  arrange(Tissue, Food, Eggphase, Name, Group, desc(Group_phaseCt), desc(PhaseMax)) %>%
#select only distinct rows according to specified var keep all others
  distinct(Tissue, Food, Eggphase, Name, .keep_all = TRUE)
</code>```

Body:
I have data where an individual (Name) appears multiple times in a eggphase category. I would like for there only to be one sample per individual but I don't just want to keep the first one the R finds. I would like to keep the one where the group appears most in all other categories. Hopefully my example helps make this clear.

library(tidyverse)
myDF <- read.table(text="Tissue Food Eggphase Name Group
  wb fl after Kia a
  wb fl after Kia c
  wb wf before Kia b
  wb fl before Lucy c
  wb fl after Lucy b
  wb fl after Lucy c
  wb fl yolkdep Jess c
  wb fl yolkdep Betty a
  wb fl yolkdep Betty b", header = TRUE)

I would like to just keep the rows where Name appears once grouped by Tissue, Food and Eggphase BUT I want to select the row where Group appears in most if not all different eggphases (with the same Tissue and Food combinations).

   #results I want
  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     c
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     c
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b

I tried

one_bird <- myDF %>%
  distinct(Tissue, Food, Eggphase, Name, .keep_all = TRUE)

but it only keeps the first entry

  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     a
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     b
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b

Any ideas in how to tell it select the row where Groupappears in most (if not all) of the eggphases within a Tissue Food combination?
In my example the group that appears the most within the Tissue and Food combination of wb and fl is c and b but Kia doesn't appear in Group b and so c is a better option. Like this example, my data has duplicates which are from groups which are not the most common Group, how do I make it choose next most common just for that row?

I hope I have made enough sense.

Body:
Hey thanx for your guys help!! A combination of what you suggested seems to have worked:

# Create a var that indicates a duplicate or a record with a duplicate
myDF$duplicate <- duplicated(myDF[,c('Name','Eggphase','Tissue','Food')])
#this won't tell you that the first entry og the combination is double
# so need to make them check against the previous row
myDF$duplicate <- ifelse(duplicated(myDF[,c('Name','Eggphase','Tissue','Food')],fromLast=T),yes=T, no=myDF$duplicate)

# Count eggphases by group
eggphaseCount <- with(myDF,aggregate(x=list(Group_phaseCt=Eggphase),by=list(Group=Group),FUN=function(x) length(unique(x))))
# Merge to DF
myDF <- merge(myDF,eggphaseCount,by='Group',all=T)

# Get the max # of egphases by name
scale <- with(myDF,aggregate(x=list(PhaseMax=Group_phaseCt),by=list(Name=Name),FUN=max))
# Add to DF
myDF <- merge(myDF,scale,by='Name',all=T)

# Take the ratio
myDF$bestRatio <- with(myDF,Group_phaseCt/PhaseMax)

# make new df without duplicates
myDF2 <- myDF %>%
#arrange in a way that the first duplicate is from the group with the most eggphases
#and the name appears in the most egg phases
  arrange(Tissue, Food, Eggphase, Name, Group, desc(Group_phaseCt), desc(PhaseMax)) %>%
#select only distinct rows according to specified var keep all others
  distinct(Tissue, Food, Eggphase, Name, .keep_all = TRUE)


问:
joomla, html + javascript, radio button validation
Hi i need to make a  html form with a number of questions, each question has 3 answers an each answer is a radio button , the thing is : each answer has a value which goes from 0 to 2, so answer 1 is equal to 0, answer 2 to 1, answer 3 to 2, i need to get the valué of the radio button selected because later i will use it to show an answer, for example : do you like helping people ? radio button 1 : never, radio button 2: sometimes, radio button 3: always, then after you answer lets say 10 questions i will show your results on screen like this : you got 5 points you are a great person for example. I think this can be made with html with javascript but i dont know the javascript stuff, can you help me telling me how to do that ?? , thanks.</p>

答: You can use RSForm!Pro for this, which will allow you to easily create the form. You will be able to modify the "Thank You" message to include the answers provided by the end user. For example, if you have a field named answer1 in your form, then you can just retrieve the field's value using {answer1:value} in the "Thank You" message.


问:
Can't convert object of type java.lang.Long to type
I'm trying to connect my app to a Firebase Database, but whenever I launch the code that problem show up

that's my main activity

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

    private static final String TAG = "ViewDatabase";

    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference("Discount/Business");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                UserInformation uInfo = new UserInformation();
                uInfo.setAltro(ds.child("Altro").getValue(UserInformation.class).getAltro());
                uInfo.setCognome(ds.child("Cognome").getValue(UserInformation.class).getCognome());
                uInfo.setInformazioni(ds.child("Informazioni").getValue(UserInformation.class).getInformazioni());
                uInfo.setNome(ds.child("Nome").getValue(UserInformation.class).getNome());

                Log.d(TAG, "showData: Altro: " + uInfo.getAltro());
                Log.d(TAG, "showData: Cognome: " + uInfo.getCognome());
                Log.d(TAG, "showData: Informazioni: " + uInfo.getInformazioni());
                Log.d(TAG, "showData: Nome: " + uInfo.getNome());

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
</code>```

that's my User class

```<code>public class UserInformation {
private String Altro;
private String Cognome;
private String Informazioni;
private String Nome;

public UserInformation(){

}

public String getAltro() {
    return Altro;
}

public void setAltro(String altro) {
    Altro = altro;
}

public String getCognome() {
    return Cognome;
}

public void setCognome(String cognome) {
    Cognome = cognome;
}

public String getInformazioni() {
    return Informazioni;
}

public void setInformazioni(String informazioni) {
    Informazioni = informazioni;
}

public String getNome() {
    return Nome;
}

public void setNome(String nome) {
    Nome = nome;
}
</code>```

My firebase database

and my log error

```<code>11-14 10:59:55.016 2909-2909/com.app8 E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.app8, PID: 2909
                                                        com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.app8.UserInformation
                                                            at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                                                            at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                            at com.app8.MainActivity$1.onDataChange(MainActivity.java:41)
                                                            at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
                                                            at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                            at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

It's my first time using Firebase, I've seen other questions related to the topic but I can't figure out how to make it works, I hope you can help me.

thanks for your help, any suggestion is highly appreciated

答:
To get those values out from the database, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference businessRef = rootRef.child("Discount").child("Business");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String altro = ds.child("Altro").getValue(String.class);
            String cognome = ds.child("Cognome").getValue(String.class);
            String informazioni = ds.child("Informazioni").getValue(String.class);
            String nome = ds.child("Nome").getValue(String.class);
            Log.d("TAG", altro + " / " + cognome + " / " + informazioni + " / " + nome);
        }
    }

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

As an advice, use in the future all fields according cu Java Naming Conventions.

Body:
I'm trying to connect my app to a Firebase Database, but whenever I launch the code that problem show up

that's my main activity

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "ViewDatabase";

    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference("Discount/Business");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                UserInformation uInfo = new UserInformation();
                uInfo.setAltro(ds.child("Altro").getValue(UserInformation.class).getAltro());
                uInfo.setCognome(ds.child("Cognome").getValue(UserInformation.class).getCognome());
                uInfo.setInformazioni(ds.child("Informazioni").getValue(UserInformation.class).getInformazioni());
                uInfo.setNome(ds.child("Nome").getValue(UserInformation.class).getNome());

                Log.d(TAG, "showData: Altro: " + uInfo.getAltro());
                Log.d(TAG, "showData: Cognome: " + uInfo.getCognome());
                Log.d(TAG, "showData: Informazioni: " + uInfo.getInformazioni());
                Log.d(TAG, "showData: Nome: " + uInfo.getNome());

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

that's my User class

public class UserInformation {
private String Altro;
private String Cognome;
private String Informazioni;
private String Nome;

public UserInformation(){

}

public String getAltro() {
    return Altro;
}

public void setAltro(String altro) {
    Altro = altro;
}

public String getCognome() {
    return Cognome;
}

public void setCognome(String cognome) {
    Cognome = cognome;
}

public String getInformazioni() {
    return Informazioni;
}

public void setInformazioni(String informazioni) {
    Informazioni = informazioni;
}

public String getNome() {
    return Nome;
}

public void setNome(String nome) {
    Nome = nome;
}

My firebase database

and my log error

11-14 10:59:55.016 2909-2909/com.app8 E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.app8, PID: 2909
                                                        com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.app8.UserInformation
                                                            at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                                                            at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                            at com.app8.MainActivity$1.onDataChange(MainActivity.java:41)
                                                            at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
                                                            at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                            at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

It's my first time using Firebase, I've seen other questions related to the topic but I can't figure out how to make it works, I hope you can help me.

thanks for your help, any suggestion is highly appreciated

Body:
To get those values out from the database, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference businessRef = rootRef.child("Discount").child("Business");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String altro = ds.child("Altro").getValue(String.class);
            String cognome = ds.child("Cognome").getValue(String.class);
            String informazioni = ds.child("Informazioni").getValue(String.class);
            String nome = ds.child("Nome").getValue(String.class);
            Log.d("TAG", altro + " / " + cognome + " / " + informazioni + " / " + nome);
        }
    }

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

As an advice, use in the future all fields according cu Java Naming Conventions.


问:
Extracting certain parts on image with PHP
I would like to be able to extract radar data from gif which occurs every hour.

This is an example of one gif:

Data colors can vary according data legend on the right. I would also like that country borders are not visible, as gif is drown in order: base layer, radar data layer, borders layer - I only need pure radar data.

Any suggestion or solution will be very much appriciated!

答:
First of all, if you are interested just in the information coded by colours, which us present in some specific frame of the gif, read here about how you can access only one frame if that gif:

Accessing gif frames

After that, considering you have a rectangle image, you can scan pixel by pixel, as a matrix, using php function 'imagecolorat'.


问:
Why trim is not working?
I am trying to trim leading whitespaces from the string and I do not know what is wrong with my approach, any suggestions would be appreciated ?

Code:

this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();

am reading poNumber from csv file as "     IG078565 and IG083060 " and output also am getting same value with same whitespaces, not sure why ?

Updated

Adding complete method for better context:

```<code>public BillingDTO(String currency, String migrationId, String chargeId, String priceId, String poNumber, String otc,
            String billingClassId, String laborOnly) {
        super();
        this.currency = currency.equals("") ? currency : currency.trim();
        this.migrationId = migrationId.equals("") ? migrationId : migrationId.trim();
        this.chargeId = chargeId.equals("") ? chargeId : chargeId.trim();
        this.priceId = priceId.equals("") ? priceId : priceId.trim();
        this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
            //poNumber.trim();
        //System.out.println("poNumber:"+this.poNumber.trim());
        //this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
        this.otc = otc.equals("") ? otc : otc.trim();
        this.billingClassId = billingClassId.equals("") ? billingClassId : billingClassId.trim();
        this.laborOnly = laborOnly.equals("") ? "N" : laborOnly;
    }
</code>```

Thanks.

答:
Update It appears your whitespace is not a whitespace (ascii=32). Yours is with code 160, which is a no-breaking space. trim() does not handle it. So you must do something like this:

```<code>this.poNumber = poNumber.replace(String.valueOf((char) 160), " ").trim();
</code>```

You'd better create an utility - YourStringUtils.trim(string) and there perform the two operations - both .trim() and the replace(..)

Original answer:

Just use this.poNumber = poNumber.trim();

If there is a possibility for poNumber to be null, then you can use the null-safe this.poNumber = StringUtils.trim(poNumber); from commons-lang.

You can also use trimToEmpty(..) from the same class, if you want null to be transformed to an empty string.

If you don't want to rely on commons-lang, then just add an if-clause:

```<code>if (poNumber != null) {
    this.poNumber = poNumber.trim();
}
</code>```

As noted in the comments under the question - make sure you are checking the right variable after the trimming. You should check the instance variable. Your parameter (or local variable, I can't tell) does not change, because strings are immutable.

Title: Why trim is not working?

Body:
I am trying to trim leading whitespaces from the string and I do not know what is wrong with my approach, any suggestions would be appreciated ?

Code:

this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();

am reading poNumber from csv file as "     IG078565 and IG083060 " and output also am getting same value with same whitespaces, not sure why ?

Updated

Adding complete method for better context:

public BillingDTO(String currency, String migrationId, String chargeId, String priceId, String poNumber, String otc,
            String billingClassId, String laborOnly) {
        super();
        this.currency = currency.equals("") ? currency : currency.trim();
        this.migrationId = migrationId.equals("") ? migrationId : migrationId.trim();
        this.chargeId = chargeId.equals("") ? chargeId : chargeId.trim();
        this.priceId = priceId.equals("") ? priceId : priceId.trim();
        this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
            //poNumber.trim();
        //System.out.println("poNumber:"+this.poNumber.trim());
        //this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
        this.otc = otc.equals("") ? otc : otc.trim();
        this.billingClassId = billingClassId.equals("") ? billingClassId : billingClassId.trim();
        this.laborOnly = laborOnly.equals("") ? "N" : laborOnly;
    }

Thanks.

Body:
Update It appears your whitespace is not a whitespace (ascii=32). Yours is with code 160, which is a no-breaking space. trim() does not handle it. So you must do something like this:

this.poNumber = poNumber.replace(String.valueOf((char) 160), " ").trim();

You'd better create an utility - YourStringUtils.trim(string) and there perform the two operations - both .trim() and the replace(..)

Original answer:

Just use this.poNumber = poNumber.trim();

If there is a possibility for poNumber to be null, then you can use the null-safe this.poNumber = StringUtils.trim(poNumber); from commons-lang.

You can also use trimToEmpty(..) from the same class, if you want null to be transformed to an empty string.

If you don't want to rely on commons-lang, then just add an if-clause:

if (poNumber != null) {
    this.poNumber = poNumber.trim();
}

As noted in the comments under the question - make sure you are checking the right variable after the trimming. You should check the instance variable. Your parameter (or local variable, I can't tell) does not change, because strings are immutable.


问:
Regex to disallow all symbols that windows doesnt allow in its file/folder names
The symbols not allowed in filename or folder name in windows are \ / : * ? " < > |. I wrote a regex for it but not able to write regex to exclude " (double quotes).

```<code>Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|]+$");
</code>```

Tried as below but it didnt work:

```<code>Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|"]+$");
</code>```

EDIT:
I am particularly looking for code with regex itself and hence its not a duplicate.

Help is greatly appreciated. Thanks.

答:
Instead of using Regex you could do something like this:</p>

```<code>var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
var invalid = input.Any(chr => invalidChars.Contains(chr));
</code>```

Body:
The symbols not allowed in filename or folder name in windows are \ / : * ? " < > |. I wrote a regex for it but not able to write regex to exclude " (double quotes).

Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|]+$");

Tried as below but it didnt work:

Regex regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|"]+$");

EDIT:
I am particularly looking for code with regex itself and hence its not a duplicate.

Help is greatly appreciated. Thanks.

Body:
Instead of using Regex you could do something like this:

var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
var invalid = input.Any(chr => invalidChars.Contains(chr));


问:
How to check if entity changed in Doctrine 2?
I need to check if a persisted entity has changed and needs to be updated on the database.
What I made (and did not work) was the following:

```<code>$product = $entityManager->getRepository('Product')->find(3);
$product->setName('A different name');

var_export($entityManager->getUnitOfWork()->isScheduledForUpdate($product));
</code>```

That code prints always false, I also tried to flush before check the unit of work, but did not work.

Anyone has a suggestion?

答:
Based on my needs, answers here and the docs, I came up with the following solution for a modifiedAt timestamp in an Entity.

```<code>/**
 * @Doctrine\ORM\Mapping\PreUpdate()
 *
 * @param \Doctrine\ORM\Event\PreUpdateEventArgs $args
 * @return $this
 */
public function preUpdateModifiedAt(\Doctrine\ORM\Event\PreUpdateEventArgs $args)
{
    $this->setModifiedAt(new \DateTime('now'));

    return $this;
}
</code>```

This is based on what the docs say about this Event as opposed to the other available ones, such as PostPersist and PreFlush:

PreUpdate is the most restrictive to use event, since it is called
  right before an update statement is called for an entity inside the
  EntityManager#flush() method. Note that this event is not triggered
  when the computed changeset is empty.

Using PreUpdate as opposed to the others lets you leave all the computations and calculation intensive functions to the process already defined by Doctrine. Manually triggering computation of changesets, such as in these answers above are server CPU intensive. The onFlush Event, such as used in the accepted answer is an option (in the way demonstrated), but not if you rely on detecting a change to the Entity, as you can with the function above (preUpdateModifiedAt(PreUpdateEventArgs $args)).

Body:
I need to check if a persisted entity has changed and needs to be updated on the database.
What I made (and did not work) was the following:

$product = $entityManager->getRepository('Product')->find(3);
$product->setName('A different name');

var_export($entityManager->getUnitOfWork()->isScheduledForUpdate($product));

That code prints always false, I also tried to flush before check the unit of work, but did not work.

Anyone has a suggestion?

Body:
Based on my needs, answers here and the docs, I came up with the following solution for a modifiedAt timestamp in an Entity.

/**
 * @Doctrine\ORM\Mapping\PreUpdate()
 *
 * @param \Doctrine\ORM\Event\PreUpdateEventArgs $args
 * @return $this
 */
public function preUpdateModifiedAt(\Doctrine\ORM\Event\PreUpdateEventArgs $args)
{
    $this->setModifiedAt(new \DateTime('now'));

    return $this;
}

This is based on what the docs say about this Event as opposed to the other available ones, such as PostPersist and PreFlush:

PreUpdate is the most restrictive to use event, since it is called
  right before an update statement is called for an entity inside the
  EntityManager#flush() method. Note that this event is not triggered
  when the computed changeset is empty.

Using PreUpdate as opposed to the others lets you leave all the computations and calculation intensive functions to the process already defined by Doctrine. Manually triggering computation of changesets, such as in these answers above are server CPU intensive. The onFlush Event, such as used in the accepted answer is an option (in the way demonstrated), but not if you rely on detecting a change to the Entity, as you can with the function above (preUpdateModifiedAt(PreUpdateEventArgs $args)).


问:
Angular material Could not find Angular Material core theme
In my Angular2 project I install lastest material plugin from https://material.angular.io/guide/getting-started. Next I add @import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; to my css file for my component. But in my console Angular shows this error:

material.es5.js:148 Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.angular.io/guide/theming`

The material components not working.
Whats wrong?

答:
Add:

@import "~@angular/material/prebuilt-themes/indigo-pink.css"

to your style.css


问:
WebSphere wsadmin: Override Session Management For Specific Web Module in Application
I have a WebSphere application called "Acme" which has 4 Web Modules ("acme1", "acme2", "acme3" and "acme4". I need to do the following for ONLY acme2, i.e only one of the 4 web modules.

Override the session management.

Disable "Set session cookies to HTTP Only to help prevent cross-site scripting attacks"

So, far I've only figured out how to override the session management at the application level through the below snippet, but not at the webmodule level.

```<code>application = AdminConfig.getid('/Deployment:Acme/')
mainObject = AdminConfig.showAttribute(application, 'deployedObject')
SessionManagerAttrs = [['sessionManagement', [['enable', 'true'], ['defaultCookieSettings', [['path','/'], ['useContextRootAsPath', 'false'], ['name', 'JSESSIONID'], ['httpOnly', 'false']]]]]]

AdminConfig.create('ApplicationConfig', mainObject, SessionManagerAttrs)
</code>```

Any ideas?

答: This IBM KnowledgeCenter topic explains how to set session management attributes at the web module level using wsadmin scripting.</p>

Body:
I have a WebSphere application called "Acme" which has 4 Web Modules ("acme1", "acme2", "acme3" and "acme4". I need to do the following for ONLY acme2, i.e only one of the 4 web modules.

Override the session management.

Disable "Set session cookies to HTTP Only to help prevent cross-site scripting attacks"

So, far I've only figured out how to override the session management at the application level through the below snippet, but not at the webmodule level.

application = AdminConfig.getid('/Deployment:Acme/')
mainObject = AdminConfig.showAttribute(application, 'deployedObject')
SessionManagerAttrs = [['sessionManagement', [['enable', 'true'], ['defaultCookieSettings', [['path','/'], ['useContextRootAsPath', 'false'], ['name', 'JSESSIONID'], ['httpOnly', 'false']]]]]]

AdminConfig.create('ApplicationConfig', mainObject, SessionManagerAttrs)

Any ideas?


问:
ui5 binding items to TableRows instead of TableColumns
I have an object and I am binding it to my table, but however normally, as I see everywhere the binding is working like ; you bind your things to the  columns.

Could I somehow change it  to be bound to Rows ?

What I know I can do  and always used to do  is ;

In my View :

```<code>    var vergleichTable1 = new sap.m.Table(this.createId("vergleichTable1"), {

        columns: [
            new sap.m.Column({
                header: new sap.m.Label({
                    text: "Header Text 1"
                })
            }),
            new sap.m.Column({
                header: new sap.m.Label({
                    text: "Header Text 2"
                })
            }),
            new sap.m.Column({
                header: new sap.m.Label({
                    text: "Header Text 3"
                })
            }),
        ]
    }).addStyleClass("vergleichTable1");
</code>```

and I was adding sth. like this into my  Controller ;

```<code>        var oTemplate1 = new sap.m.ColumnListItem({
            cells: [
                new sap.m.Text({
                    text:  "{KEYNAME}"
                }),
                new sap.m.Text({
                    text:  "{KEYNAME}"
                }),
                new sap.m.Text({
                    text:  "{KEYNAME}"
                })
            ]
        });
</code>```

and for conencting :

```<code>this.byId("vergleichTable1").setModel(mymodel).bindItems("/foo/0", oTemplate1);
</code>```

However as I mentioned i need something different .  I want to bind it not to columns  but to rows, there is no information about it in the ui5 API.

Here is something to make it more understandable what I need

And I want to have  as much as columns as my object keys.length

How can I do this ?

答:
If I've understood the problem, below is the result you want:(please notify if not so I can correct/delete my answer). Best if you can paste your sample data.

First: Data:

```<code>var selProps = [
        "Prop1", "Prop2", "Prop3" // Selected Properties stored in an array
    ];
    var data = [ // Data, data, data ( with all properties)
        {
            phone:"Moto G",
            "Prop1": "Prop1-1",
            "Prop2" :"Prop1-2",
            "Prop3": "Prop1-3",
            "Prop4" :"Prop1-4"
        },
        {
            phone:"Moto X",
            "Prop1": "Prop2-1",
            "Prop2" :"Prop2-2",
            "Prop3": "Prop2-3",
            "Prop4" :"Prop2-4"
        },
        {
            phone:"iPhone",
            "Prop1": "Prop3-1",
            "Prop2" :"Prop3-2",
            "Prop3": "Prop3-3",
            "Prop4" :"Prop3-4"
        },
        {
            phone:"G Pixel 2",
            "Prop1": "Prop4-1",
            "Prop2" :"Prop4-2",
            "Prop3": "Prop4-3",
            "Prop4" :"Prop4-4"
        }

    ];
</code>```

Output :

Code:
View:

```<code>var oTable =  new sap.m.Table();
    var oColTemplate = new sap.m.Column({
        header: new sap.m.Text({
            text: "{phone}"
        })
    });
    oTable.bindAggregation("columns", "/data", oColTemplate);

    oTable.bindItems("/selProps", function(sId, oContext) {
        var aCells = [];
        var oModel = oContext.getModel();
        var aCols = oModel.getProperty("/data"); // Fetch No of columns. Create that many Texts.
        for (var index = 0 ;index < aCols.length; index++) {
            // data will be stored in : /data/index/selected Property(present in oContext)

             var oText = new sap.m.Text({
                 text : "{/data/" + index + "/" + oContext.getProperty() +"}"
             });
             aCells.push(oText);
        }

        return new sap.m.ColumnListItem({
            cells: aCells
        });
    }.bind(oTable));

    return new sap.m.Page({
        title: "Title",
        content: [
            oTable
        ]
    });
</code>```

Controller :

```<code>onInit: function() {

    var selProps = [
        "Prop1", "Prop2", "Prop3" // Selected Properties stored in an array
    ];
    var data = [ // Data, data, data ( with all properties)
        {
            phone:"Moto G",
            "Prop1": "Prop1-1",
            "Prop2" :"Prop1-2",
            "Prop3": "Prop1-3",
            "Prop4" :"Prop1-4"
        },
        {
            phone:"Moto X",
            "Prop1": "Prop2-1",
            "Prop2" :"Prop2-2",
            "Prop3": "Prop2-3",
            "Prop4" :"Prop2-4"
        },
        {
            phone:"iPhone",
            "Prop1": "Prop3-1",
            "Prop2" :"Prop3-2",
            "Prop3": "Prop3-3",
            "Prop4" :"Prop3-4"
        },
        {
            phone:"G Pixel 2",
            "Prop1": "Prop4-1",
            "Prop2" :"Prop4-2",
            "Prop3": "Prop4-3",
            "Prop4" :"Prop4-4"
        }

    ];

    var oModel =  new sap.ui.model.json.JSONModel({data: data, selProps: selProps});
    this.getView().setModel(oModel);
},
</code>```

Read more about Factory Functions : Factory Functions

Update: To show empty column and row.

Step 1: To Add empty Column :

Now, in above example we bind of columns directly to the data present. This will change as extra columns( at the start) has to be added.

So, paste this where the data is read ( in my Example below setting of manual JSON Data). Remember this has to be done every time new data is read:

new INIT function :

```<code>onInit: function() {

    var selProps = [
        ...// same as above: To reduce post length
    ];
    var data = [ ...// same as above: To reduce post length];

    var oModel =  new sap.ui.model.json.JSONModel({data: data, selProps: selProps});
    this.getView().setModel(oModel);

    this.fnBindColumns(); // Call function to create columns

},

fnBindColumns : function() {
    var oTable = this.byId('idTable');
    var aData = this.getView().getModel().getProperty("/data");

    var oPropCol = new sap.m.Column({
            header: new sap.m.Text({
            text: ""
        })
    });

    oTable.addColumn(oPropCol);

    for(var i = 0; i <aData.length ; i++ ) {
        var oCol = new sap.m.Column({
            header: new sap.m.Text({
                text : "{/data/" + i + "/phone}"
            })
        });
        oTable.addColumn(oCol);
    }
}
</code>```

Step 2: Add property Row. This forces change to our factory function. So, in create content of our JS view:

```<code>    var oTable =  new sap.m.Table({
        id: this.createId("idTable") // Look Id added
    });

    oTable.bindItems("/selProps", function(sId, oContext) {
        var aCells = [];
        var oModel = oContext.getModel();
        var aCols = oModel.getProperty("/data");
        for (var index = 0 ;index < aCols.length + 1; index++) { // length = no of mobile phones + 1 ( +1 for extra property row).
            if (index == 0) { // add the property Text if first column
                var oText = new sap.m.Text({
                     text : oContext.getProperty()
                 });
            } else {
                var oText = new sap.m.Text({
                     text : "{/data/" + (index-1) + "/" + oContext.getProperty() +"}" // bind the text via absolute path.
                });
            }

             aCells.push(oText);
        }

        return new sap.m.ColumnListItem({
            cells: aCells
        });
    }.bind(oTable));
</code>```

New Table:

Hope this helps.

Body:
I have an object and I am binding it to my table, but however normally, as I see everywhere the binding is working like ; you bind your things to the  columns.

Could I somehow change it  to be bound to Rows ?

What I know I can do  and always used to do  is ;

In my View :

    var vergleichTable1 = new sap.m.Table(this.createId("vergleichTable1"), {

        columns: [
            new sap.m.Column({
                header: new sap.m.Label({
                    text: "Header Text 1"
                })
            }),
            new sap.m.Column({
                header: new sap.m.Label({
                    text: "Header Text 2"
                })
            }),
            new sap.m.Column({
                header: new sap.m.Label({
                    text: "Header Text 3"
                })
            }),
        ]
    }).addStyleClass("vergleichTable1");

and I was adding sth. like this into my  Controller ;

        var oTemplate1 = new sap.m.ColumnListItem({
            cells: [
                new sap.m.Text({
                    text:  "{KEYNAME}"
                }),
                new sap.m.Text({
                    text:  "{KEYNAME}"
                }),
                new sap.m.Text({
                    text:  "{KEYNAME}"
                })
            ]
        });

and for conencting :

this.byId("vergleichTable1").setModel(mymodel).bindItems("/foo/0", oTemplate1);

However as I mentioned i need something different .  I want to bind it not to columns  but to rows, there is no information about it in the ui5 API.

Here is something to make it more understandable what I need

And I want to have  as much as columns as my object keys.length

How can I do this ?

Body:
If I've understood the problem, below is the result you want:(please notify if not so I can correct/delete my answer). Best if you can paste your sample data.

First: Data:

var selProps = [
        "Prop1", "Prop2", "Prop3" // Selected Properties stored in an array
    ];
    var data = [ // Data, data, data ( with all properties)
        {
            phone:"Moto G",
            "Prop1": "Prop1-1",
            "Prop2" :"Prop1-2",
            "Prop3": "Prop1-3",
            "Prop4" :"Prop1-4"
        },
        {
            phone:"Moto X",
            "Prop1": "Prop2-1",
            "Prop2" :"Prop2-2",
            "Prop3": "Prop2-3",
            "Prop4" :"Prop2-4"
        },
        {
            phone:"iPhone",
            "Prop1": "Prop3-1",
            "Prop2" :"Prop3-2",
            "Prop3": "Prop3-3",
            "Prop4" :"Prop3-4"
        },
        {
            phone:"G Pixel 2",
            "Prop1": "Prop4-1",
            "Prop2" :"Prop4-2",
            "Prop3": "Prop4-3",
            "Prop4" :"Prop4-4"
        }

    ];

Output :

Code:
View:

var oTable =  new sap.m.Table();
    var oColTemplate = new sap.m.Column({
        header: new sap.m.Text({
            text: "{phone}"
        })
    });
    oTable.bindAggregation("columns", "/data", oColTemplate);

    oTable.bindItems("/selProps", function(sId, oContext) {
        var aCells = [];
        var oModel = oContext.getModel();
        var aCols = oModel.getProperty("/data"); // Fetch No of columns. Create that many Texts.
        for (var index = 0 ;index < aCols.length; index++) {
            // data will be stored in : /data/index/selected Property(present in oContext)

             var oText = new sap.m.Text({
                 text : "{/data/" + index + "/" + oContext.getProperty() +"}"
             });
             aCells.push(oText);
        }

        return new sap.m.ColumnListItem({
            cells: aCells
        });
    }.bind(oTable));

    return new sap.m.Page({
        title: "Title",
        content: [
            oTable
        ]
    });

Controller :

onInit: function() {

    var selProps = [
        "Prop1", "Prop2", "Prop3" // Selected Properties stored in an array
    ];
    var data = [ // Data, data, data ( with all properties)
        {
            phone:"Moto G",
            "Prop1": "Prop1-1",
            "Prop2" :"Prop1-2",
            "Prop3": "Prop1-3",
            "Prop4" :"Prop1-4"
        },
        {
            phone:"Moto X",
            "Prop1": "Prop2-1",
            "Prop2" :"Prop2-2",
            "Prop3": "Prop2-3",
            "Prop4" :"Prop2-4"
        },
        {
            phone:"iPhone",
            "Prop1": "Prop3-1",
            "Prop2" :"Prop3-2",
            "Prop3": "Prop3-3",
            "Prop4" :"Prop3-4"
        },
        {
            phone:"G Pixel 2",
            "Prop1": "Prop4-1",
            "Prop2" :"Prop4-2",
            "Prop3": "Prop4-3",
            "Prop4" :"Prop4-4"
        }

    ];

    var oModel =  new sap.ui.model.json.JSONModel({data: data, selProps: selProps});
    this.getView().setModel(oModel);
},

Read more about Factory Functions : Factory Functions

Update: To show empty column and row.

Step 1: To Add empty Column :

Now, in above example we bind of columns directly to the data present. This will change as extra columns( at the start) has to be added.

So, paste this where the data is read ( in my Example below setting of manual JSON Data). Remember this has to be done every time new data is read:

new INIT function :

onInit: function() {

    var selProps = [
        ...// same as above: To reduce post length
    ];
    var data = [ ...// same as above: To reduce post length];

    var oModel =  new sap.ui.model.json.JSONModel({data: data, selProps: selProps});
    this.getView().setModel(oModel);

    this.fnBindColumns(); // Call function to create columns

},

fnBindColumns : function() {
    var oTable = this.byId('idTable');
    var aData = this.getView().getModel().getProperty("/data");

    var oPropCol = new sap.m.Column({
            header: new sap.m.Text({
            text: ""
        })
    });

    oTable.addColumn(oPropCol);

    for(var i = 0; i <aData.length ; i++ ) {
        var oCol = new sap.m.Column({
            header: new sap.m.Text({
                text : "{/data/" + i + "/phone}"
            })
        });
        oTable.addColumn(oCol);
    }
}

Step 2: Add property Row. This forces change to our factory function. So, in create content of our JS view:

    var oTable =  new sap.m.Table({
        id: this.createId("idTable") // Look Id added
    });

    oTable.bindItems("/selProps", function(sId, oContext) {
        var aCells = [];
        var oModel = oContext.getModel();
        var aCols = oModel.getProperty("/data");
        for (var index = 0 ;index < aCols.length + 1; index++) { // length = no of mobile phones + 1 ( +1 for extra property row).
            if (index == 0) { // add the property Text if first column
                var oText = new sap.m.Text({
                     text : oContext.getProperty()
                 });
            } else {
                var oText = new sap.m.Text({
                     text : "{/data/" + (index-1) + "/" + oContext.getProperty() +"}" // bind the text via absolute path.
                });
            }

             aCells.push(oText);
        }

        return new sap.m.ColumnListItem({
            cells: aCells
        });
    }.bind(oTable));

New Table:

Hope this helps.


问:
IIS C# Rewriter
I have just started looking at URL the Rewriter module in IIS.

The code below is what I have that works (It removes www from all the URLs to the site)

```<code><rewrite>
  <rules>
    <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
   <match url="*" />
   <conditions>
      <add input="{CACHE_URL}" pattern="*://www.*" />
   </conditions>
  <action type="Redirect" url="{C:1}://{C:2}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</code>```

However, we have a third party API that posts to http://www.example.com/api/controller/method that no longer works. (It is being served 405's)

The problem is (I believe) that whilst WebAPI allows www.example.com/api/controller/method to POST, it is seeing example.com/api/controller/method as a different URL and is not allowing POST.

However the followingconfig section does not work. (Note, removing the wildcard section means it does work, so I am as convinced as I can be that it is this that is causing the 3rd Party to fail). Though testing the PassAPICall in IIS in the configure rewriting section passes. Is it that I have misunderstood the intent of stopProcessing, and in fact all it does is stop processing for that rule, so it then falls throug hto the following condition?

```<code><rules>
            <clear />
            <rule name="PassAPICall" stopProcessing="true">
                <match url="/api/Blah/QuotationComplete" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
                <action type="None" />
            </rule>

 <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{CACHE_URL}" pattern="*://www.*" />
                </conditions>
                <action type="Redirect" url="{C:1}://{C:2}" redirectType="Permanent" />
            </rule>

</rules>
</code>```

答:
Was a simple syntax issue, I needed to be a little more explicit with the Rule than the IIS test tool led me to believe.

changing

```<code> <match url="/api/Blah/QuotationComplete" />
</code>```

to

```<code>  <match url="^api/Blah/QuotationComplete$" />
</code>```

did it.

Title: IIS C# Rewriter

Body:
I have just started looking at URL the Rewriter module in IIS.

The code below is what I have that works (It removes www from all the URLs to the site)

<rewrite>
  <rules>
    <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
   <match url="*" />
   <conditions>
      <add input="{CACHE_URL}" pattern="*://www.*" />
   </conditions>
  <action type="Redirect" url="{C:1}://{C:2}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>

However, we have a third party API that posts to http://www.example.com/api/controller/method that no longer works. (It is being served 405's)

The problem is (I believe) that whilst WebAPI allows www.example.com/api/controller/method to POST, it is seeing example.com/api/controller/method as a different URL and is not allowing POST.

However the followingconfig section does not work. (Note, removing the wildcard section means it does work, so I am as convinced as I can be that it is this that is causing the 3rd Party to fail). Though testing the PassAPICall in IIS in the configure rewriting section passes. Is it that I have misunderstood the intent of stopProcessing, and in fact all it does is stop processing for that rule, so it then falls throug hto the following condition?

<rules>
            <clear />
            <rule name="PassAPICall" stopProcessing="true">
                <match url="/api/Blah/QuotationComplete" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
                <action type="None" />
            </rule>

 <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
                <match url="*" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{CACHE_URL}" pattern="*://www.*" />
                </conditions>
                <action type="Redirect" url="{C:1}://{C:2}" redirectType="Permanent" />
            </rule>

</rules>

Body:
Was a simple syntax issue, I needed to be a little more explicit with the Rule than the IIS test tool led me to believe.

changing

 <match url="/api/Blah/QuotationComplete" />

to

  <match url="^api/Blah/QuotationComplete$" />

did it.