问:
After login redirect to different page with session and after log out destroy the session
I made a login page , after login click it redirect to another page(index) , now index page have different page connected with  code  , now I want when I logout the page it should  destroy the index page and related page  until user again login.

here is code of my login

```<code><?php
if(isset($_POST['submit']))
{
    $user=$_POST['user'];
    $password=$_POST['password'];
    $query="select * from users";
    $con=mysqli_connect('localhost','root','','fileprogramsysteeem');
    $run=mysqli_query($con,$query);
    if(mysqli_num_rows($run)>0)
    {
        if($row=mysqli_fetch_array($run))
        {
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password)
            {
                if(isset($_POST['remember']))
                {
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "<script> window.location.assign('../index.php'); </script>";
                exit();
            }
            else
            {
               echo"<script>alert('incorrect user name or password')</script>";
               echo "<script> window.location.assign('login.php'); </script>";
            }
        }
    }
    else
    {
        echo"<script>alert('incorrect user name or password')</script>";
    }

}
?>
</code>```

and this is my logout page code , I wanted when user click logout the it should destroy the index part and all the related page with index , how to write that code ,

```<code><?php
session_start();
if(isset($_COOKIE['user']) and isset($_COOKIE['password']))
{
    $user=$_COOKIE['user'];
    $password=$_COOKIE['password'];
    setcookie('user',$user,time()-1);
    setcookie('password',$password,time()-1);
 }
header("location:./login.php");
exit();
?>
</code>```

help me please.

How I use session_destroy() so when I click the logout, Then it should destroy the index page until user again login.

here is index code

```<code><?php require_once('inc/top.php');?>
    <body>
        <div id="wrapper">
            <?php require_once('inc/header.php');
            $total_num_page=2;
            if (isset($_GET['page'])){$page_id = $_GET['page'];}
            else{$page_id = 1;}
            $search = '' ;
            if(isset($_POST['search'])){$search = urldecode($_POST['search']);}
            else if( isset($_GET['search'])){$search = urldecode($_GET['search']);}
            if ($search){
                $all_post_query = "SELECT COUNT(*)
                FROM files
                WHERE recieved_by LIKE '%".$search."%'
                OR processed_by LIKE '%".$search."%'
                OR purpose LIKE '%".$search."%'
                OR file_name LIKE '%".$search."%'
                ORDER BY date DESC";
                $all_stmt=$db->prepare($all_post_query);
                $all_stmt->execute();
                $all_post=$all_stmt->fetch();
                $total_page = ceil($all_post / $total_num_page);
                $page_start_from = ($page_id - 1) * $total_num_page;
            }
            else {
                $all_post_query = "SELECT COUNT(*) FROM files ORDER BY date DESC";
                $all_stmt=$db->prepare($all_post_query);
                $all_stmt->execute();
                $all_post=$all_stmt->fetch();
                $total_page = ceil($all_post / $total_num_page);
                $page_start_from = ($page_id - 1) * $total_num_page;
            }
            ?>
            <div class="container-fluid body-section " style="margin-top:90px;margin-bottom:300px;">
                <div class="row">
                    <div class="col-xs-12 col-sm-12 col-md-12">
                        <h1><i class="fa fa-hand-o-down" aria-hidden="true"> File List </i></h1>
                        <a href="letterfile.php">
                            <button type="button" style=" margin-left:190px; margin-top:-70px;" class="btn btn-primary">
                                <i class="fa fa-envelope-o" aria-hidden="true">Case for Letter</i>
                            </button>
                        </a>
                        <a href="callfile.php">
                            <button type="button" class="btn btn-default" style=" margin-left:210px; margin-top:-70px; background:#880E4F;">
                                <i class="fa fa-phone-square"aria-hidden="true" style="color:white;">
                                    <font color="white">Case for Call</font>
                                </i>
                            </button>
                        </a>
                        <a href="dustbinfile.php">
                            <button type="button" class="btn btn-danger" style=" margin-left:150px; margin-top:-70px;">
                                <i class="fa fa-book" aria-hidden="true">Filed Case</i>
                            </button>
                        </a>
                        <div class="col-md-4 col-md-offset-7 search-box">
                            <form  action="index.php" class="search-form" method="post">
                                <div class="form-group has-feedbacck">
                                    <label for="search" class="sr-only">Search:</label>
                                    <input type="text" class="form-control" name="search" id="search" placeholder="Search Here" />
                                    <input type="submit" class="Goform" name="submitSearch" value="Go!"/>
                                    <span class="glyphicon glyphicon-search form-control-feedback"></span>
                                </div>
                            </form>
                        </div><hr />
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>File-name</th>
                                    <th>Purpose</th>
                                    <th>Recieved-By </th>
                                    <th>Processed-By</th>
                                    <th>Adress</th>
                                    <th>Contact-No</th>
                                    <th>Date</th>
                                    <th>Update</th>
                                </tr>
                            </thead>
                            <tbody><?php if($search){
                                $stmt=$con->prepare("SELECT * FROM files WHERE recieved_by LIKE '%$search%' OR processed_by LIKE '%$search%' OR purpose LIKE '%$search%' OR file_name LIKE '%$search%' ORDER BY date DESC LIMIT $page_start_from, $total_num_page");
                                }
                                else{$stmt=$con->prepare("select * from files order by date desc limit $page_start_from, $total_num_page");}
                                if($stmt->execute()){
                                    while($row=$stmt->fetch()){
                                        $c_id=$row['id'];
                                        $file=$row['file_name'];
                                        $purpose=$row['purpose'];
                                        $recieve=$row['recieved_by'];
                                        $processed=$row['processed_by'];
                                        $address=$row['address'];
                                        $contact=$row['contact_no'];
                                        $date=$row['date'];
                                    ?>
                                <tr>
                                    <td><a  href="post.php?post_id=<?php echo $c_id?>"><?php echo $c_id;?></a></td>
                                    <td><a href="post.php?post_id=<?php echo $c_id?>"><?php echo $file;?></a></td>
                                    <td><a href="post.php?post_id=<?php echo $c_id?>"><?php echo $purpose;?></a></td>
                                    <td><a href="post.php?post_id=<?php echo $c_id?>"><?php echo $recieve;?></a></td>
                                    <td><a href="post.php?post_id=<?php echo $c_id?>"><?php echo $processed;?></a></td>
                                    <td><a href="post.php?post_id=<?php echo $c_id?>"><?php echo $address;?></a></td>
                                    <td><a href="post.php?post_id=<?php echo $c_id?>"><?php echo $contact;?></a></td>
                                    <td><a href="post.php?post_id=<?php echo $c_id?>"><?php echo $date;?></a></td>
                                </tr>
                                <?php
                                    }
                                }
                                else{
                                    echo "No Related File Found Here ";
                                }
                                ?>
                            </tbody>
                        </table>
                    <nav id="pagination">
                        <ul class="pagination">
                        <?php
                            $search_str = '';
                            if($search){
                                $search_str = "&search=" . urlencode($search);
                            }
                            for ($i=1;$i<=$total_page;$i++)echo "
                            <li class='".($page_id == $i ? 'active' : '')."'><a href='index.php?page=" . $i . $search_str . "'>$i</a></li>";
                        ?>
                        </ul>
                   </nav>
               </div>
           </div>
       </div>
       <?php require_once('inc/footer.php');?>
</code>```

答:
To destroy the session you can easily use session_destroy() function. Then you have to do is make every other pages restricted for others (Only accessible logged users). to do that you can use these kind of php code to the top of each page.

```<code><?php
session_start();
//This will check that user is logged in or not
if(!isset($_SESSION['user'])
{
   //this will redirect user to log in page if he is not logged user
   header("location:./login.php");
}
?>
</code>```

If some one trying to access the page without log in, there is nothing on $_SESSION['user']. So it will redirect to log in page.

(If you want mare security check session variable with your database each time)

Body:
I made a login page , after login click it redirect to another page(index) , now index page have different page connected with  code  , now I want when I logout the page it should  destroy the index page and related page  until user again login.

here is code of my login

<?php
if(isset($_POST['submit']))
{
    $user=$_POST['user'];
    $password=$_POST['password'];
    $query="select * from users";
    $con=mysqli_connect('localhost','root','','fileprogramsysteeem');
    $run=mysqli_query($con,$query);
    if(mysqli_num_rows($run)>0)
    {
        if($row=mysqli_fetch_array($run))
        {
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password)
            {
                if(isset($_POST['remember']))
                {
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "";
                exit();
            }
            else
            {
               echo"";
               echo "";
            }
        }
    }
    else
    {
        echo"";
    }

}
?>

and this is my logout page code , I wanted when user click logout the it should destroy the index part and all the related page with index , how to write that code ,

<?php
session_start();
if(isset($_COOKIE['user']) and isset($_COOKIE['password']))
{
    $user=$_COOKIE['user'];
    $password=$_COOKIE['password'];
    setcookie('user',$user,time()-1);
    setcookie('password',$password,time()-1);
 }
header("location:./login.php");
exit();
?>

help me please.

How I use session_destroy() so when I click the logout, Then it should destroy the index page until user again login.

here is index code

<?php require_once('inc/top.php');?>

            <?php require_once('inc/header.php');
            $total_num_page=2;
            if (isset($_GET['page'])){$page_id = $_GET['page'];}
            else{$page_id = 1;}
            $search = '' ;
            if(isset($_POST['search'])){$search = urldecode($_POST['search']);}
            else if( isset($_GET['search'])){$search = urldecode($_GET['search']);}
            if ($search){
                $all_post_query = "SELECT COUNT(*)
                FROM files
                WHERE recieved_by LIKE '%".$search."%'
                OR processed_by LIKE '%".$search."%'
                OR purpose LIKE '%".$search."%'
                OR file_name LIKE '%".$search."%'
                ORDER BY date DESC";
                $all_stmt=$db->prepare($all_post_query);
                $all_stmt->execute();
                $all_post=$all_stmt->fetch();
                $total_page = ceil($all_post / $total_num_page);
                $page_start_from = ($page_id - 1) * $total_num_page;
            }
            else {
                $all_post_query = "SELECT COUNT(*) FROM files ORDER BY date DESC";
                $all_stmt=$db->prepare($all_post_query);
                $all_stmt->execute();
                $all_post=$all_stmt->fetch();
                $total_page = ceil($all_post / $total_num_page);
                $page_start_from = ($page_id - 1) * $total_num_page;
            }
            ?>

 File List

                            <button type="button" style=" margin-left:190px; margin-top:-70px;" class="btn btn-primary">
                                Case for Letter
                            </button>

                            <button type="button" class="btn btn-default" style=" margin-left:210px; margin-top:-70px; background:#880E4F;">

                                    Case for Call

                            </button>

                            <button type="button" class="btn btn-danger" style=" margin-left:150px; margin-top:-70px;">
                                Filed Case
                            </button>

                            <form  action="index.php" class="search-form" method="post">

                                    Search:
                                    <input type="text" class="form-control" name="search" id="search" placeholder="Search Here" />
                                    <input type="submit" class="Goform" name="submitSearch" value="Go!"/>

                            </form>

                                    Id
                                    File-name
                                    Purpose
                                    Recieved-By
                                    Processed-By
                                    Adress
                                    Contact-No
                                    Date
                                    Update

<?php if($search){
                                $stmt=$con->prepare("SELECT * FROM files WHERE recieved_by LIKE '%$search%' OR processed_by LIKE '%$search%' OR purpose LIKE '%$search%' OR file_name LIKE '%$search%' ORDER BY date DESC LIMIT $page_start_from, $total_num_page");
                                }
                                else{$stmt=$con->prepare("select * from files order by date desc limit $page_start_from, $total_num_page");}
                                if($stmt->execute()){
                                    while($row=$stmt->fetch()){
                                        $c_id=$row['id'];
                                        $file=$row['file_name'];
                                        $purpose=$row['purpose'];
                                        $recieve=$row['recieved_by'];
                                        $processed=$row['processed_by'];
                                        $address=$row['address'];
                                        $contact=$row['contact_no'];
                                        $date=$row['date'];
                                    ?>

                                    <a  href="post.php?post_id=<?php echo $c_id?>"><?php echo $c_id;?>
                                    <a href="post.php?post_id=<?php echo $c_id?>"><?php echo $file;?>
                                    <a href="post.php?post_id=<?php echo $c_id?>"><?php echo $purpose;?>
                                    <a href="post.php?post_id=<?php echo $c_id?>"><?php echo $recieve;?>
                                    <a href="post.php?post_id=<?php echo $c_id?>"><?php echo $processed;?>
                                    <a href="post.php?post_id=<?php echo $c_id?>"><?php echo $address;?>
                                    <a href="post.php?post_id=<?php echo $c_id?>"><?php echo $contact;?>
                                    <a href="post.php?post_id=<?php echo $c_id?>"><?php echo $date;?>

                                <?php
                                    }
                                }
                                else{
                                    echo "No Related File Found Here ";
                                }
                                ?>

                        <?php
                            $search_str = '';
                            if($search){
                                $search_str = "&search=" . urlencode($search);
                            }
                            for ($i=1;$i<=$total_page;$i++)echo "

$i
";
                        ?>

       <?php require_once('inc/footer.php');?>

Body:
To destroy the session you can easily use session_destroy() function. Then you have to do is make every other pages restricted for others (Only accessible logged users). to do that you can use these kind of php code to the top of each page.

<?php
session_start();
//This will check that user is logged in or not
if(!isset($_SESSION['user'])
{
   //this will redirect user to log in page if he is not logged user
   header("location:./login.php");
}
?>

If some one trying to access the page without log in, there is nothing on $_SESSION['user']. So it will redirect to log in page.

(If you want mare security check session variable with your database each time)


来源: stackexchange

问:
Wercker deploy returns 404 for docker push
First time with Wercker and I'm using internal/docker-push. When I run my deployment step, I'm getting a 404 error from docker-hub.

```<code>ERROR Error interacting with this repository: wluce/statler-waldorf-corp-team-service PUT https://registry.hub.docker.com/v1/repositories/wluce/statler-waldorf-corp-team-service/ returned 404
</code>```

This isn't the first time I've run this step and it's worked before. The image exists and is here.

I can't figure out what could've changed.

Here is the wercker.yml file I'm using to perform the build and deploy.

```<code>box: microsoft/dotnet:2.0.0-sdk-2.0.2
no-response-timeout: 10
build:
  steps:
    - script:
        name: restore
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet restore
    - script:
        name: build
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet build

    - script:
        name: test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet restore
    - script:
        name: test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet build
    - script:
        name: test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet test

    - script:
        name: integration-test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet restore
    - script:
        name: integration-test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet build
    - script:
        name: integration-test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet test

    - script:
        name: publish
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet publish -o publish
    - script:
        name: copy binary
        cwd: src/StatlerWaldorfCorp.TeamService
        code: cp -r . $WERCKER_OUTPUT_DIR/app

deploy:
  box: microsoft/aspnetcore:2.0.0
  steps:
    - internal/docker-push:
        cwd: $WERCKER_OUTPUT_DIR/app
        username: $DOCKER_USERNAME
        password: $DOCKER_PASSWORD
        repository: wluce/statler-waldorf-corp-team-service
        registry: https://registry.hub.docker.com
        entrypoint: "/pipeline/source/app/docker_entrypoint.sh"
</code>```

答:
In internal/docker-push step,
just add registry with v2 appended to make wercker use v2 registry api like this</p>

```<code>    repository: gapostolov/course-repo
    registry: https://registry.hub.docker.com/v2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
First time with Wercker and I'm using internal/docker-push. When I run my deployment step, I'm getting a 404 error from docker-hub.

ERROR Error interacting with this repository: wluce/statler-waldorf-corp-team-service PUT https://registry.hub.docker.com/v1/repositories/wluce/statler-waldorf-corp-team-service/ returned 404

This isn't the first time I've run this step and it's worked before. The image exists and is here.

I can't figure out what could've changed.

Here is the wercker.yml file I'm using to perform the build and deploy.

box: microsoft/dotnet:2.0.0-sdk-2.0.2
no-response-timeout: 10
build:
  steps:
    - script:
        name: restore
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet restore
    - script:
        name: build
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet build

    - script:
        name: test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet restore
    - script:
        name: test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet build
    - script:
        name: test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet test

    - script:
        name: integration-test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet restore
    - script:
        name: integration-test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet build
    - script:
        name: integration-test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet test

    - script:
        name: publish
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet publish -o publish
    - script:
        name: copy binary
        cwd: src/StatlerWaldorfCorp.TeamService
        code: cp -r . $WERCKER_OUTPUT_DIR/app

deploy:
  box: microsoft/aspnetcore:2.0.0
  steps:
    - internal/docker-push:
        cwd: $WERCKER_OUTPUT_DIR/app
        username: $DOCKER_USERNAME
        password: $DOCKER_PASSWORD
        repository: wluce/statler-waldorf-corp-team-service
        registry: https://registry.hub.docker.com
        entrypoint: "/pipeline/source/app/docker_entrypoint.sh"

Body:
In internal/docker-push step,
just add registry with v2 appended to make wercker use v2 registry api like this

    repository: gapostolov/course-repo
    registry: https://registry.hub.docker.com/v2


问:
Making a string concatenation operator in R
I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.

The easiest way would be to create a special operator using %, like

```<code>`%+%` <- function(a, b) paste(a, b, sep="")
</code>```

but this leads to lots of ugly %'s in the code.

I noticed that + is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?

答: You have given yourself the correct answer -- everything in R is a function, and you cannot define new operators. So %+% is as good as it gets.

ContentLicense: CC BY-SA 2.5

Body:
I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.

The easiest way would be to create a special operator using %, like

`%+%` <- function(a, b) paste(a, b, sep="")

but this leads to lots of ugly %'s in the code.

I noticed that + is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?


问:
Java Appium Android - How to handle sidebar or left panel?
My application which is developed in Cordova. And in automation script, I want to navigate different pages through the sidebar. I am able to locate elements in the sidebar, but don't know why it's not clickable. I tried with locater like id, XPath, accessibility, className, but it's not working.

I tried with coordinates as well, but its x-value in -ve. TouchAction class does not accept -ve value and it's throwing org.openqa.selenium.invalidargumentexception.

ids -
Hamburger Menu - Id = "SA_hm"
Services Menu - Id = "SA_hm_Services"

I tried -

XPath -

//android.widget.ListView[@index='0']/android.view.View[@resource-id='SA_hm_MyDevices']

//android.widget.ListView[@index='0']/android.view.View[@index='2']

答:
I have handled this with following logic -

```<code>Point point = element.getLocation();

int upperY = point.getY();
int lowerY = upperY + element.getSize().getHeight();
int middleY = (upperY + lowerY) / 2;

new TouchAction(((AppiumDriver<MobileElement>) driver)).press(100, middleY).waitAction().release().perform();
</code>```

please suggest someone have the better approach.

Body:
I have handled this with following logic -

Point point = element.getLocation();

int upperY = point.getY();
int lowerY = upperY + element.getSize().getHeight();
int middleY = (upperY + lowerY) / 2;

new TouchAction(((AppiumDriver<MobileElement>) driver)).press(100, middleY).waitAction().release().perform();

please suggest someone have the better approach.


问:
How to create Neo4J relationship between nodes yelp dataset
I am new to Neo4j. I am trying to populate Yelp dataset in Neo4j. Basically, I am interested in three json file provided by them i.e.

user.json

```<code>{
    "user_id": "-lGwMGHMC_XihFJNKCJNRg",
    "name": "Gabe",
    "review_count": 277,
    "yelping_since": "2014-10-31",
    "friends": ["Oa84FFGBw1axX8O6uDkmqg", "SRcWERSl4rhm-Bz9zN_J8g", "VMVGukgapRtx3MIydAibkQ", "8sLNQ3dAV35VBCnPaMh1Lw", "87LhHHXbQYWr5wlo5W7_QQ"],
    "useful": 45,
    "funny": 4,
    "cool": 55,
    "fans": 17,
    "elite": [],
    "average_stars": 4.72,
    "compliment_hot": 5,
    "compliment_more": 1,
    "compliment_profile": 0,
    "compliment_cute": 1,
    "compliment_list": 0,
    "compliment_note": 11,
    "compliment_plain": 20,
    "compliment_cool": 15,
    "compliment_funny": 15,
    "compliment_writer": 1,
    "compliment_photos": 8
}
</code>```

I have omitted several entries from friends array to make output readable

business.json

```<code>{
    "business_id": "YDf95gJZaq05wvo7hTQbbQ",
    "name": "Richmond Town Square",
    "neighborhood": "",
    "address": "691 Richmond Rd",
    "city": "Richmond Heights",
    "state": "OH",
    "postal_code": "44143",
    "latitude": 41.5417162,
    "longitude": -81.4931165,
    "stars": 2.0,
    "review_count": 17,
    "is_open": 1,
    "attributes": {
        "RestaurantsPriceRange2": 2,
        "BusinessParking": {
            "garage": false,
            "street": false,
            "validated": false,
            "lot": true,
            "valet": false
        },
        "BikeParking": true,
        "WheelchairAccessible": true
    },
    "categories": ["Shopping", "Shopping Centers"],
    "hours": {
        "Monday": "10:00-21:00",
        "Tuesday": "10:00-21:00",
        "Friday": "10:00-21:00",
        "Wednesday": "10:00-21:00",
        "Thursday": "10:00-21:00",
        "Sunday": "11:00-18:00",
        "Saturday": "10:00-21:00"
    }
}
</code>```

review.json

```<code>{
    "review_id": "VfBHSwC5Vz_pbFluy07i9Q",
    "user_id": "-lGwMGHMC_XihFJNKCJNRg",
    "business_id": "YDf95gJZaq05wvo7hTQbbQ",
    "stars": 5,
    "date": "2016-07-12",
    "text": "My girlfriend and I stayed here for 3 nights and loved it.",
    "useful": 0,
    "funny": 0,
    "cool": 0
}
</code>```

As we can see in the sample files that relationship between user and business is associated via the review.json file. How can I create a relationship edge between user and business using the review.json file.

I have also seen Mark Needham tutorial where he has shown StackOverflow data population but in that case, relationship file was already present with sample data. Do I need to build a similar file? If yes, how should I approach this problem? or is there any other way to build relationship between user & business?

答:
It very much depends on your model as to what you want to do, but you could do 3 imports:

```<code>//Create Users - does assume the data is unique
CALL apoc.load.json('file:///c://temp//SO//user.json') YIELD value AS user
CREATE (u:User)
SET u = user
</code>```

then add the businesses:

```<code>CALL apoc.load.json('file:///c://temp//SO//business.json') YIELD value AS business
CREATE (b:Business {
            business_id     : business.business_id,
            name            : business.name,
            neighborhood    : business.neighborhood,
            address         : business.address,
            city            : business.city,
            state           : business.state,
            postal_code     : business.postal_code,
            latitude        : business.latitude,
            longitude       : business.longitude,
            stars           : business.stars,
            review_count    : business.review_count,
            is_open         : business.is_open,
            categories      : business.categories
        })
</code>```

For the businesses, we can't just do the SET b = business because the JSON has nested maps. So you might want to decide if you want them, and might have to go down a different route.

Lastly, the reviews, which is where we join it all up.

```<code>CALL apoc.load.json('file:///c://temp//SO//review.json') YIELD value AS review
CREATE (r:Review)
SET r = review
WITH r
//Match user to a review
MATCH (u:User {user_id: r.user_id})
CREATE (u)-[:HAS_REVIEW]->(r)
WITH r, u
//Match business to a review, and a user to a business
MATCH (b:Business {business_id: r.business_id})
//Merge here in case of multiple reviews
MERGE (u)-[:HAS_REVIEWED]->(b)
CREATE (b)-[:HAS_REVIEW]->(r)
</code>```

Obviously - change labels/relationships to types you want, and it might need tuning depending on the size of data etc, so you might need to use apoc.periodic.iterate to work it.

Apoc is here if you need it (and you should use it!)

Body:
I am new to Neo4j. I am trying to populate Yelp dataset in Neo4j. Basically, I am interested in three json file provided by them i.e.

user.json

{
    "user_id": "-lGwMGHMC_XihFJNKCJNRg",
    "name": "Gabe",
    "review_count": 277,
    "yelping_since": "2014-10-31",
    "friends": ["Oa84FFGBw1axX8O6uDkmqg", "SRcWERSl4rhm-Bz9zN_J8g", "VMVGukgapRtx3MIydAibkQ", "8sLNQ3dAV35VBCnPaMh1Lw", "87LhHHXbQYWr5wlo5W7_QQ"],
    "useful": 45,
    "funny": 4,
    "cool": 55,
    "fans": 17,
    "elite": [],
    "average_stars": 4.72,
    "compliment_hot": 5,
    "compliment_more": 1,
    "compliment_profile": 0,
    "compliment_cute": 1,
    "compliment_list": 0,
    "compliment_note": 11,
    "compliment_plain": 20,
    "compliment_cool": 15,
    "compliment_funny": 15,
    "compliment_writer": 1,
    "compliment_photos": 8
}

I have omitted several entries from friends array to make output readable

business.json

{
    "business_id": "YDf95gJZaq05wvo7hTQbbQ",
    "name": "Richmond Town Square",
    "neighborhood": "",
    "address": "691 Richmond Rd",
    "city": "Richmond Heights",
    "state": "OH",
    "postal_code": "44143",
    "latitude": 41.5417162,
    "longitude": -81.4931165,
    "stars": 2.0,
    "review_count": 17,
    "is_open": 1,
    "attributes": {
        "RestaurantsPriceRange2": 2,
        "BusinessParking": {
            "garage": false,
            "street": false,
            "validated": false,
            "lot": true,
            "valet": false
        },
        "BikeParking": true,
        "WheelchairAccessible": true
    },
    "categories": ["Shopping", "Shopping Centers"],
    "hours": {
        "Monday": "10:00-21:00",
        "Tuesday": "10:00-21:00",
        "Friday": "10:00-21:00",
        "Wednesday": "10:00-21:00",
        "Thursday": "10:00-21:00",
        "Sunday": "11:00-18:00",
        "Saturday": "10:00-21:00"
    }
}

review.json

{
    "review_id": "VfBHSwC5Vz_pbFluy07i9Q",
    "user_id": "-lGwMGHMC_XihFJNKCJNRg",
    "business_id": "YDf95gJZaq05wvo7hTQbbQ",
    "stars": 5,
    "date": "2016-07-12",
    "text": "My girlfriend and I stayed here for 3 nights and loved it.",
    "useful": 0,
    "funny": 0,
    "cool": 0
}

As we can see in the sample files that relationship between user and business is associated via the review.json file. How can I create a relationship edge between user and business using the review.json file.

I have also seen Mark Needham tutorial where he has shown StackOverflow data population but in that case, relationship file was already present with sample data. Do I need to build a similar file? If yes, how should I approach this problem? or is there any other way to build relationship between user & business?

Body:
It very much depends on your model as to what you want to do, but you could do 3 imports:

//Create Users - does assume the data is unique
CALL apoc.load.json('file:///c://temp//SO//user.json') YIELD value AS user
CREATE (u:User)
SET u = user

then add the businesses:

CALL apoc.load.json('file:///c://temp//SO//business.json') YIELD value AS business
CREATE (b:Business {
            business_id     : business.business_id,
            name            : business.name,
            neighborhood    : business.neighborhood,
            address         : business.address,
            city            : business.city,
            state           : business.state,
            postal_code     : business.postal_code,
            latitude        : business.latitude,
            longitude       : business.longitude,
            stars           : business.stars,
            review_count    : business.review_count,
            is_open         : business.is_open,
            categories      : business.categories
        })

For the businesses, we can't just do the SET b = business because the JSON has nested maps. So you might want to decide if you want them, and might have to go down a different route.

Lastly, the reviews, which is where we join it all up.

CALL apoc.load.json('file:///c://temp//SO//review.json') YIELD value AS review
CREATE (r:Review)
SET r = review
WITH r
//Match user to a review
MATCH (u:User {user_id: r.user_id})
CREATE (u)-[:HAS_REVIEW]->(r)
WITH r, u
//Match business to a review, and a user to a business
MATCH (b:Business {business_id: r.business_id})
//Merge here in case of multiple reviews
MERGE (u)-[:HAS_REVIEWED]->(b)
CREATE (b)-[:HAS_REVIEW]->(r)

Obviously - change labels/relationships to types you want, and it might need tuning depending on the size of data etc, so you might need to use apoc.periodic.iterate to work it.

Apoc is here if you need it (and you should use it!)


问:
CSS grid support for autoprefixer on webpack
I am using autoprefixer with postcss and webpack for a project.  I am also using CSS grid.  However, I've noticed when I build my code the ms prefixes for css grid does not work.

Here is my postcss.config.js which is working for things such as flexbox.

How do I enable CSS grid support?

```<code>module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}
</code>```

答:
By default, autoprefixer doesn't prefix grid properties.

See the autoprefixer documentation:

Autoprefixer has 4 features, which can be enabled or disabled by
  options:

...

grid: true will enable Grid Layout prefixes for IE.

The syntax for setting options would look something like:

```<code>const autoprefixer = require('autoprefixer');
const plugin = autoprefixer({ grid: true });
module.exports = { plugins: [ plugin ] }
</code>```

That being said, MDN has this to say about autoprefixer for grid properties:

The popular tool autoprefixer has been updated to support the -ms-
  grid version when you use the new grid properties. Unless your layout
  is very simple line-based placement, this is likely to cause you more
  problems that it solves. I would not suggest letting autoprefixer run
  on grid properties, and instead write a version using the IE version
  of Grid Layout, if it makes sense for you.

Additionally, Rachel Andrew wrote a thorough post on this topic

In that post she notes the following:

...even where similar properties exist in the two versions of the
  specification, the capabilities of the older spec and implementation
  are very different to the new one. This means you can’t simply run
  Autoprefixer and consider the job done.

Body:
I am using autoprefixer with postcss and webpack for a project.  I am also using CSS grid.  However, I've noticed when I build my code the ms prefixes for css grid does not work.

Here is my postcss.config.js which is working for things such as flexbox.

How do I enable CSS grid support?

module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}

Body:
By default, autoprefixer doesn't prefix grid properties.

See the autoprefixer documentation:

Autoprefixer has 4 features, which can be enabled or disabled by
  options:

...

grid: true will enable Grid Layout prefixes for IE.

The syntax for setting options would look something like:

const autoprefixer = require('autoprefixer');
const plugin = autoprefixer({ grid: true });
module.exports = { plugins: [ plugin ] }

That being said, MDN has this to say about autoprefixer for grid properties:

The popular tool autoprefixer has been updated to support the -ms-
  grid version when you use the new grid properties. Unless your layout
  is very simple line-based placement, this is likely to cause you more
  problems that it solves. I would not suggest letting autoprefixer run
  on grid properties, and instead write a version using the IE version
  of Grid Layout, if it makes sense for you.

Additionally, Rachel Andrew wrote a thorough post on this topic

In that post she notes the following:

...even where similar properties exist in the two versions of the
  specification, the capabilities of the older spec and implementation
  are very different to the new one. This means you can’t simply run
  Autoprefixer and consider the job done.


问:
How do you allow time entry in 2 formats in Django?
I want users to be able to entry time as decimals:

8.25

and as time:

8:15

What Django FormField should I use?

My thoughts are to make is a forms.CharField() as that would remove HTML restrictions and forms.TimeField() creates the same input.

What Validators should be applied to that formfield?

I'm not sure if I need to create a custom validator.

答:
There are many possible approaches and which is the best one depends on many other things in your project.

How do you save the time in your database? Do you use models.TimeField()? Do you denormalize - save the value also in models.DecimalField()?

Can you use JavaScript in the templates? If yes, I'd go with a dynamic form that allows user interaction. Maybe something like this:

```<code><label for="timeformat_switcher"
<input type="checkbox" id="timeformat_switcher">Enter a decimal value
</label>

<input type="time" id="time">
<input type="number" id="number"><!-- make it per default in CSS hidden -->
</code>```

When the user checks the checkbox hide the <input type="time"> with JavaScript and unhide the <input type="number">.
Use also JavaScript to convert the decimal value to time and send it to the server.

Body:
There are many possible approaches and which is the best one depends on many other things in your project.

How do you save the time in your database? Do you use models.TimeField()? Do you denormalize - save the value also in models.DecimalField()?

Can you use JavaScript in the templates? If yes, I'd go with a dynamic form that allows user interaction. Maybe something like this:

<label for="timeformat_switcher"
<input type="checkbox" id="timeformat_switcher">Enter a decimal value
</label>

<input type="time" id="time">
<input type="number" id="number"><!-- make it per default in CSS hidden -->

When the user checks the checkbox hide the <input type="time"> with JavaScript and unhide the <input type="number">.
Use also JavaScript to convert the decimal value to time and send it to the server.


问:
vue-select select the option based on ipaddress
I am trying to use this plugin https://github.com/sagalbot/vue-select

The issue with this is v-model gives the entire object unlike native select which is really a pain.

It is confirmed that the plugin does not support the option as outlined here https://github.com/sagalbot/vue-select/issues/122

The author suggests to use computed property for it. Here is the demo: http://jsbin.com/wedalog/8/edit?html,js,output

Here is the code:

```<code>Vue.component('v-select', VueSelect.VueSelect);

new Vue({
  el: '#app',
  data: {
    selected: null,
    options: [
    {
      "id": 1,
      "first_name": "Timothy Chavez",
      "ip_address": "20.153.187.10"
    },
    {
      "id": 2,
      "first_name": "Harold Armstrong",
      "ip_address": "55.156.218.75"
    },
    {
      "id": 3,
      "first_name": "Randy Black",
      "ip_address": "79.135.200.161"
    },
    {
      "id": 4,
      "first_name": "Joshua Phillips",
      "ip_address": "146.153.135.116"
    }
    ]
  },
  computed: {
    selectedIp() {
        return this.selected ? this.selected['ip_address'] : null
    }
  }
});
</code>```

and here is how it used in html:

```<code><v-select v-model="selected" label="first_name" :options="options"></v-select>
</code>```

It works but the answer is only valid while saving. Not sure what to do when loading? For example the IpAddress which I get from the server is 20.153.187.10 How would I then the appropriate option?

I am not sure why the author ignored this for something as basic as this.

Is there any more hack to make it work which would work for saving as well as loading?

答:
You will need to use getOptoinLabel and make sure you're using latest vue-select cause i'm not sure on which version that prop was added. So in reference to your example.You will add this to your code:

```<code>methods: {
   getLabel: function(val){
     if(typeof val === 'object'){
         return val.first_name;
     }else {
     return this.options.filter(function(option){
            return option.ip_address === val;
        })[0].first_name;
     }
   }
}
</code>```

And on the component instance add the prop :get-option-label="getLabel"

<v-select :get-option-label="getLabel" v-model="selected" label="first_name" :options="options"></v-select>

Note that the above function by default will have the argument val as the option you passed i.e in this case the v-model. So in your case it will be the ip address and all you need to do is then filter through your options the way you like and return the name.

Body:
I am trying to use this plugin https://github.com/sagalbot/vue-select

The issue with this is v-model gives the entire object unlike native select which is really a pain.

It is confirmed that the plugin does not support the option as outlined here https://github.com/sagalbot/vue-select/issues/122

The author suggests to use computed property for it. Here is the demo: http://jsbin.com/wedalog/8/edit?html,js,output

Here is the code:

Vue.component('v-select', VueSelect.VueSelect);

new Vue({
  el: '#app',
  data: {
    selected: null,
    options: [
    {
      "id": 1,
      "first_name": "Timothy Chavez",
      "ip_address": "20.153.187.10"
    },
    {
      "id": 2,
      "first_name": "Harold Armstrong",
      "ip_address": "55.156.218.75"
    },
    {
      "id": 3,
      "first_name": "Randy Black",
      "ip_address": "79.135.200.161"
    },
    {
      "id": 4,
      "first_name": "Joshua Phillips",
      "ip_address": "146.153.135.116"
    }
    ]
  },
  computed: {
    selectedIp() {
        return this.selected ? this.selected['ip_address'] : null
    }
  }
});

and here is how it used in html:

<v-select v-model="selected" label="first_name" :options="options"></v-select>

It works but the answer is only valid while saving. Not sure what to do when loading? For example the IpAddress which I get from the server is 20.153.187.10 How would I then the appropriate option?

I am not sure why the author ignored this for something as basic as this.

Is there any more hack to make it work which would work for saving as well as loading?

Body:
You will need to use getOptoinLabel and make sure you're using latest vue-select cause i'm not sure on which version that prop was added. So in reference to your example.You will add this to your code:

methods: {
   getLabel: function(val){
     if(typeof val === 'object'){
         return val.first_name;
     }else {
     return this.options.filter(function(option){
            return option.ip_address === val;
        })[0].first_name;
     }
   }
}

And on the component instance add the prop :get-option-label="getLabel"

<v-select :get-option-label="getLabel" v-model="selected" label="first_name" :options="options"></v-select>

Note that the above function by default will have the argument val as the option you passed i.e in this case the v-model. So in your case it will be the ip address and all you need to do is then filter through your options the way you like and return the name.


问:
Font size based on container
I have a Symbol to display in a ZxZ px container:

.symbol {
 width: 32px;
 height: 32px;
 border: 1px dotted;
 text-align: center;
}

.symbol>span {
color: darkred;
font-size: 3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Some Text
<div class="symbol"><span>☎</span></div>
</div></code>```

I would like to adjust the font-size always to fit the dotted square, whatever the Z size is...

Please read the question before making it duplicate! I don't need to fit it to viewport, or in any way the question is linked with responsiveness, mobile tablets etc.

I just need a letter to adjust to its container's rectangle/div.

答:
One of the solutions is to use JS.

Here is example:

$(function(){

  var box = $('.symbol');
  var boxWith = box.width();

  $('.symbol span').css('font-size',boxWith);

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.symbol {
  width: 50px;
  height: 50px;
  border: 1px dotted;
  text-align: center;
  display: flex;
  align-items: center;
}

.symbol>span {
  color: darkred;
  font-size: 3em;
}</code>```

Some Text

☎

```

Title: Font size based on container

Body:
I have a Symbol to display in a ZxZ px container:

.symbol {
 width: 32px;
 height: 32px;
 border: 1px dotted;
 text-align: center;
}

.symbol>span {
color: darkred;
font-size: 3em;
}

Some Text

☎

I would like to adjust the font-size always to fit the dotted square, whatever the Z size is...

Please read the question before making it duplicate! I don't need to fit it to viewport, or in any way the question is linked with responsiveness, mobile tablets etc.

I just need a letter to adjust to its container's rectangle/div.

Body:
One of the solutions is to use JS.

Here is example:

$(function(){

  var box = $('.symbol');
  var boxWith = box.width();

  $('.symbol span').css('font-size',boxWith);

});

.symbol {
  width: 50px;
  height: 50px;
  border: 1px dotted;
  text-align: center;
  display: flex;
  align-items: center;
}

.symbol>span {
  color: darkred;
  font-size: 3em;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Some Text
  <div class="symbol"><span>☎</span></div>
</div>


问:
Linux grep a command outcome into a variable
I want a command output stored in a variable.

A.sh

```<code>out=$(sqlldr userid=scott/tiger control=emp.ctl l grep "value i want")
echo $out
</code>```

But it is giving me empty output.

答:
Try to do this:

OUT=$(sqlldr userid=scott/tiger control=emp.ctl 2>&1 | grep "value i want" )
echo $OUT

In this case you also will have the error output, so if something is not working properly, you will know.

Body:
I want a command output stored in a variable.

A.sh

out=$(sqlldr userid=scott/tiger control=emp.ctl l grep "value i want")
echo $out

But it is giving me empty output.


问:
Cucumber/Capybara/Selenium - Setting the cookies
For my test case, I tried setting the cookies with following ways, But it is not getting set

```<code>1)browser = Capybara.current_session.driver.browser
  browser.manage.add_cookie :name => "xxx", :value => "cookie"

2)driver = Capybara.current_session.driver
  br = driver.browser.send(:bridge)
  br.addCookie({
    'name'    => "xxx",
    'domain'  => "localhost",
    'value'   => "cookie",
    'path'    => '/',
    'expires' => (Time.now + 100.years).to_i
  })
</code>```

Let me know if i miss anything or i have to do it in other way

答:
Capybara has to visit the website you're testing first. It is a required step before you can set any cookie.

This works:

```<code>visit '/'
browser = Capybara.current_session.driver.browser
browser.manage.add_cookie name: "name", value: "value"
</code>```

For best performance, either run this step just once, or see if the cookie is already set. Here is actual code that sets the cookieconsent cookie, which bypasses a cookie wall.

```<code>browser = page.driver.browser
unless browser.manage.cookie_named("cookieconsent")
  visit '/'
  browser.manage.add_cookie name: "cookieconsent", value: "dismiss"
end
</code>```

I am using page.driver to get the driver. It's the same thing as Capybara.current_session.driver.

Body:
For my test case, I tried setting the cookies with following ways, But it is not getting set

1)browser = Capybara.current_session.driver.browser
  browser.manage.add_cookie :name => "xxx", :value => "cookie"

2)driver = Capybara.current_session.driver
  br = driver.browser.send(:bridge)
  br.addCookie({
    'name'    => "xxx",
    'domain'  => "localhost",
    'value'   => "cookie",
    'path'    => '/',
    'expires' => (Time.now + 100.years).to_i
  })

Let me know if i miss anything or i have to do it in other way

Body:
Capybara has to visit the website you're testing first. It is a required step before you can set any cookie.

This works:

visit '/'
browser = Capybara.current_session.driver.browser
browser.manage.add_cookie name: "name", value: "value"

For best performance, either run this step just once, or see if the cookie is already set. Here is actual code that sets the cookieconsent cookie, which bypasses a cookie wall.

browser = page.driver.browser
unless browser.manage.cookie_named("cookieconsent")
  visit '/'
  browser.manage.add_cookie name: "cookieconsent", value: "dismiss"
end

I am using page.driver to get the driver. It's the same thing as Capybara.current_session.driver.


问:
AJAX POST data not being sent
On button click, i want to post the contents of the email text box. When i click the login button nothing happens.

My File dir:

Model/                <-- configuration.php is inside Model dir.

View/

Controller/

index.php             <-- calls the header, body, and footer php classes that are in the view dir

```<code>                    <!-- Modal body -->
                <div class="modal-body" style="padding:40px 50px;">
                    <form>
                        <div class="form-group">
                            <label for="usrname"><span class="glyphicon glyphicon-user"></span> Username</label>
                            <input type="text" class="form-control" name="email" id="email" placeholder="Enter email">
                        </div>
                        <div class="form-group">
                            <label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Password</label>
                            <input type="text" class="form-control" id="password" placeholder="Enter password">
                        </div>
                        <div class="checkbox">
                            <label><input type="checkbox" value="" checked>Remember me</label>
                        </div>
                        <button type="button" name="loginButton" id="loginButton" name="loginButton" class="btn btn-success btn-block">Login</button>
                    </form>
                </div>

                <!-- Modal footer -->
                <div class="modal-footer">
                    <p>Not a member? <a href="View/registration.php">Sign Up</a></p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        $("#loginButton").click(function() {
            $.ajax({
                type: "POST",
                url: "Model/configuration.php?action=login",
                data: "email=" + $("#email").val(),
                success: function (result) {
                    alert("result");
                }
            })
        })
    })
</script>
</code>```

PHP file

```<code><?php

if($_GET['action'] == "login") {
    print_r($_POST);
}

?>
</code>```

答:
```<code>$("#loginButton").click(function() {
            $.ajax({
                type: "POST",
                url: "Model/configuration.php?action=login",
                data: {email:$("#email").val()},
                success: function (result) {
                    alert("result");
                }
            })
        })
</code>```

Title: AJAX POST data not being sent

Body:
On button click, i want to post the contents of the email text box. When i click the login button nothing happens.

My File dir:

Model/                <-- configuration.php is inside Model dir.

View/

Controller/

index.php             <-- calls the header, body, and footer php classes that are in the view dir

                    <form>

                             Username
                            <input type="text" class="form-control" name="email" id="email" placeholder="Enter email">

                             Password
                            <input type="text" class="form-control" id="password" placeholder="Enter password">

                            <input type="checkbox" value="" checked>Remember me

                        <button type="button" name="loginButton" id="loginButton" name="loginButton" class="btn btn-success btn-block">Login</button>
                    </form>

Not a member? Sign Up

PHP file

<?php

if($_GET['action'] == "login") {
    print_r($_POST);
}

?>


问:
Does SSL protect documents sent over it?
If I understand correctly, SSL will protect (encrypt) HTTP transfer sent over it. But does this apply only to HTTP commands and responses?

If I GET a plain text file and someone intercepts my transaction, do they see plain text or encrypted text?

答: It applies to the metadata (commands and responses) and the data (the text file).  So it will be encrypted.  Keep in mind that SSL over HTTP is better known as HTTPS.</p>


问:
Android Studio - HorizontalScollView not moving
I am doing some Android Studio courses. As part of this I am working on a mock-up music player app. The app should be mostly XML as not functionality needs to be added.
I am trying to build e Discover (new music) screen, where you have media like views. To do this, I want to implement an HorizontalScrollView.
The problem is that my scroll view doesn't move. The xml code looks fine to me and I also googled this but did not find anything that would help my situation.

Would very much appreciate some clarification on this. Here is my code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alexcojocaru.vibes.Discover">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5px"
            android:text="Recommendations"
            android:textColor="#cc3300" />

        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:padding="5px"
            android:scrollbars="horizontal">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="5px"
                        android:src="@drawable/bear" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="My Name is Bear"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Nahko"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/omam" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Beneath The Skin"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:id="@+id/textView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Of Monsters and Men"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/jmj" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Essential Recollection"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Jean-Michel Jarre"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/ram" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Random Access Memories"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Daft Punk"
                        android:textSize="10sp" />

                </LinearLayout>

            </LinearLayout>

        </HorizontalScrollView>

    </LinearLayout>

</LinearLayout>
</code>```

答:
I ran the above code and it works by default.
I think the problem is that if the layout fits fully on screen then you might not be able to see the scroll.
Suggesting to test on a smaller screen.

P.S:Not enough rep for comments.

Body:
I am doing some Android Studio courses. As part of this I am working on a mock-up music player app. The app should be mostly XML as not functionality needs to be added.
I am trying to build e Discover (new music) screen, where you have media like views. To do this, I want to implement an HorizontalScrollView.
The problem is that my scroll view doesn't move. The xml code looks fine to me and I also googled this but did not find anything that would help my situation.

Would very much appreciate some clarification on this. Here is my code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alexcojocaru.vibes.Discover">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5px"
            android:text="Recommendations"
            android:textColor="#cc3300" />

        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:padding="5px"
            android:scrollbars="horizontal">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="5px"
                        android:src="@drawable/bear" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="My Name is Bear"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Nahko"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/omam" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Beneath The Skin"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:id="@+id/textView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Of Monsters and Men"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/jmj" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Essential Recollection"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Jean-Michel Jarre"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/ram" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Random Access Memories"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Daft Punk"
                        android:textSize="10sp" />

                </LinearLayout>

            </LinearLayout>

        </HorizontalScrollView>

    </LinearLayout>

</LinearLayout>


问:
MVC4: HTML5 boolean attributes rendered with True/False value
I'm trying to render a radiobutton with some boolean attributes (required and disabled) using:

```<code>@Html.RadioButton("radio-name","false", new { id="test", required=Model.BooleanValue})
</code>```

and

```<code><input type="radio" name="radio-name" id="radio-name-no" value="false" class="radio" @if (!Model.BooleanValue) { <text>required</text> } disabled="@Model.BooleanValue" />
</code>```

But the output is this:

```<code><input id="test" name="radio-name" required="False" value="false" type="radio">
</code>```

and

```<code><input name="radio-name" id="radio-name-no" value="false" class="radio" disabled="True" type="radio">
</code>```

MVC4 should render the boolean attributes as per HTML5 specs, so why it's outputting disabled="True" (or False) instead of disabled="disabled" or disabled (or nothing at all if the BooleanValue property is false)?

答:
You can include conditionally rendered attributes like this:

<input
    type="radio"
    required="@(!Model.BooleanValue)"
    disabled="@Model.BooleanValue" />
```

The solution was pretty strange. While doing some tests, I put an @if in the HTML input tag. This if was used to show the required attribute. After this @if, I put the disabled="@Model.BooleanValue" attribute.

It seems that this order disrupted the expected behaviour. Placing the disabled attribute before the @if solved the problem (later I have deleted the @if and converted it to required="@(!Model.BooleanValue)").

Body:
I'm trying to render a radiobutton with some boolean attributes (required and disabled) using:

@Html.RadioButton("radio-name","false", new { id="test", required=Model.BooleanValue})

and

<input type="radio" name="radio-name" id="radio-name-no" value="false" class="radio" @if (!Model.BooleanValue) { <text>required</text> } disabled="@Model.BooleanValue" />

But the output is this:

<input id="test" name="radio-name" required="False" value="false" type="radio">

and

<input name="radio-name" id="radio-name-no" value="false" class="radio" disabled="True" type="radio">

MVC4 should render the boolean attributes as per HTML5 specs, so why it's outputting disabled="True" (or False) instead of disabled="disabled" or disabled (or nothing at all if the BooleanValue property is false)?

Body:
You can include conditionally rendered attributes like this:

<input
    type="radio"
    required="@(!Model.BooleanValue)"
    disabled="@Model.BooleanValue" />

The solution was pretty strange. While doing some tests, I put an @if in the HTML input tag. This if was used to show the required attribute. After this @if, I put the disabled="@Model.BooleanValue" attribute.

It seems that this order disrupted the expected behaviour. Placing the disabled attribute before the @if solved the problem (later I have deleted the @if and converted it to required="@(!Model.BooleanValue)").

ContentLicense: CC BY-SA 4.0


问:
How to make image fit screen in Godot
I am new in godot engine and I am trying to make mobile game (portrait mode only). I would like to make background image fit screen size. How do I do that? Do i have to import images with specific sizes and implement them all for various screens? If I import image to big, it will just cut out parts that don't fit screen.
Also, while developing, which width and height values should I use for these purposes?</p>

答:
Working with different screen sizes is always a bit complicated. Especially for mobile games due to the different screen sizes, resolutions and aspect ratios.

The easiest way I can think of, is scaling of the viewport. Keep in mind that your root node is always a viewport. In Godot you can stretch the viewport in the project settings (you have to enable the stretch mode option). You can find a nice little tutorial here.

However, viewport stretching might result in an image distortion or black bars at the edges.

Another elegant approach would be to create an image that is larger than you viewport and just define an area that has to be shown on every device no matter whats the resolution. Here is someone showing what I am meaning.

I can't really answer your second question about the optimal width and height but I would look for the most typical mobile phone resolutions and ratios and go with that settings. In the end you probably should start with using the width and height ratio of the phone you want to use for testing and debugging.

Hope that helps.

Title: How to make image fit screen in Godot


问:
Send errors from Pure Data's terminal window?
I'm new to working with Pure Data. I can send messages from Python to Pure Data but I'm interested in trying to get error messages back. There are error messages in Pure Data's terminal window. Is it possible to get at these with a Pure Data object? Or is there another mechanism I can use?</p>

答: Perhaps this answer by umläute to a related question could be helpful to you: use the -stderr startup flag in Pd and capture the stderrin your Python script.


问:
How to replace relective method access by Java 1.8 functions?
Problem: We need to get a (String) key for different classes of objects.
For expendability we want to configure the Method to use to get the key String – instead of implementing many if-else with intanceOf…

Naive solution (with example data) is:

```<code>public static String getKey(Object object, Map<Class<?>, Method> keySources) {
    Method source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    try {
        return (String) source.invoke(object);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException("Error at 'invoke': " + e.getMessage(), e);
    }
}

public static void main(String[] args) {
    Map<Class<?>, Method> keySources = new HashMap<>();

    try {
        keySources.put(String.class, String.class.getMethod("toString"));
        keySources.put(Thread.class, Thread.class.getMethod("getName"));
    } catch (NoSuchMethodException | SecurityException e) {
        throw new RuntimeException("Error at 'getMethod': " + e.getMessage(), e);
    }

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}
</code>```

Desired solution would be like:

```<code>public static String getKey(Object object, Map<Class<?>, Function<Object, String>> keySources) {
    Function<Object, String> source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    return source.apply(object);
}

public static void main(String[] args) {
    Map<Class<?>, Function<Object, String>> keySources = new HashMap<>();

    keySources.put(String.class, String::toString);
    keySources.put(Thread.class, Thread::getName);

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}
</code>```

But String::toString is giving compilation error: The type String does not define toString(Object) that is applicable here

Constraints: We cannot modify the classes since they were generated.

答:
Function take one parameter, which does not match the signature.

Try using Callable which take no parameter and return a value

Body:
Problem: We need to get a (String) key for different classes of objects.
For expendability we want to configure the Method to use to get the key String – instead of implementing many if-else with intanceOf…

Naive solution (with example data) is:

public static String getKey(Object object, Map<Class<?>, Method> keySources) {
    Method source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    try {
        return (String) source.invoke(object);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException("Error at 'invoke': " + e.getMessage(), e);
    }
}

public static void main(String[] args) {
    Map<Class<?>, Method> keySources = new HashMap<>();

    try {
        keySources.put(String.class, String.class.getMethod("toString"));
        keySources.put(Thread.class, Thread.class.getMethod("getName"));
    } catch (NoSuchMethodException | SecurityException e) {
        throw new RuntimeException("Error at 'getMethod': " + e.getMessage(), e);
    }

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}

Desired solution would be like:

public static String getKey(Object object, Map<Class<?>, Function<Object, String>> keySources) {
    Function<Object, String> source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    return source.apply(object);
}

public static void main(String[] args) {
    Map<Class<?>, Function<Object, String>> keySources = new HashMap<>();

    keySources.put(String.class, String::toString);
    keySources.put(Thread.class, Thread::getName);

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}

But String::toString is giving compilation error: The type String does not define toString(Object) that is applicable here

Constraints: We cannot modify the classes since they were generated.


问:
Passing a list to a JSON file in C#
I want to write to and read from a JSON file.

I use the Newtonsoft.Json package

I have a list containing an object

```<code>private List<LinkElement> links = new List<LinkElement>();
</code>```

the object structure is

```<code>public class LinkElement
{
public LinkElement(string link, string key, string description, string type, string[] tags)
{
       Link = link;
       Description = description;
       Type = type;
       Tags = tags;
}

public string Link { get; set; }

public string Key { get; set; }

public string Description { get; set; }

public string Type { get; set; }

public string[] Tags { get; set; }
}
</code>```

So when reading from the file I would go for

```<code>string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<List<LinkElement>>(data);
</code>```

and when writing to the file I would go for

```<code>string newData = JsonConvert.SerializeObject(links);
File.WriteAllText(path, newData);
</code>```

but it seems lists are not the right element to take. Dictionaries would be possible.

Could someone help me out passing the list to the JSON file?

答:
You need to extract the Key from LinkElement and use it as the key value in a Dictionary, like this:

```<code>public class LinkElement
{
  public string Link { get; set; }
  public string Description { get; set; }
  public string Type { get; set; }
  public string[] Tags { get; set; }
}

private Dictionary<string, LinkElement> links = new Dictionary<string, LinkElement>();
</code>```

To store items in links, use this:

```<code>links.Add(key1, linkElement1);
links.Add(key2, linkElement2);
</code>```

(Or if each LinkElement needs to know its own Key, then leave it in the class and use this to add: links.Add(linkElement1.Key, linkElement1); etc)

To write it, your code stays the same.

To read it, your code changes a little:

```<code>string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<Dictionary<string, LinkElement>>(data);
</code>```

Title: Passing a list to a JSON file in C#

Body:
I want to write to and read from a JSON file.

I use the Newtonsoft.Json package

I have a list containing an object

private List<LinkElement> links = new List<LinkElement>();

the object structure is

public class LinkElement
{
public LinkElement(string link, string key, string description, string type, string[] tags)
{
       Link = link;
       Description = description;
       Type = type;
       Tags = tags;
}

public string Link { get; set; }

public string Key { get; set; }

public string Description { get; set; }

public string Type { get; set; }

public string[] Tags { get; set; }
}

So when reading from the file I would go for

string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<List<LinkElement>>(data);

and when writing to the file I would go for

string newData = JsonConvert.SerializeObject(links);
File.WriteAllText(path, newData);

but it seems lists are not the right element to take. Dictionaries would be possible.

Could someone help me out passing the list to the JSON file?

Body:
You need to extract the Key from LinkElement and use it as the key value in a Dictionary, like this:

public class LinkElement
{
  public string Link { get; set; }
  public string Description { get; set; }
  public string Type { get; set; }
  public string[] Tags { get; set; }
}

private Dictionary<string, LinkElement> links = new Dictionary<string, LinkElement>();

To store items in links, use this:

links.Add(key1, linkElement1);
links.Add(key2, linkElement2);

(Or if each LinkElement needs to know its own Key, then leave it in the class and use this to add: links.Add(linkElement1.Key, linkElement1); etc)

To write it, your code stays the same.

To read it, your code changes a little:

string data = File.ReadAllText(path);
links = JsonConvert.DeserializeObject<Dictionary<string, LinkElement>>(data);


问:
CSS hover at level row
At this table, I apply a CSS
example from here
http://gridviewscroll.aspcity.idv.tw/Demo.aspx
and the example
https://github.com/twlikol/GridViewScroll

```<code><table cellspacing="0" id="gvMain2" style="width: 100%; border-collapse: collapse;">
    <tr class="GridViewScrollHeader">
        <th>StandardCost</th>
        <th>ListPrice</th>
        <th>SafetyStockLevel</th>
        <th>SellStartDate</th>
        <th>SellEndDate</th>
        <th>ModifiedDate</th>
        <th>ProductID</th>
        <th>Name</th>
        <th>Number</th>
        <th>ReorderPoint</th>
        <th>Weight</th>
    </tr>
    <tr class="GridViewScrollItem">
        <td>747</td>
        <td>HL Mountain Frame - Black, 38</td>
        <td>FR-M94B-38</td>
        <td>375</td>
        <td>2.68</td>
        <td>739.0410</td>
        <td>1349.6000</td>
        <td>500</td>
        <td>7/1/2001 12:00:00 AM</td>
        <td> </td>
        <td>3/11/2004 10:01:36 AM</td>
    </tr>
</table>
</code>```

CSS section Header ok assign the color

```<code>.GridViewScrollHeader TH,
.GridViewScrollHeader TD {
    padding: 10px;
    font-weight: normal;
    white-space: nowrap;
    border-right: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
    background-color: cornflowerblue;
    color: palegoldenrod;
    text-align: left;
    vertical-align: bottom;
    cursor:default;
}
</code>```

CSS section Item at level TD assign the color and border, and the cell change color when the event TD:hover is triggered

```<code>.GridViewScrollItem TD {
    padding: 10px;
    white-space: nowrap;
    border-right: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
    /*background-color: lemonchiffon;*/
    color: blue;
    background-color: gray;
    /*cursor: pointer;*/
}

/* this work and change color at cell level */
.GridViewScrollItem TD:hover {
     background-color: yellow;
    cursor: pointer;
}
</code>```

CSS hover at level row ??
at the line, TR level does not trigger the hover event, as if there were no instructions, certainly my error, even though it seems correct to refer to TR.

```<code>/* this section not have effect
- the cursor not change form
- the background color not change
*/
.GridViewScrollItem TR {
   background-color: #b8d1f3;
}

.GridViewScrollItem TR:hover {
   /* background-color: #00C080FF; */
    background-color: yellow;
    cursor:pointer;
}
</code>```

答:
The row color does change, but under the colored TD. So apply the effect directly to the column with:

```<code>.GridViewScrollItem:hover TD {
   /* background-color: #00C080FF; */
    background-color: yellow;
    cursor:pointer;
}
</code>```

In addition, .GridViewScrollItem is the actual TR you mention, so basically your original CSS rule said:

```<code>tr tr:hover {};
</code>```

Working codepen example:
https://codepen.io/robertspier/pen/LOjMNW

Title: CSS hover at level row

Body:
At this table, I apply a CSS
example from here
http://gridviewscroll.aspcity.idv.tw/Demo.aspx
and the example
https://github.com/twlikol/GridViewScroll

        StandardCost
        ListPrice
        SafetyStockLevel
        SellStartDate
        SellEndDate
        ModifiedDate
        ProductID
        Name
        Number
        ReorderPoint
        Weight

        747
        HL Mountain Frame - Black, 38
        FR-M94B-38
        375
        2.68
        739.0410
        1349.6000
        500
        7/1/2001 12:00:00 AM

        3/11/2004 10:01:36 AM

CSS section Header ok assign the color

.GridViewScrollHeader TH,
.GridViewScrollHeader TD {
    padding: 10px;
    font-weight: normal;
    white-space: nowrap;
    border-right: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
    background-color: cornflowerblue;
    color: palegoldenrod;
    text-align: left;
    vertical-align: bottom;
    cursor:default;
}

CSS section Item at level TD assign the color and border, and the cell change color when the event TD:hover is triggered

.GridViewScrollItem TD {
    padding: 10px;
    white-space: nowrap;
    border-right: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
    /*background-color: lemonchiffon;*/
    color: blue;
    background-color: gray;
    /*cursor: pointer;*/
}

/* this work and change color at cell level */
.GridViewScrollItem TD:hover {
     background-color: yellow;
    cursor: pointer;
}

CSS hover at level row ??
at the line, TR level does not trigger the hover event, as if there were no instructions, certainly my error, even though it seems correct to refer to TR.

/* this section not have effect
- the cursor not change form
- the background color not change
*/
.GridViewScrollItem TR {
   background-color: #b8d1f3;
}

.GridViewScrollItem TR:hover {
   /* background-color: #00C080FF; */
    background-color: yellow;
    cursor:pointer;
}

Body:
The row color does change, but under the colored TD. So apply the effect directly to the column with:

.GridViewScrollItem:hover TD {
   /* background-color: #00C080FF; */
    background-color: yellow;
    cursor:pointer;
}

In addition, .GridViewScrollItem is the actual TR you mention, so basically your original CSS rule said:

tr tr:hover {};

Working codepen example:
https://codepen.io/robertspier/pen/LOjMNW


答: SSL (otherwise known as TLS - "Transport Layer Security"), protects everything at the socket-level. That is, everything in a TCP packet is encrypted, meaning that you essentially have an encrypted bytestream between two hosts. So, the plain text transmission will be encrypted.</p>

Title: Does SSL protect documents sent over it?

Body:
If I understand correctly, SSL will protect (encrypt) HTTP transfer sent over it. But does this apply only to HTTP commands and responses?

If I GET a plain text file and someone intercepts my transaction, do they see plain text or encrypted text?


问:
Angular - Using a component across multiple modules
What I'm using

Angular

What I'm trying to do

I have a loading component I want to reuse across multiple modules

What I've done

I've created a new module called 'loading-overlay'

Inside this module I export the overlay component

I add this module to app.module

When adding the component to multiple modules I receive the following error:

Type LoadingOverlayComponent is part of the declarations of 2 modules: LoadingOverlayModule and ProjectsModule! Please consider moving LoadingOverlayComponent to a higher module that imports LoadingOverlayModule and ProjectsModule. You can also create a new NgModule that exports and includes LoadingOverlayComponent then import that NgModule in LoadingOverlayModule and ProjectsModule.

I've tried removing it from app.module and importing it into the other modules I need without much luck. I must be missing some obvious.

Overlay Module

// Modules
import { NgModule } from '@angular/core';

// Components
import { LoadingOverlayComponent } from './loading-overlay.component';

@NgModule({
  declarations: [
    LoadingOverlayComponent,
  ],

  imports: [

  ],

  exports: [
    LoadingOverlayComponent
  ],

  providers: [ ],

})

export class LoadingOverlayModule { }
```

<p><strong>App Module</strong></p>

<pre class="lang-js prettyprint-override"><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Routing
import { AppRouting } from './routing/app-routing';

// Modules
import { ProjectsModule } from './projects/projects.module';
import { UserModule } from './user/user.module';
import { LoadingOverlayModule } from './loading-overlay/loading-overlay.module';

// Services / Providers
import { AuthService } from './user/auth.service'

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRouting,
    LoadingOverlayModule
  ],
  providers: [
    AuthService,

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Project Module

// Modules
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LoadingOverlayModule } from '../loading-overlay/loading-overlay.module';

import { LoadingOverlayComponent } from '../loading-overlay/loading-overlay.component';

@NgModule({
  declarations: [

    LoadingOverlayComponent
  ],

  imports: [
    CommonModule,
    RouterModule,

    LoadingOverlayModule
  ],

  providers: [ ],

})

export class ProjectsModule { }
```

Any help pointing out what I've stupidly missed would be greatly appreciated.

答:
LoadingOverlayModule is shared module. It has its own component. Now to use its component you need to import LoadingOverlayModule into Project module. Remove LoadingOverlayComponent from project module's declarations.

You will need another component (say ProjectComponent) for Project Module declaration. As shared module is imported into you project module you can directly use overlay component in ProjectComponent template, using selector. Hope this helps.

Body:
What I'm using

Angular

What I'm trying to do

I have a loading component I want to reuse across multiple modules

What I've done

I've created a new module called 'loading-overlay'

Inside this module I export the overlay component

I add this module to app.module

When adding the component to multiple modules I receive the following error:

Type LoadingOverlayComponent is part of the declarations of 2 modules: LoadingOverlayModule and ProjectsModule! Please consider moving LoadingOverlayComponent to a higher module that imports LoadingOverlayModule and ProjectsModule. You can also create a new NgModule that exports and includes LoadingOverlayComponent then import that NgModule in LoadingOverlayModule and ProjectsModule.

I've tried removing it from app.module and importing it into the other modules I need without much luck. I must be missing some obvious.

Overlay Module

// Modules
import { NgModule } from '@angular/core';

// Components
import { LoadingOverlayComponent } from './loading-overlay.component';

@NgModule({
  declarations: [
    LoadingOverlayComponent,
  ],

  imports: [

  ],

  exports: [
    LoadingOverlayComponent
  ],

  providers: [ ],

})

export class LoadingOverlayModule { }

App Module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// Routing
import { AppRouting } from './routing/app-routing';

// Modules
import { ProjectsModule } from './projects/projects.module';
import { UserModule } from './user/user.module';
import { LoadingOverlayModule } from './loading-overlay/loading-overlay.module';

// Services / Providers
import { AuthService } from './user/auth.service'

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRouting,
    LoadingOverlayModule
  ],
  providers: [
    AuthService,

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Project Module

// Modules
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LoadingOverlayModule } from '../loading-overlay/loading-overlay.module';

import { LoadingOverlayComponent } from '../loading-overlay/loading-overlay.component';

@NgModule({
  declarations: [

    LoadingOverlayComponent
  ],

  imports: [
    CommonModule,
    RouterModule,

    LoadingOverlayModule
  ],

  providers: [ ],

})

export class ProjectsModule { }

Any help pointing out what I've stupidly missed would be greatly appreciated.


问:
Codeigniter callback validation problems
I want to create a callback function that is used during validation to check if the username / email address is already in the database... problem is I just cant seem to get it working

So this is the callback function:

```<code>function callback_username_available($username)
{
    if($this->user_model->username_available($username))
    {
        return TRUE;
    }
    else
    {
        $this->form_validation->set_message('username_available', 'ERROR');
        return FALSE;
    }
}
</code>```

And this is the validation logic :

```<code>// setup form validation rules
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'callback_username_available');

if($this->form_validation->run() == FALSE)
{
    // validation errors
}
else
{
    // no validation errors
}
</code>```

I have been at this for hours and have no idea what i'm doing wrong... both functions are in the same controller and all other standard validation rules work just fine.

Even when i set the callback function to just return FALSE, it still validates the username.

Any ideas guys... its driving me up the wall at the moment :S

答:
```<code>// setup form validation rules
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'callback_callback_username_available');

if($this->form_validation->run() == FALSE)
{
    // validation errors
}
else
{
    // no validation errors
}
</code>```

Body:
I want to create a callback function that is used during validation to check if the username / email address is already in the database... problem is I just cant seem to get it working

So this is the callback function:

function callback_username_available($username)
{
    if($this->user_model->username_available($username))
    {
        return TRUE;
    }
    else
    {
        $this->form_validation->set_message('username_available', 'ERROR');
        return FALSE;
    }
}

And this is the validation logic :

// setup form validation rules
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'callback_username_available');

if($this->form_validation->run() == FALSE)
{
    // validation errors
}
else
{
    // no validation errors
}

I have been at this for hours and have no idea what i'm doing wrong... both functions are in the same controller and all other standard validation rules work just fine.

Even when i set the callback function to just return FALSE, it still validates the username.

Any ideas guys... its driving me up the wall at the moment :S